Files
.gitignore
bot.py
cogs_erlc.py
cogs_help.py
cogs_setup.py
cogs_staff.py
config.py
database.py
erlc_api.py
permissions.py
README.md
requirements.txt
views.py
Code
13 1,055
bot.py
from __future__ import annotations
import logging
import time
import discord
from discord.ext import commands
from config import DATABASE_PATH, DISCORD_TOKEN, ENCRYPTION_KEY, PREFIX
from database import Database
from erlc_api import ERLCClient
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("erlc-management")
class ManagementBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
super().__init__(command_prefix=PREFIX, intents=intents, help_command=None)
self.db = Database(DATABASE_PATH, ENCRYPTION_KEY)
self.rate_limit: dict[tuple[int, int], float] = {}
async def setup_hook(self) -> None:
await self.db.connect()
from cogs_erlc import ERLCCog
from cogs_help import HelpCog
from cogs_setup import SetupCog
from cogs_staff import StaffCog
await self.add_cog(SetupCog(self))
await self.add_cog(ERLCCog(self))
await self.add_cog(StaffCog(self))
await self.add_cog(HelpCog(self))
async def client_for(self, guild_id: int) -> ERLCClient | None:
key = await self.db.get_api_key(guild_id)
return ERLCClient(key) if key else None
async def close(self) -> None:
await self.db.close()
await super().close()
bot = ManagementBot()
@bot.check
async def command_rate_limit(ctx: commands.Context) -> bool:
if not ctx.guild:
return True
key = (ctx.guild.id, ctx.author.id)
now = time.monotonic()
previous = bot.rate_limit.get(key, 0)
if now - previous < 2:
raise commands.CommandOnCooldown(commands.Cooldown(1, 2), 2 - (now - previous), commands.BucketType.user)
bot.rate_limit[key] = now
return True
@bot.event
async def on_ready():
logger.info("Logged in as %s", bot.user)
@bot.event
async def on_command_error(ctx: commands.Context, error: commands.CommandError):
if isinstance(error, commands.CommandNotFound):
return
if isinstance(error, commands.CommandOnCooldown):
await ctx.send(f"Please wait {error.retry_after:.1f}s before using another command.", delete_after=5)
return
if isinstance(error, commands.CheckFailure):
await ctx.send(str(error) or "You do not have permission to use that command.", delete_after=8)
return
if isinstance(error, commands.MissingRequiredArgument):
await ctx.send(f"Missing argument: `{error.param.name}`. Use `-help` for command categories.", delete_after=8)
return
if isinstance(error, commands.BadArgument):
await ctx.send(str(error) or "One of the arguments is invalid.", delete_after=8)
return
logger.error("Command error in %s", ctx.command, exc_info=error)
await ctx.send("An unexpected error occurred while processing that command.", delete_after=8)
bot.run(DISCORD_TOKEN)