Files
cogs
dashboard
bot.py
config.py
database.py
requirements.txt
Code
32 4,191
bot.py
import discord
from discord.ext import commands
import os
import asyncio
import threading
import logging
import datetime
from dotenv import load_dotenv
from database import Database
import config
load_dotenv()
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
datefmt="%Y-%m-%d %H:%M:%S",
)
logger = logging.getLogger("CorlBot")
class CorlBot(commands.Bot):
def __init__(self):
intents = discord.Intents.all()
super().__init__(
command_prefix=self._get_prefix,
intents=intents,
help_command=None,
case_insensitive=True,
)
self.db = Database()
self.start_time: datetime.datetime = None
async def _get_prefix(self, bot, message: discord.Message):
if not message.guild:
return config.DEFAULT_PREFIX
prefix = await self.db.get_prefix(message.guild.id)
return commands.when_mentioned_or(prefix)(bot, message)
async def setup_hook(self):
await self.db.initialize()
for cog in config.COGS:
try:
await self.load_extension(cog)
logger.info(f"Loaded: {cog}")
except Exception as e:
logger.error(f"Failed to load {cog}: {e}")
await self.tree.sync()
logger.info("Slash commands synced.")
async def on_ready(self):
self.start_time = datetime.datetime.utcnow()
logger.info(f"Ready: {self.user} (ID: {self.user.id}) | {len(self.guilds)} guilds")
await self.change_presence(
activity=discord.Activity(
type=discord.ActivityType.watching,
name=f"{len(self.guilds)} servers | !help",
)
)
self._start_dashboard()
def _start_dashboard(self):
from dashboard.app import create_app, set_bot
app = create_app()
set_bot(self)
def run():
app.run(
host="0.0.0.0",
port=config.DASHBOARD_PORT,
debug=False,
use_reloader=False,
)
t = threading.Thread(target=run, daemon=True, name="dashboard")
t.start()
logger.info(f"Dashboard running on port {config.DASHBOARD_PORT}")
async def on_guild_join(self, guild: discord.Guild):
await self.db.ensure_guild(guild.id)
logger.info(f"Joined guild: {guild.name} ({guild.id})")
async def on_command_error(self, ctx: commands.Context, error):
if isinstance(error, commands.CommandNotFound):
cmd = await self.db.get_custom_command(ctx.guild.id if ctx.guild else 0, ctx.invoked_with)
if cmd:
await ctx.send(cmd)
return
embed = discord.Embed(color=config.ERROR_COLOR)
if isinstance(error, commands.MissingPermissions):
embed.description = f"โ You need these permissions: `{'`, `'.join(error.missing_permissions)}`"
elif isinstance(error, commands.BotMissingPermissions):
embed.description = f"โ I need these permissions: `{'`, `'.join(error.missing_permissions)}`"
elif isinstance(error, commands.MissingRequiredArgument):
embed.description = f"โ Missing argument: `{error.param.name}`\nUsage: `{ctx.prefix}{ctx.command.qualified_name} {ctx.command.signature}`"
elif isinstance(error, commands.BadArgument):
embed.description = f"โ Invalid argument: {error}"
elif isinstance(error, commands.CheckFailure):
embed.description = "โ You don't have permission to use this command."
elif isinstance(error, commands.CommandOnCooldown):
embed.description = f"โณ Command on cooldown. Try again in `{error.retry_after:.1f}s`."
else:
logger.error(f"Unhandled error in {ctx.command}: {error}", exc_info=error)
return
await ctx.send(embed=embed, delete_after=8)
bot = CorlBot()
if __name__ == "__main__":
if not config.DISCORD_TOKEN:
logger.error("DISCORD_TOKEN is not set. Check your .env file.")
exit(1)
bot.run(config.DISCORD_TOKEN, log_handler=None)