Files
bot.py
requirements.txt
Code
2 134
bot.py
import json
import logging
import os
from pathlib import Path
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
load_dotenv()
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
CONFIG_PATH = Path("config.json")
class VerifyView(discord.ui.View):
def __init__(self, role_id: int):
super().__init__(timeout=None)
self.role_id = role_id
@discord.ui.button(label="Verify", style=discord.ButtonStyle.success, custom_id="verify:grant-role")
async def verify(self, interaction: discord.Interaction, button: discord.ui.Button):
if interaction.guild is None or not isinstance(interaction.user, discord.Member):
await interaction.response.send_message("Verification is only available in a server.", ephemeral=True)
return
role = interaction.guild.get_role(self.role_id)
if role is None:
await interaction.response.send_message(
"The verification role is no longer available. Ask a server administrator to run `/setup_verify` again.",
ephemeral=True,
)
return
if role in interaction.user.roles:
await interaction.response.send_message("You are already verified.", ephemeral=True)
return
if not role.is_assignable():
await interaction.response.send_message(
"I can't assign the verification role. Ask an administrator to move my role above it.",
ephemeral=True,
)
return
try:
await interaction.user.add_roles(role, reason="Completed server verification")
await interaction.response.send_message("You are verified!", ephemeral=True)
except discord.Forbidden:
await interaction.response.send_message(
"I don't have permission to assign the verification role.", ephemeral=True
)
except discord.HTTPException:
logging.exception("Could not assign the verification role")
await interaction.response.send_message(
"Verification failed due to a Discord error. Please try again.", ephemeral=True
)
class VerifyBot(commands.Bot):
async def setup_hook(self):
try:
config = json.loads(CONFIG_PATH.read_text(encoding="utf-8"))
role_id = config.get("verify_role_id")
if isinstance(role_id, int):
self.add_view(VerifyView(role_id))
except FileNotFoundError:
pass
except (OSError, json.JSONDecodeError, AttributeError, TypeError):
logging.exception("Could not load verification configuration")
await self.tree.sync()
bot = VerifyBot(command_prefix="!", intents=discord.Intents.default())
@bot.tree.command(name="setup_verify", description="Create a verification panel for this server")
@app_commands.guild_only()
@app_commands.default_permissions(administrator=True)
async def setup_verify(interaction: discord.Interaction, role: discord.Role):
if interaction.guild is None:
await interaction.response.send_message("This command can only be used in a server.", ephemeral=True)
return
if not interaction.user.guild_permissions.administrator:
await interaction.response.send_message("Only administrators can set up verification.", ephemeral=True)
return
if role.is_default() or not role.is_assignable():
await interaction.response.send_message(
"Choose a normal role that is below my highest role in the server.", ephemeral=True
)
return
try:
CONFIG_PATH.write_text(json.dumps({"verify_role_id": role.id}, indent=2), encoding="utf-8")
except OSError:
logging.exception("Could not save verification configuration")
await interaction.response.send_message("I couldn't save the setup. Please try again.", ephemeral=True)
return
embed = discord.Embed(
title="Server Verification",
description=f"Click the button below to receive the {role.mention} role.",
color=discord.Color.green(),
)
await interaction.response.send_message(embed=embed, view=VerifyView(role.id))
@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError):
logging.error("Slash command failed", exc_info=(type(error), error, error.__traceback__))
message = "Something went wrong while running that command. Please try again."
if interaction.response.is_done():
await interaction.followup.send(message, ephemeral=True)
else:
await interaction.response.send_message(message, ephemeral=True)
@bot.event
async def on_ready():
logging.info("Logged in as %s", bot.user)
print("KODARI_READY", flush=True)
if __name__ == "__main__":
token = os.getenv("DISCORD_TOKEN")
if not token:
raise RuntimeError("DISCORD_TOKEN is missing from the environment or .env file")
bot.run(token)