Files
.gitignore
bot.py
config.py
database.py
modal.py
README.md
requirements.txt
views.py
Code
8 530
bot.py
import logging
import os
from typing import Any
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from config import Settings
from database import ApplicationDatabase
from modal import ApplicationModal
from views import ReviewView
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("trusted-applications")
class TrustedApplicationBot(commands.Bot):
def __init__(self, settings: Settings) -> None:
intents = discord.Intents.default()
super().__init__(command_prefix=commands.when_mentioned, intents=intents)
self.settings = settings
self.database = ApplicationDatabase(settings.database_path)
async def setup_hook(self) -> None:
self.add_view(ReviewView(self))
if self.settings.guild_id is not None:
guild = discord.Object(id=self.settings.guild_id)
self.tree.copy_global_to(guild=guild)
synced = await self.tree.sync(guild=guild)
logger.info("Synced %d application command(s) to guild %d", len(synced), guild.id)
else:
synced = await self.tree.sync()
logger.info("Synced %d global application command(s)", len(synced))
async def close(self) -> None:
self.database.close()
await super().close()
def is_reviewer(self, member: discord.Member) -> bool:
if member.guild_permissions.administrator or member.guild_permissions.manage_guild:
return True
role_id = self.settings.staff_role_id
return role_id is not None and any(role.id == role_id for role in member.roles)
async def get_review_channel(self) -> Any | None:
channel = self.get_channel(self.settings.review_channel_id)
if channel is not None:
return channel
try:
return await self.fetch_channel(self.settings.review_channel_id)
except (discord.NotFound, discord.Forbidden, discord.HTTPException):
return None
@staticmethod
def _truncate(value: str, limit: int = 1024) -> str:
value = value.strip()
if len(value) <= limit:
return value
return value[: limit - 1] + "…"
def _application_embed(
self,
application_id: int,
interaction: discord.Interaction,
answers: dict[str, str],
) -> discord.Embed:
embed = discord.Embed(
title=f"Trusted application #{application_id}",
description="Review the applicant's answers and choose an outcome.",
color=discord.Color.blurple(),
timestamp=discord.utils.utcnow(),
)
embed.add_field(
name="Applicant",
value=f"{interaction.user.mention}\nUser ID: `{interaction.user.id}`",
inline=False,
)
for question, answer in answers.items():
embed.add_field(name=question, value=self._truncate(answer), inline=False)
embed.set_footer(text=f"Application ID: {application_id}")
if interaction.user.avatar:
embed.set_thumbnail(url=interaction.user.avatar.url)
return embed
async def submit_application(
self,
interaction: discord.Interaction,
answers: dict[str, str],
) -> None:
await interaction.response.defer(ephemeral=True)
try:
if self.database.has_recent_application(
interaction.user.id,
self.settings.cooldown_hours,
):
await interaction.followup.send(
"You already submitted an application recently. Please wait before applying again.",
ephemeral=True,
)
return
review_channel = await self.get_review_channel()
if review_channel is None:
await interaction.followup.send(
"Applications are temporarily unavailable because the review channel could not be found.",
ephemeral=True,
)
return
application_id = self.database.create_application(
user_id=interaction.user.id,
username=str(interaction.user),
answers=answers,
)
embed = self._application_embed(application_id, interaction, answers)
message = await review_channel.send(
embed=embed,
view=ReviewView(self),
allowed_mentions=discord.AllowedMentions.none(),
)
self.database.set_review_message(application_id, message.id)
await interaction.followup.send(
"Your trusted application was submitted for review.",
ephemeral=True,
)
except (discord.Forbidden, discord.HTTPException):
logger.exception("Could not submit application from user %d", interaction.user.id)
await interaction.followup.send(
"I could not send your application to the review team. Please contact a server administrator.",
ephemeral=True,
)
except Exception:
logger.exception("Unexpected error while submitting application")
await interaction.followup.send(
"Something went wrong while submitting your application. Please try again later.",
ephemeral=True,
)
load_dotenv()
settings = Settings.from_environment()
bot = TrustedApplicationBot(settings)
@bot.tree.command(name="apply", description="Submit an application for the trusted role")
@app_commands.guild_only()
async def apply(interaction: discord.Interaction) -> None:
if bot.database.has_recent_application(
interaction.user.id,
bot.settings.cooldown_hours,
):
await interaction.response.send_message(
"You already submitted an application recently. Please wait before applying again.",
ephemeral=True,
)
return
await interaction.response.send_modal(ApplicationModal(bot))
@bot.tree.error
async def on_app_command_error(
interaction: discord.Interaction,
error: app_commands.AppCommandError,
) -> None:
logger.error("Application command failed: %s", error, exc_info=error)
message = "The command could not be completed. Please try again later."
if isinstance(error, app_commands.errors.CheckFailure):
message = "This command can only be used inside a server."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
if __name__ == "__main__":
token = settings.token
bot.run(token, log_handler=None)