Files
.gitignore
bot.py
database.py
moderation.py
README.md
requirements.txt
Code
6 566
bot.py
from __future__ import annotations
import logging
import os
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from database import Database
from moderation import Moderation
load_dotenv()
logging.basicConfig(
level=os.getenv("LOG_LEVEL", "INFO").upper(),
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("royal_military_police")
class RoyalMilitaryPoliceBot(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,
)
self.database = Database(os.getenv("DATABASE_PATH", "royal_military_police.db"))
async def setup_hook(self) -> None:
await self.database.initialize()
await self.add_cog(Moderation(self))
test_guild_id = os.getenv("TEST_GUILD_ID")
if test_guild_id:
guild = discord.Object(id=int(test_guild_id))
self.tree.copy_global_to(guild=guild)
synced = await self.tree.sync(guild=guild)
logger.info("Synced %d commands to test guild %s", len(synced), test_guild_id)
else:
synced = await self.tree.sync()
logger.info("Synced %d global commands", len(synced))
async def on_ready(self) -> None:
if self.user is not None:
logger.info("Logged in as %s (%s)", self.user, self.user.id)
async def on_app_command_error(
self,
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
original = getattr(error, "original", error)
logger.error(
"Slash command failed for %s: %s",
interaction.user,
original,
exc_info=(type(original), original, original.__traceback__),
)
if isinstance(original, discord.Forbidden):
message = "I do not have permission to perform that action. Check my role position and permissions."
elif isinstance(original, discord.NotFound):
message = "That Discord resource no longer exists."
elif isinstance(error, app_commands.CheckFailure):
message = "You do not have permission to use this command."
else:
message = "Something went wrong while processing that command."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
async def close(self) -> None:
await self.database.close()
await super().close()
def main() -> None:
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("DISCORD_TOKEN is not set. Copy .env.example to .env and add your bot token.")
bot = RoyalMilitaryPoliceBot()
bot.run(token, log_handler=None)
if __name__ == "__main__":
main()