Migration vers Disnake et ajout des components V2

This commit is contained in:
Mathis 2026-05-09 18:42:42 +02:00
parent c8c579eefe
commit 98f7501e07
47 changed files with 1196 additions and 722 deletions

88
bot.py
View file

@ -1,4 +1,5 @@
import os
import sys
from dotenv import load_dotenv
# Charger les variables d'environnement AVANT tout le reste
@ -13,7 +14,6 @@ from src.logger import kuby_logger, log_performance
import logging
from src.advanced_logger import AdvancedLogger
import subprocess
import sys
# Récupération et validation de l'ID d'application
application_id_raw = os.getenv("APPLICATION_ID")
@ -41,9 +41,6 @@ class MyBot(commands.Bot):
application_id=application_id,
)
kuby_logger.info("MyBot instance created successfully")
async def setup_hook(self):
kuby_logger.info("🚀 Démarrage du bot Kuby...")
# Initialize advanced logger
self.advanced_logger = AdvancedLogger(self)
@ -54,8 +51,6 @@ class MyBot(commands.Bot):
try:
flask_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "serveur_flask.py")
if os.path.exists(flask_path):
# On utilise DEVNULL car PM2 ou Nohup gèrent déjà les logs globaux
# et ça évite que le pipe se remplisse et bloque le serveur Flask
self.flask_process = subprocess.Popen(
[sys.executable, flask_path],
stdout=subprocess.DEVNULL,
@ -68,6 +63,11 @@ class MyBot(commands.Bot):
except Exception as e:
kuby_logger.error(f"❌ Impossible de démarrer le serveur Flask: {e}")
async def do_async_setup(self):
# --- INITIALIZATION LOGIC (Called before start() in kuby.py) ---
kuby_logger.info("🚀 Configuration initiale du bot Kuby...")
# Charger les extensions
extensions = [
"commandes.whitelist",
@ -95,62 +95,43 @@ class MyBot(commands.Bot):
for extension in extensions:
try:
await self.load_extension(extension)
self.load_extension(extension)
kuby_logger.info(f"✅ Extension chargée : {extension}")
except Exception as e:
kuby_logger.error(f"❌ Erreur lors du chargement de {extension} : {e}", exc_info=True)
# --- SYSTÈME DE WHITELIST (CORRIGÉ POUR ÉVITER LES ERREURS) ---
@self.check
async def whitelist_check(ctx):
# --- SYSTÈME DE WHITELIST (DÉDIÉ SLASH COMMANDS) ---
async def global_slash_whitelist_check(inter: disnake.ApplicationCommandInteraction):
try:
# 1. Bypass pour le propriétaire (Owner)
if await self.is_owner(ctx.author):
if await self.is_owner(inter.author):
return True
command_name = inter.data.name
if command_name in ["ticketconfig", "ticketpanel", "ticket_config", "ticket_panel", "ticket_whitelist_config"]:
return True
# 1b. Bypass pour les commandes de config tickets
# Si la commande est une commande ticket et l'utilisateur a les perms ticket
if ctx.command and (ctx.command.name in ["ticketconfig", "ticketsetup", "configticket"]):
try:
storage = get_storage()
config = storage.load_config(ctx.guild.id)
if can_access_config(ctx, config):
return True
except Exception as e:
kuby_logger.error(f"Error checking ticket permissions in global whitelist: {e}")
# Fallthrough to normal whitelist check if error
# 2. Récupération du Cog
whitelist_cog = self.get_cog("WhitelistMonitor")
if not whitelist_cog:
kuby_logger.warning("WhitelistMonitor cog not found, allowing all commands")
return True
is_whitelisted = whitelist_cog.is_whitelisted(ctx.guild.id, ctx.author.id)
is_whitelisted = whitelist_cog.is_whitelisted(inter.guild.id, inter.author.id)
if not is_whitelisted:
kuby_logger.info(f"User {ctx.author} (ID: {ctx.author.id}) attempted to use command but is not whitelisted")
# Réponse adaptée (Slash vs Message)
kuby_logger.info(f"🚫 [Check] Accès refusé : {inter.author} sur /{command_name}")
msg = "❌ Vous n'êtes pas autorisé à utiliser cette commande. Veuillez demander à être ajouté à la whitelist."
if ctx.interaction:
await ctx.send(msg, ephemeral=True)
else:
await ctx.send(msg)
if not inter.response.is_done():
await inter.response.send_message(msg, ephemeral=True)
return False
return True
except Exception as e:
kuby_logger.error(f"Error in whitelist check: {e}")
kuby_logger.error(f"⚠️ [Check] Erreur critique: {e}", exc_info=True)
return True
# Sync slash commands
try:
# Disnake handles syncing automatically by default
kuby_logger.info("✅ Commandes slash prêtes avec Disnake")
except Exception as e:
kuby_logger.error(f"❌ Erreur lors de la synchronisation des commandes slash : {e}", exc_info=True)
self.add_app_command_check(global_slash_whitelist_check)
# --- LOGGING DES INTERACTIONS ---
@self.listen("on_interaction")
async def log_interaction(inter: disnake.Interaction):
if inter.type == disnake.InteractionType.application_command:
kuby_logger.info(f"⚡ Interaction reçue : /{inter.data.name} par {inter.user}")
kuby_logger.info("✅ Configuration terminée")
async def close(self):
if hasattr(self, 'flask_process') and self.flask_process:
@ -163,22 +144,12 @@ class MyBot(commands.Bot):
await super().close()
# --- ÉVÉNEMENTS RESTAURÉS ---
async def on_ready(self):
kuby_logger.info(f"🤖 Bot connecté : {self.user} (ID : {self.user.id})")
kuby_logger.info(f"📊 Serveurs : {len(self.guilds)}")
# Log intents status
kuby_logger.info(f"🔍 Intents Status - Members: {self.intents.members}, Presences: {self.intents.presences}, Core: {self.intents.message_content}")
if not self.intents.members:
kuby_logger.warning("⚠️ L'intent MEMBERS est désactivé ! Les événements de join/leave et les DMs pourraient ne pas fonctionner correctement.")
for guild in self.guilds:
kuby_logger.debug(f"Guild: {guild.name} (ID: {guild.id}) - Members: {guild.member_count}")
total_members = sum(guild.member_count for guild in self.guilds)
kuby_logger.info(f"📊 Total members across all guilds: {total_members}")
kuby_logger.warning("⚠️ L'intent MEMBERS est désactivé !")
kuby_logger.info("✅ Bot prêt et opérationnel !")
async def on_guild_join(self, guild):
@ -209,7 +180,6 @@ class MyBot(commands.Bot):
kuby_logger.info(f"👋 {member} left {member.guild.name}")
if hasattr(self, 'advanced_logger'):
self.advanced_logger.log_member_leave(member)
# Notification de départ
try:
from commandes.security import load_settings
settings = load_settings(member.guild.id)
@ -246,7 +216,7 @@ class MyBot(commands.Bot):
async def on_command_error(self, ctx, error):
if isinstance(error, commands.CheckFailure):
return # Déjà géré dans le whitelist_check
return
kuby_logger.error(f"Command error in {ctx.command}: {str(error)}", exc_info=True)
bot = MyBot()