Files
bot.py
commands.py
config.json
dashboard.py
database.py
README.md
requirements.txt
security.py
Code
8 826
bot.py
from __future__ import annotations
import json
import logging
import os
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from commands import COMMAND_NAMES, register_commands
from dashboard import DashboardServer
from database import Database
from security import AntiRaid
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
logger = logging.getLogger("erlc-bot")
def load_config() -> dict:
with open("config.json", "r", encoding="utf-8") as file:
return json.load(file)
class ERLCBot(commands.Bot):
def __init__(self):
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
super().__init__(command_prefix="!", intents=intents, help_command=None)
self.database = Database(os.getenv("DATABASE_PATH", "data/erlc_bot.db"))
self.config = load_config()
self.started_at = discord.utils.utcnow()
async def setup_hook(self) -> None:
await self.database.initialize()
register_commands(self, self.database)
await self.add_cog(AntiRaid(self, self.database, self.config))
dev_guild_id = os.getenv("DEV_GUILD_ID", "").strip()
if dev_guild_id.isdigit():
guild = discord.Object(id=int(dev_guild_id))
self.tree.copy_global_to(guild=guild)
synced = await self.tree.sync(guild=guild)
logger.info("Synced %d commands to development guild", len(synced))
else:
synced = await self.tree.sync()
logger.info("Synced %d global commands", len(synced))
dashboard_config = self.config.get("dashboard", {})
if dashboard_config.get("enabled", True):
DashboardServer(
self,
self.database.path,
os.getenv("DASHBOARD_SECRET", ""),
os.getenv("DASHBOARD_HOST", "0.0.0.0"),
int(os.getenv("DASHBOARD_PORT", "8080")),
).start()
bot = ERLCBot()
@bot.event
async def on_ready():
logger.info("Logged in as %s; serving %d guild(s) with %d commands", bot.user, len(bot.guilds), len(COMMAND_NAMES))
@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
if isinstance(error, app_commands.CommandOnCooldown):
message = f"Try again in {error.retry_after:.1f} seconds."
elif isinstance(error, app_commands.TransformerError):
message = "One of the supplied values is invalid."
elif isinstance(error, app_commands.MissingPermissions):
message = "You do not have permission to use this command."
else:
logger.exception("Slash command failed", exc_info=error)
message = "Something went wrong while running that command."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("DISCORD_TOKEN is missing. Copy .env.example to .env and set it.")
bot.run(token)