Files
bot.py
requirements.txt
Code
2 350
bot.py
import asyncio
import logging
import os
import re
import sqlite3
import time
from collections import defaultdict, deque
from datetime import timedelta
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")
log = logging.getLogger("empire")
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
db = sqlite3.connect("empire_noctis.db")
db.executescript("""
CREATE TABLE IF NOT EXISTS settings (guild_id INTEGER PRIMARY KEY, log_channel INTEGER, anti_invites INTEGER NOT NULL DEFAULT 0, anti_spam INTEGER NOT NULL DEFAULT 1, raid_threshold INTEGER NOT NULL DEFAULT 8);
CREATE TABLE IF NOT EXISTS cases (id INTEGER PRIMARY KEY AUTOINCREMENT, guild_id INTEGER NOT NULL, user_id INTEGER NOT NULL, moderator_id INTEGER NOT NULL, action TEXT NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP);
""")
db.commit()
def settings(guild_id):
db.execute("INSERT OR IGNORE INTO settings (guild_id) VALUES (?)", (guild_id,))
db.commit()
return db.execute("SELECT log_channel, anti_invites, anti_spam, raid_threshold FROM settings WHERE guild_id = ?", (guild_id,)).fetchone()
async def record_case(guild, user_id, moderator_id, action, reason):
cursor = db.execute("INSERT INTO cases (guild_id, user_id, moderator_id, action, reason) VALUES (?, ?, ?, ?, ?)", (guild.id, user_id, moderator_id, action, reason[:1000]))
db.commit()
channel_id = settings(guild.id)[0]
channel = guild.get_channel(channel_id) if channel_id else None
if channel:
try:
embed = discord.Embed(title=f"Empire Noctis • {action}", description=f"Membre : `{user_id}`\nModérateur : `{moderator_id}`\nRaison : {reason[:1000]}", color=discord.Color.dark_purple())
embed.set_footer(text=f"Dossier #{cursor.lastrowid}")
await channel.send(embed=embed, allowed_mentions=discord.AllowedMentions.none())
except discord.HTTPException:
log.warning("Impossible d'envoyer le journal dans %s", channel_id)
class EmpireBot(commands.Bot):
def __init__(self):
super().__init__(command_prefix=commands.when_mentioned, intents=intents)
self.joins = defaultdict(deque)
self.raid_alerts = {}
self.messages = defaultdict(deque)
self.spam_actions = {}
self.lock = asyncio.Lock()
async def setup_hook(self):
await self.tree.sync()
bot = EmpireBot()
@bot.event
async def on_ready():
log.info("Connecté en tant que %s", bot.user)
print("KODARI_READY", flush=True)
async def announce_raid(guild: discord.Guild, count: int):
channel_id = settings(guild.id)[0]
channel = guild.get_channel(channel_id) if channel_id else guild.system_channel
if channel and channel.permissions_for(guild.me).send_messages:
await channel.send(
f"🚨 **Alerte anti-raid :** {count} arrivées en 30 secondes. "
"Tentative de passage du niveau de vérification au maximum. "
"Le staff peut utiliser `/verrouiller` et vérifier le journal d'audit.",
allowed_mentions=discord.AllowedMentions.none(),
)
@bot.event
async def on_member_join(member: discord.Member):
now = time.monotonic()
async with bot.lock:
recent = bot.joins[member.guild.id]
recent.append(now)
while recent and now - recent[0] > 30:
recent.popleft()
if len(recent) < settings(member.guild.id)[3] or now - bot.raid_alerts.get(member.guild.id, float('-inf')) < 300:
return
bot.raid_alerts[member.guild.id] = now
count = len(recent)
try:
if member.guild.verification_level != discord.VerificationLevel.highest:
await member.guild.edit(verification_level=discord.VerificationLevel.highest, reason="Anti-raid : arrivées massives")
except discord.Forbidden:
log.warning("Permissions insuffisantes pour protéger le serveur %s", member.guild.id)
except discord.HTTPException:
log.exception("Échec de la protection anti-raid sur %s", member.guild.id)
try:
await announce_raid(member.guild, count)
except discord.HTTPException:
log.exception("Impossible d'envoyer l'alerte anti-raid")
@bot.event
async def on_message(message: discord.Message):
if not message.guild or message.author.bot or not isinstance(message.author, discord.Member):
return
if message.author.guild_permissions.manage_messages:
return
_, anti_invites, anti_spam, _ = settings(message.guild.id)
invitation = anti_invites and re.search(r"(?:discord(?:app)?\.com/invite|discord\.gg)\s*/\s*[\w-]+", message.content, re.IGNORECASE)
now = time.monotonic()
key = (message.guild.id, message.author.id)
spam = False
if anti_spam:
recent = bot.messages[key]
recent.append(now)
while recent and now - recent[0] > 8:
recent.popleft()
spam = len(recent) >= 6
if spam:
recent.clear()
if not invitation and not spam:
return
try:
await message.delete()
except discord.HTTPException:
log.warning("Impossible de supprimer un message suspect dans %s", message.guild.id)
if spam and now - bot.spam_actions.get(key, 0) >= 60:
bot.spam_actions[key] = now
try:
await message.author.timeout(timedelta(minutes=5), reason="Empire Noctis : anti-spam")
await record_case(message.guild, message.author.id, bot.user.id, "Timeout automatique", "Spam : 6 messages en 8 secondes")
except discord.HTTPException:
log.warning("Impossible de sanctionner le spammeur %s", message.author.id)
@bot.tree.command(name="ban", description="Bannir un membre du serveur")
@app_commands.default_permissions(ban_members=True)
@app_commands.checks.has_permissions(ban_members=True)
@app_commands.checks.bot_has_permissions(ban_members=True)
@app_commands.checks.cooldown(2, 10.0, key=lambda i: (i.guild_id, i.user.id))
@app_commands.describe(membre="Membre à bannir", raison="Raison du bannissement")
async def ban(interaction: discord.Interaction, membre: discord.Member, raison: str = "Aucune raison indiquée"):
if not await can_moderate(interaction, membre):
return
await membre.ban(reason=f"{interaction.user} : {raison}"[:512])
await interaction.response.send_message(f"🔨 {membre} a été banni. Raison : {raison}", allowed_mentions=discord.AllowedMentions.none())
await record_case(interaction.guild, membre.id, interaction.user.id, "Ban", raison)
@bot.tree.command(name="kick", description="Expulser un membre du serveur")
@app_commands.default_permissions(kick_members=True)
@app_commands.checks.has_permissions(kick_members=True)
@app_commands.checks.bot_has_permissions(kick_members=True)
@app_commands.checks.cooldown(2, 10.0, key=lambda i: (i.guild_id, i.user.id))
@app_commands.describe(membre="Membre à expulser", raison="Raison de l'expulsion")
async def kick(interaction: discord.Interaction, membre: discord.Member, raison: str = "Aucune raison indiquée"):
if not await can_moderate(interaction, membre):
return
await membre.kick(reason=f"{interaction.user} : {raison}"[:512])
await interaction.response.send_message(f"👢 {membre} a été expulsé. Raison : {raison}", allowed_mentions=discord.AllowedMentions.none())
await record_case(interaction.guild, membre.id, interaction.user.id, "Kick", raison)
async def can_moderate(interaction: discord.Interaction, member: discord.Member) -> bool:
actor = interaction.user
guild = interaction.guild
if member.id in (actor.id, guild.owner_id) or (actor.id != guild.owner_id and member.top_role >= actor.top_role):
await interaction.response.send_message("Tu ne peux pas modérer ce membre à cause de la hiérarchie des rôles.", ephemeral=True)
return False
if member.id == bot.user.id or member.top_role >= guild.me.top_role:
await interaction.response.send_message("Mon rôle doit être supérieur à celui du membre.", ephemeral=True)
return False
return True
@bot.tree.command(name="purge", description="Supprimer des messages récents de ce salon")
@app_commands.default_permissions(manage_messages=True)
@app_commands.checks.has_permissions(manage_messages=True)
@app_commands.checks.bot_has_permissions(manage_messages=True, read_message_history=True)
@app_commands.checks.cooldown(1, 10.0, key=lambda i: (i.guild_id, i.user.id))
@app_commands.describe(nombre="Nombre de messages à supprimer (1 à 100)")
async def purge(interaction: discord.Interaction, nombre: app_commands.Range[int, 1, 100]):
if not isinstance(interaction.channel, (discord.TextChannel, discord.Thread)):
await interaction.response.send_message("Cette commande nécessite un salon textuel ou un fil.", ephemeral=True)
return
await interaction.response.defer(ephemeral=True, thinking=True)
deleted = await interaction.channel.purge(limit=nombre, reason=f"Purge par {interaction.user}")
await interaction.followup.send(f"🧹 {len(deleted)} message(s) supprimé(s).", ephemeral=True)
async def set_lock(interaction: discord.Interaction, locked: bool):
channel = interaction.channel