Files
cogs
.gitignore
bot.py
README.md
requirements.txt
Code
6 391
bot.py
import logging
import os
import discord
from discord.ext import commands
from dotenv import load_dotenv
from cogs.moderation import Moderation
load_dotenv()
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
super().__init__(
command_prefix=commands.when_mentioned,
intents=intents,
help_command=None,
)
async def setup_hook(self) -> None:
await self.add_cog(Moderation(self))
dev_guild_id = os.getenv("DEV_GUILD_ID")
if dev_guild_id:
guild = discord.Object(id=int(dev_guild_id))
self.tree.copy_global_to(guild=guild)
await self.tree.sync(guild=guild)
logger.info("Commands synced to development guild %s", dev_guild_id)
else:
await self.tree.sync()
logger.info("Global commands synced")
async def on_ready(self) -> None:
if self.user:
logger.info("Logged in as %s (%s)", self.user, self.user.id)
async def on_app_command_error(
self,
interaction: discord.Interaction,
error: discord.app_commands.AppCommandError,
) -> None:
original = getattr(error, "original", error)
if isinstance(original, discord.app_commands.errors.MissingPermissions):
message = "You do not have permission to use this command."
elif isinstance(original, discord.app_commands.errors.BotMissingPermissions):
missing = ", ".join(original.missing_permissions).replace("_", " ")
message = f"I am missing these permissions: {missing}."
elif isinstance(original, discord.app_commands.errors.NoPrivateMessage):
message = "This command can only be used inside a server."
else:
logger.error(
"Unhandled application-command error",
exc_info=(type(original), original, original.__traceback__),
)
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 not set. Copy .env.example to .env and add your token.")
bot = ModerationBot()
bot.run(token)