Files
cogs
.gitignore
bot.py
requirements.txt
Code
5 485
bot.py
import logging
import os
from pathlib import Path
import aiosqlite
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import dotenv_values, load_dotenv
from cogs.moderation import Moderation
BASE_DIR = Path(__file__).resolve().parent
ENV_FILE = BASE_DIR / ".env"
load_dotenv(dotenv_path=ENV_FILE, override=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("moderation_bot")
class ModerationBot(commands.Bot):
def __init__(self) -> None:
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
super().__init__(
command_prefix=os.getenv("COMMAND_PREFIX", "!"),
intents=intents,
help_command=None,
)
self.db: aiosqlite.Connection | None = None
async def setup_hook(self) -> None:
database_path = os.getenv("DATABASE_PATH", "moderation.db")
self.db = await aiosqlite.connect(database_path)
await self.db.execute(
"""
CREATE TABLE IF NOT EXISTS warnings (
id INTEGER PRIMARY KEY AUTOINCREMENT,
guild_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
moderator_id INTEGER NOT NULL,
reason TEXT NOT NULL,
created_at TEXT NOT NULL
)
"""
)
await self.db.commit()
await self.add_cog(Moderation(self))
guild_id = os.getenv("DEV_GUILD_ID")
if guild_id:
guild = discord.Object(id=int(guild_id))
self.tree.copy_global_to(guild=guild)
synced = await self.tree.sync(guild=guild)
logger.info("Synced %d commands to development guild %s", len(synced), guild_id)
else:
synced = await self.tree.sync()
logger.info("Synced %d global commands", len(synced))
async def close(self) -> None:
if self.db is not None:
await self.db.close()
await super().close()
bot = ModerationBot()
@bot.event
async def on_ready() -> None:
if bot.user is not None:
logger.info("Logged in as %s (%s)", bot.user, bot.user.id)
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
if isinstance(error, app_commands.CommandOnCooldown):
message = f"Please wait {error.retry_after:.1f} seconds before using this command again."
elif isinstance(error, app_commands.MissingPermissions):
permissions = ", ".join(permission.replace("_", " ") for permission in error.missing_permissions)
message = f"You need these permissions: {permissions}."
elif isinstance(error, app_commands.NoPrivateMessage):
message = "This command can only be used in a server."
elif isinstance(error, app_commands.CheckFailure):
message = "You are not allowed to use this command."
else:
logger.exception("Unhandled application-command error", 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)
env_values = dotenv_values(ENV_FILE) if ENV_FILE.is_file() else {}
token = (env_values.get("DISCORD_TOKEN") or os.getenv("DISCORD_TOKEN") or "").strip()
if not token or token in {"put_your_new_bot_token_here", "your_new_token_here", "your_token_here"}:
if not ENV_FILE.is_file():
detail = f"The file does not exist: {ENV_FILE}"
elif "DISCORD_TOKEN" not in env_values:
detail = "The file exists, but it has no DISCORD_TOKEN= line"
else:
detail = "DISCORD_TOKEN is empty or still contains the example placeholder"
raise RuntimeError(
f"No Discord token found. {detail}. Add your reset token to that file as "
"DISCORD_TOKEN=your_token_here (without quotes or spaces around '=')"
)
bot.run(token)