Files
bot.py
requirements.txt
Code
2 448
bot.py
import json
import logging
import os
from pathlib import Path
from urllib.parse import urlsplit
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",
)
logger = logging.getLogger("kverify")
CONFIG_PATH = Path("data/verification.json")
COLOR_NAMES = {
"yellow": discord.Color.yellow,
"red": discord.Color.red,
"orange": discord.Color.orange,
"green": discord.Color.green,
"blue": discord.Color.blue,
"purple": discord.Color.purple,
"pink": discord.Color.magenta,
"black": discord.Color.dark_grey,
"white": discord.Color.light_grey,
"blurple": discord.Color.blurple,
}
def load_configs() -> dict[str, dict]:
try:
with CONFIG_PATH.open("r", encoding="utf-8") as config_file:
configs = json.load(config_file)
return configs if isinstance(configs, dict) else {}
except FileNotFoundError:
return {}
except (json.JSONDecodeError, OSError):
logger.exception("Could not read verification configuration")
return {}
verification_configs = load_configs()
def save_configs() -> None:
CONFIG_PATH.parent.mkdir(parents=True, exist_ok=True)
temporary_path = CONFIG_PATH.with_suffix(".tmp")
with temporary_path.open("w", encoding="utf-8") as config_file:
json.dump(verification_configs, config_file, indent=2)
temporary_path.replace(CONFIG_PATH)
def parse_color(value: str) -> discord.Color:
normalized = value.strip().lower()
if normalized in COLOR_NAMES:
return COLOR_NAMES[normalized]()
hex_value = normalized.removeprefix("#").removeprefix("0x")
if len(hex_value) != 6:
raise ValueError("Use a color name or a six-digit hex color such as #FFFF00.")
try:
return discord.Color(int(hex_value, 16))
except ValueError as error:
raise ValueError("That hex color is not valid.") from error
def validate_image_url(value: str) -> str | None:
url = value.strip()
if not url:
return None
parsed = urlsplit(url)
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
raise ValueError("Image URL must start with http:// or https://.")
return url
def make_embed(config: dict) -> discord.Embed:
embed = discord.Embed(
title=config["title"],
description=config["description"],
color=parse_color(config["color"]),
)
if config.get("image_url"):
embed.set_image(url=config["image_url"])
return embed
def is_manager(interaction: discord.Interaction) -> bool:
return isinstance(interaction.user, discord.Member) and (
interaction.user.guild_permissions.manage_guild
)
async def deny_non_managers(interaction: discord.Interaction) -> bool:
if is_manager(interaction):
return True
await interaction.response.send_message(
"You need the **Manage Server** permission to use this command.",
ephemeral=True,
)
return False
async def send_private_result(
interaction: discord.Interaction, content: str
) -> None:
if interaction.response.is_done():
await interaction.followup.send(content, ephemeral=True)
else:
await interaction.response.send_message(content, ephemeral=True)
class VerificationEditModal(discord.ui.Modal):
def __init__(self, guild_id: int, owner_id: int, config: dict):
super().__init__(title="Edit verification message")
self.guild_id = guild_id
self.owner_id = owner_id
self.title_input = discord.ui.TextInput(
label="Title",
default=config["title"],
max_length=256,
)
self.description_input = discord.ui.TextInput(
label="Description",
style=discord.TextStyle.paragraph,
default=config["description"],
max_length=4000,
)
self.color_input = discord.ui.TextInput(
label="Color name or hex (for example #FFFF00)",
default=config["color"],
max_length=20,
)
self.image_input = discord.ui.TextInput(
label="Image URL (leave blank to remove)",
default=config.get("image_url", ""),
required=False,
max_length=500,
)
self.add_item(self.title_input)
self.add_item(self.description_input)
self.add_item(self.color_input)
self.add_item(self.image_input)
async def on_submit(self, interaction: discord.Interaction) -> None:
if interaction.user.id != self.owner_id or not is_manager(interaction):
await interaction.response.send_message(
"Only the moderator who opened this form can submit it.",
ephemeral=True,
)
return
config = verification_configs.get(str(self.guild_id))
if config is None:
await interaction.response.send_message(
"Verification is no longer configured. Run `/kverify add` first.",
ephemeral=True,
)
return
try:
parse_color(self.color_input.value)
image_url = validate_image_url(self.image_input.value)
except ValueError as error:
await interaction.response.send_message(str(error), ephemeral=True)
return
config["title"] = self.title_input.value
config["description"] = self.description_input.value
config["color"] = self.color_input.value
config["image_url"] = image_url or ""
guild = interaction.guild
channel = guild.get_channel(config["channel_id"]) if guild else None
if not isinstance(channel, discord.TextChannel):
await interaction.response.send_message(
"The configured verification channel no longer exists. Run `/kverify add` again.",
ephemeral=True,
)
return
try:
embed = make_embed(config)
panel = await channel.fetch_message(config["panel_message_id"])
await panel.edit(embed=embed)
except discord.NotFound:
panel = await channel.send(embed=make_embed(config))
config["panel_message_id"] = panel.id
except (discord.Forbidden, discord.HTTPException):
logger.exception("Could not update verification panel in guild %s", self.guild_id)
await interaction.response.send_message(
"I couldn't update the verification message. Check my channel permissions and try again.",
ephemeral=True,
)