discord-bot-nlp/src/bot.py

96 lines
3 KiB
Python
Raw Normal View History

2025-07-09 13:03:05 +10:00
# General libraries needed
import os
import asyncio
# Discord libraries needed
import discord
from discord.ext import commands
# Helper that identifies intents
from helpers.intent import match_intent
# Helper for logging
from helpers.logger import get_logger
# Initiate logger
logger = get_logger("bxt")
class DiscordBot:
def __init__(self):
# Load logger
self.logger = logger
self.logger.info("🚀 Logger successfully initialized")
# Get log level desired
self.LOG_LEVEL = os.environ.get('LOG_LEVEL', 'DEBUG').upper()
self.DISCORD_TOKEN = os.environ.get('DISCORD_TOKEN')
self.REDIS_SERVER = os.environ.get('REDIS_SERVER', 'localhost')
self.REDIS_PORT = os.environ.get('REDIS_PORT', '6379')
self.REDIS_CONF_DB = os.environ.get('REDIS_CONF_DB', '1')
self.REDIS_DATA_DB = os.environ.get('REDIS_DATA_DB', '0')
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.members = True
intents.voice_states = True
self.bot = commands.Bot(command_prefix="!", intents=intents)
# Register events
self.bot.event(self.on_message)
self.bot.event(self.on_ready)
async def on_message(self, message):
if message.author == self.bot.user:
return
bot_mention = f"<@{self.bot.user.id}>"
content = message.content.strip()
# Only handle if in guild and message mentions bot at start or end,
# or if it's a DM (no guild)
if message.guild and not (content.startswith(bot_mention) or content.endswith(bot_mention)):
return
# Remove bot mention from content
content = content.replace(bot_mention, "").strip()
# Split message content into lines and process each
lines = [line.strip() for line in content.split('\n') if line.strip()]
ctx = await self.bot.get_context(message)
handled_any = False
for line in lines:
func, doc = match_intent(line)
if func:
handled_any = True
try:
await func(ctx, doc)
except Exception as e:
self.logger.debug(f"Error running intent handler: {e}")
else:
await message.channel.send(f"Sorry, I didn't understand that: `{line}`")
await self.bot.process_commands(message)
async def on_ready(self):
self.logger.info(f"Logged in as {self.bot.user} (ID: {self.bot.user.id})")
async def start(self):
# Load cogs (adjust the names/paths to your setup)
await self.bot.load_extension("cogs.cogcontrol")
await self.bot.load_extension("cogs.admin")
await self.bot.load_extension("cogs.guild")
await self.bot.load_extension("cogs.autovoicechannel")
await self.bot.start(self.DISCORD_TOKEN)
if __name__ == '__main__':
discord_bot = DiscordBot()
asyncio.run(discord_bot.start())