Files
data
.gitignore
bot.py
config.json
README.md
requirements.txt
storage.py
Code
7 559
bot.py
import json
import logging
import os
import re
from pathlib import Path
from typing import Any
import discord
from discord import app_commands
from discord.ext import commands
from dotenv import load_dotenv
from storage import JsonStore
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s | %(levelname)s | %(name)s | %(message)s",
)
logger = logging.getLogger("whitelist-bot")
load_dotenv()
def load_config() -> dict[str, Any]:
path = Path("config.json")
try:
with path.open("r", encoding="utf-8") as file:
config = json.load(file)
except (OSError, json.JSONDecodeError) as error:
raise RuntimeError("Le fichier config.json est introuvable ou invalide.") from error
config.setdefault("guild_id", 0)
config.setdefault("whitelist_role_id", 0)
config.setdefault("whitelist_role_name", "Whitelist")
config.setdefault("log_channel_id", 0)
config.setdefault("staff_role_id", 0)
config.setdefault("messages", {})
config["messages"].setdefault(
"whitelist_accepted",
"Ta whitelist pour {username} a été acceptée sur {guild}.",
)
config["messages"].setdefault(
"whitelist_rejected",
"Ta whitelist pour {username} a été refusée. Raison : {reason}",
)
config["messages"].setdefault(
"whitelist_received",
"Ta demande de whitelist {request_id} a bien été envoyée.",
)
return config
CONFIG = load_config()
STORE = JsonStore()
INTENTS = discord.Intents.default()
INTENTS.members = True
BOT = commands.Bot(command_prefix="!", intents=INTENTS)
GUILD_OBJECT = discord.Object(id=int(CONFIG["guild_id"])) if CONFIG["guild_id"] else None
def guild_command(**kwargs: Any):
if GUILD_OBJECT is not None:
kwargs["guild"] = GUILD_OBJECT
return BOT.tree.command(**kwargs)
def configured_message(name: str, **values: str) -> str:
template = str(CONFIG["messages"].get(name, ""))
try:
return template.format(**values)
except (KeyError, ValueError):
return template
def is_staff(interaction: discord.Interaction) -> bool:
if interaction.guild is None or not isinstance(interaction.user, discord.Member):
return False
permissions = interaction.user.guild_permissions
if permissions.administrator or permissions.manage_guild:
return True
role_id = int(CONFIG.get("staff_role_id", 0))
return role_id != 0 and any(role.id == role_id for role in interaction.user.roles)
async def require_staff(interaction: discord.Interaction) -> bool:
if is_staff(interaction):
return True
await interaction.response.send_message(
"❌ Cette commande est réservée au staff.", ephemeral=True
)
return False
async def send_log(
guild: discord.Guild, title: str, description: str, color: discord.Color
) -> None:
await STORE.add_log(title, description, guild.id)
channel_id = int(CONFIG.get("log_channel_id", 0))
channel = guild.get_channel(channel_id) if channel_id else None
if not isinstance(channel, discord.TextChannel):
logger.warning("Le canal de logs %s est introuvable dans %s", channel_id, guild.name)
return
embed = discord.Embed(title=title, description=description, color=color)
embed.timestamp = discord.utils.utcnow()
try:
await channel.send(embed=embed)
except discord.Forbidden:
logger.warning("Le bot ne peut pas écrire dans le canal de logs %s", channel.id)
def get_whitelist_role(guild: discord.Guild) -> discord.Role | None:
role_id = int(CONFIG.get("whitelist_role_id", 0))
if role_id:
role = guild.get_role(role_id)
if role is not None:
return role
role_name = str(CONFIG.get("whitelist_role_name", "Whitelist"))
return discord.utils.find(lambda role: role.name == role_name, guild.roles)
def valid_minecraft_username(username: str) -> bool:
return re.fullmatch(r"[A-Za-z0-9_]{3,16}", username) is not None
@BOT.event
async def on_ready() -> None:
if GUILD_OBJECT is not None:
synced = await BOT.tree.sync(guild=GUILD_OBJECT)
else:
synced = await BOT.tree.sync()
logger.info("Connecté en tant que %s — %d commande(s) synchronisée(s)", BOT.user, len(synced))
@guild_command(name="whitelist", description="Envoyer une demande de whitelist Minecraft")
@app_commands.describe(username="Ton pseudo Minecraft Java")
async def whitelist(interaction: discord.Interaction, username: str) -> None:
if interaction.guild is None:
await interaction.response.send_message("❌ Cette commande doit être utilisée sur le serveur.", ephemeral=True)
return
username = username.strip()
if not valid_minecraft_username(username):
await interaction.response.send_message(
"❌ Le pseudo doit contenir entre 3 et 16 caractères : lettres, chiffres ou underscore.",
ephemeral=True,
)
return
existing = await STORE.find_pending_request(interaction.guild.id, interaction.user.id)
if existing is not None:
await interaction.response.send_message(
f"❌ Tu as déjà une demande en attente : `{existing['id']}`.", ephemeral=True
)
return
request = await STORE.create_whitelist_request(
interaction.guild.id,
interaction.user.id,
str(interaction.user),
username,
)
await send_log(
interaction.guild,
"Nouvelle demande de whitelist",
f"ID : `{request['id']}`\nUtilisateur : {interaction.user.mention} (`{interaction.user.id}`)\nPseudo Minecraft : `{username}`",
discord.Color.blurple(),
)
await interaction.response.send_message(
configured_message(
"whitelist_received", request_id=request["id"], username=username, guild=interaction.guild.name, reason=""
),
ephemeral=True,
)
@guild_command(name="whitelist_accept", description="Accepter une demande de whitelist")
@app_commands.describe(request_id="ID affiché dans le canal de logs")
async def whitelist_accept(interaction: discord.Interaction, request_id: str) -> None:
if not await require_staff(interaction):
return
if interaction.guild is None:
return
request = await STORE.get_whitelist_request(request_id.strip())
if request is None or request["guild_id"] != interaction.guild.id:
await interaction.response.send_message("❌ Demande introuvable.", ephemeral=True)
return
if request["status"] != "pending":
await interaction.response.send_message(
f"❌ Cette demande est déjà traitée : `{request['status']}`.", ephemeral=True
)
return
role = get_whitelist_role(interaction.guild)
if role is None:
await interaction.response.send_message(
"❌ Le rôle whitelist configuré est introuvable.", ephemeral=True
)
return