import os import json import asyncio import threading import traceback import gradio as gr import discord from discord import app_commands from discord.ext import commands import spaces # Satisfies Hugging Face ZeroGPU startup check @spaces.GPU def dummy_gpu_check(): return "GPU active" # --- Configuration & Persistence --- DATA_DIR = os.path.dirname(__file__) DATA_FILE = os.path.join(DATA_DIR, "bot_data.json") LOG_CHANNEL_ID = 1569093676758474926 GOLD_COLOR = discord.Color(0xD4AF37) TARGET_ROLES_CONFIG = { "prince": { "name": "Fils du Prince", "color": discord.Color(0xD4AF37), "label": "Fils du Prince" }, "cold_war": { "name": "Inscrit Cold War", "color": discord.Color(0x3498DB), "label": "Inscrit Cold War" }, "w_n": { "name": "Inscrit W-N", "color": discord.Color(0x9B59B6), "label": "Inscrit W-N" } } def resolve_target_choice(choice: str) -> tuple[list[str], str]: if choice == "cold_war": return ["cold_war"], "Inscrit Cold War" elif choice == "w_n": return ["w_n"], "Inscrit W-N" elif choice == "tous_les_roles": return ["prince", "cold_war", "w_n"], "Inscrits (Prince, Cold War, W-N)" return ["prince"], "Fils du Prince" def load_data(): if os.path.exists(DATA_FILE): try: with open(DATA_FILE, "r", encoding="utf-8") as f: return json.load(f) except Exception: pass return {"announcements": {}, "polls": {}} def save_data(data): try: with open(DATA_FILE, "w", encoding="utf-8") as f: json.dump(data, f, ensure_ascii=False, indent=2) except Exception as e: print(f"[ERROR] Failed to save data: {e}") bot_storage = load_data() # --- Discord Setup --- intents = discord.Intents.default() intents.message_content = True intents.members = True bot = commands.Bot(command_prefix="!", intents=intents) bot_status = {"connected": False, "user": "Non connecté", "guilds": 0} # --- Système de Logs --- async def send_log(title: str, description: str, color: discord.Color = GOLD_COLOR, dev_details: str | None = None): try: channel = bot.get_channel(LOG_CHANNEL_ID) or await bot.fetch_channel(LOG_CHANNEL_ID) if not channel: return embed = discord.Embed( title=title, description=description, color=color, timestamp=discord.utils.utcnow() ) if dev_details: embed.add_field( name="Developer Details", value=f"```\n{dev_details[:1000]}\n```", inline=False ) await channel.send(embed=embed) except Exception as e: print(f"[LOG ERROR] Impossible d'envoyer le log dans {LOG_CHANNEL_ID}: {e}") # --- Gestion des Rôles Cibles --- async def get_or_create_target_roles(guild: discord.Guild) -> dict[str, discord.Role]: roles = {} for key, cfg in TARGET_ROLES_CONFIG.items(): role = discord.utils.get(guild.roles, name=cfg["name"]) if not role: try: role = await guild.create_role( name=cfg["name"], color=cfg["color"], mentionable=True, reason=f"Rôle cible automatique : {cfg['name']}" ) await send_log( title="🛡️ Création Automatique de Rôle", description=f"Le rôle **{cfg['name']}** a été créé sur **{guild.name}**.", color=cfg["color"], dev_details=f"guild_id: {guild.id}\nrole_id: {role.id}\nrole_name: {cfg['name']}" ) except Exception as e: print(f"[ERROR] Impossible de créer le rôle '{cfg['name']}': {e}") role = None if role: roles[key] = role return roles # --- UI Views: Annonce --- class AnnouncementView(discord.ui.View): def __init__(self, announcement_id: str): super().__init__(timeout=None) self.announcement_id = announcement_id button = discord.ui.Button( label="J'ai lu ✅", style=discord.ButtonStyle.success, custom_id=f"ann_read_{announcement_id}" ) button.callback = self.on_read_click self.add_item(button) async def on_read_click(self, interaction: discord.Interaction): ann = bot_storage["announcements"].get(self.announcement_id) if not ann: await interaction.response.send_message("❌ Cette annonce n'existe plus en mémoire.", ephemeral=True) return user_id = str(interaction.user.id) if user_id in ann["readers"]: await interaction.response.send_message("ℹ️ Vous avez déjà confirmé votre lecture pour cette annonce.", ephemeral=True) return ann["readers"][user_id] = interaction.user.display_name save_data(bot_storage) await interaction.response.send_message("✅ Votre lecture a bien été enregistrée !", ephemeral=True) # Log action await send_log( title="👁️ Confirmation de Lecture", description=f"**{interaction.user.display_name}** ({interaction.user.mention}) a confirmé la lecture de l'annonce **{ann['title']}**.", color=discord.Color.green(), dev_details=f"action: ANNOUNCEMENT_READ\nann_id: {self.announcement_id}\nuser_id: {user_id}\ntotal_readers: {len(ann['readers'])}" ) # Update channel message channel_id = ann.get("channel_id") message_id = ann.get("message_id") if channel_id and message_id: try: channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id) msg = await channel.fetch_message(message_id) target_members = ann.get("target_members", {}) new_embed = build_announcement_embed( ann["title"], ann["content"], ann["author_name"], ann["readers"], target_members, ann.get("target_label", "Fils du Prince") ) await msg.edit(embed=new_embed) except Exception as e: print(f"[WARN] Failed to update channel announcement message: {e}") def build_announcement_embed(title: str, content: str, author_name: str, readers: dict, target_members: dict, target_label: str = "Fils du Prince"): embed = discord.Embed( title=f"📢 ❯ {title}", description=f">>> {content}\n\n*Cliquez sur le bouton ci-dessous pour confirmer votre lecture.*", color=GOLD_COLOR ) total_targets = len(target_members) pending = [name for u_id, name in target_members.items() if u_id not in readers] if total_targets == 0: embed.add_field( name="⏳・En Attente de Lecture", value="*Aucun membre avec ce rôle sur le serveur.*", inline=False ) elif pending: if len(pending) > 25: names_str = ", ".join(pending[:25]) + f" *et {len(pending) - 25} autres...*" else: names_str = ", ".join(pending) read_count = total_targets - len(pending) embed.add_field( name=f"⏳・En Attente de Lecture ({len(pending)}/{total_targets})", value=f"```fix\n{len(pending)} restant(s)・{read_count} ont validé\n```\n{names_str}", inline=False ) else: embed.add_field( name=f"✅・Lectures Terminées ({total_targets}/{total_targets})", value="🎉 **Tous les membres ciblés ont confirmé leur lecture !**", inline=False ) embed.set_footer(text=f"BOTBARBAK • Cible : {target_label} • Publié par {author_name}") embed.timestamp = discord.utils.utcnow() return embed # --- UI Views: Sondage --- NUM_EMOJIS = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣"] class PollView(discord.ui.View): def __init__(self, poll_id: str, options: list[str]): super().__init__(timeout=None) self.poll_id = poll_id self.options = options for idx, opt in enumerate(options): emoji = NUM_EMOJIS[idx] if idx < len(NUM_EMOJIS) else None btn = discord.ui.Button( label=opt[:80], emoji=emoji, style=discord.ButtonStyle.primary, custom_id=f"poll_{poll_id}_{idx}" ) btn.callback = self.make_vote_callback(idx) self.add_item(btn) def make_vote_callback(self, option_index: int): async def callback(interaction: discord.Interaction): poll = bot_storage["polls"].get(self.poll_id) if not poll: await interaction.response.send_message("❌ Ce sondage n'existe plus en mémoire.", ephemeral=True) return user_id = str(interaction.user.id) chosen_opt = poll["options"][option_index] is_change = False prev_opt_name = None if user_id in poll["voters"]: prev_val = poll["voters"][user_id] prev_opt = prev_val.get("option", 0) if isinstance(prev_val, dict) else int(prev_val) if prev_opt == option_index: await interaction.response.send_message( f"ℹ️ Vous avez déjà voté pour : **{chosen_opt}**.", ephemeral=True ) return # Decrement previous option count prev_str = str(prev_opt) poll["votes"][prev_str] = max(0, poll["votes"].get(prev_str, 1) - 1) is_change = True prev_opt_name = poll["options"][prev_opt] if prev_opt < len(poll["options"]) else f"Option {prev_opt + 1}" poll["voters"][user_id] = { "option": option_index, "name": interaction.user.display_name } poll["votes"][str(option_index)] = poll["votes"].get(str(option_index), 0) + 1 save_data(bot_storage) if is_change: await interaction.response.send_message( f"🔄 Votre vote a été modifié : **{prev_opt_name}** ➔ **{chosen_opt}** !", ephemeral=True ) log_title = "🔄 Vote Modifié" log_desc = f"**{interaction.user.display_name}** ({interaction.user.mention}) a modifié son vote : **{prev_opt_name}** ➔ **{chosen_opt}** sur le sondage **{poll['question']}**." else: await interaction.response.send_message(f"✅ Votre vote pour **{chosen_opt}** a été comptabilisé !", ephemeral=True) log_title = "🗳️ Vote Enregistré" log_desc = f"**{interaction.user.display_name}** ({interaction.user.mention}) a voté pour **{chosen_opt}** sur le sondage **{poll['question']}**." # Log action await send_log( title=log_title, description=log_desc, color=discord.Color.purple(), dev_details=f"action: {'POLL_VOTE_CHANGED' if is_change else 'POLL_VOTE'}\npoll_id: {self.poll_id}\nuser_id: {user_id}\noption_index: {option_index}\ntotal_votes: {len(poll['voters'])}" ) # Update channel message channel_id = poll.get("channel_id") message_id = poll.get("message_id") if channel_id and message_id: try: channel = bot.get_channel(channel_id) or await bot.fetch_channel(channel_id) msg = await channel.fetch_message(message_id) target_members = poll.get("target_members", {}) new_embed = build_poll_embed( poll["question"], poll["options"], poll["votes"], poll["voters"], target_members, poll.get("target_label", "Fils du Prince") ) await msg.edit(embed=new_embed) except Exception as e: print(f"[WARN] Failed to update poll message: {e}") return callback def build_poll_embed(question: str, options: list[str], votes: dict, voters: dict, target_members: dict, target_label: str = "Fils du Prince"): total_votes = len(voters) embed = discord.Embed( title="📊 ❯ Sondage Communautaire", description=f">>> {question}\n\n*Exprimez votre choix ci-dessous ou directement depuis vos messages privés.*", color=GOLD_COLOR ) for idx, opt in enumerate(options): v_count = votes.get(str(idx), 0) pct = (v_count / total_votes * 100) if total_votes > 0 else 0 filled = int(pct / 10) bar = "▰" * filled + "▱" * (10 - filled) emoji = NUM_EMOJIS[idx] if idx < len(NUM_EMOJIS) else f"{idx + 1}." # Extract voter names for this specific option option_voters = [] for u_id, v_info in voters.items(): if isinstance(v_info, dict): if v_info.get("option") == idx: option_voters.append(v_info.get("name", "Membre")) elif int(v_info) == idx: option_voters.append("Membre") if option_voters: if len(option_voters) > 15: names_str = ", ".join(option_voters[:15]) + f" *et {len(option_voters) - 15} autres...*" else: names_str = ", ".join(option_voters) voters_display = f"\n> 👥 **Votants :** {names_str}" else: voters_display = "\n> 👥 *Aucun vote pour l'instant*" embed.add_field( name=f"{emoji} {opt}", value=f"`{bar}` **{v_count}** vote(s)・**{pct:.1f}%**{voters_display}", inline=False ) # Inverted display: Show who STILL has to vote total_targets = len(target_members) pending_voters = [name for u_id, name in target_members.items() if u_id not in voters] if total_targets == 0: embed.add_field( name="⏳・En Attente de Vote", value="*Aucun membre avec ce rôle sur le serveur.*", inline=False ) elif pending_voters: if len(pending_voters) > 25: names_str = ", ".join(pending_voters[:25]) + f" *et {len(pending_voters) - 25} autres...*" else: names_str = ", ".join(pending_voters) embed.add_field( name=f"⏳・En Attente de Vote ({len(pending_voters)}/{total_targets})", value=f"```fix\n{len(pending_voters)} restant(s)・{total_votes} ont voté\n```\n{names_str}", inline=False ) else: embed.add_field( name=f"✅・Participation Complète ({total_targets}/{total_targets})", value="🎉 **Tous les membres ciblés ont voté !**", inline=False ) embed.set_footer(text=f"BOTBARBAK • Cible : {target_label} • Total votants : {total_votes} • Vote modifiable") embed.timestamp = discord.utils.utcnow() return embed # --- Diffusion en MP --- async def broadcast_dm(guild: discord.Guild, embed: discord.Embed, view_factory, target_keys: list[str]): all_roles = await get_or_create_target_roles(guild) member_set = set() for key in target_keys: r = all_roles.get(key) if r: for m in r.members: if not m.bot: member_set.add(m) targets = list(member_set) target_members_dict = {str(m.id): m.display_name for m in targets} total_targets = len(targets) sent = 0 failed = 0 for member in targets: try: view = view_factory() await member.send(embed=embed, view=view) sent += 1 await asyncio.sleep(0.6) # Protection contre le rate-limit Discord except (discord.Forbidden, discord.HTTPException): failed += 1 return sent, failed, total_targets, target_members_dict # --- Commandes Slash --- @bot.tree.command(name="annonce", description="Publie une annonce officielle et l'envoie en MP aux membres des rôles ciblés.") @app_commands.describe( titre="Titre de l'annonce", contenu="Texte de l'annonce", role_cible="Rôle ciblé pour la diffusion en MP" ) @app_commands.choices(role_cible=[ app_commands.Choice(name="Fils du Prince (défaut)", value="prince"), app_commands.Choice(name="Inscrit Cold War", value="cold_war"), app_commands.Choice(name="Inscrit W-N", value="w_n"), app_commands.Choice(name="Tous les 3 rôles cibles", value="tous_les_roles") ]) @app_commands.default_permissions(administrator=True) async def slash_annonce(interaction: discord.Interaction, titre: str, contenu: str, role_cible: str = "prince"): if not interaction.user.guild_permissions.administrator: await interaction.response.send_message("❌ Cette commande est réservée aux administrateurs.", ephemeral=True) return await interaction.response.defer(ephemeral=False) keys, label = resolve_target_choice(role_cible) ann_id = str(interaction.id) bot_storage["announcements"][ann_id] = { "title": titre, "content": contenu, "author_name": interaction.user.display_name, "channel_id": interaction.channel_id, "message_id": None, "target_label": label, "target_members": {}, "readers": {} } # Temporary initial embed init_embed = build_announcement_embed(titre, contenu, interaction.user.display_name, {}, {}, label) view = AnnouncementView(ann_id) msg = await interaction.followup.send(embed=init_embed, view=view) bot_storage["announcements"][ann_id]["message_id"] = msg.id # Broadcast DM to targeted role(s) sent, failed, total, target_members = await broadcast_dm(interaction.guild, init_embed, lambda: AnnouncementView(ann_id), keys) bot_storage["announcements"][ann_id]["target_members"] = target_members save_data(bot_storage) # Update channel message with inverted pending list final_embed = build_announcement_embed(titre, contenu, interaction.user.display_name, {}, target_members, label) await msg.edit(embed=final_embed) # Log Action await send_log( title="📢 Nouvelle Annonce Publiée", description=f"Annonce **{titre}** lancée par {interaction.user.mention} dans <#{interaction.channel_id}>.\n" f"Diffusion aux **{label}** : **{sent}/{total}** reçus (**{failed}** bloqués/fermés).", color=GOLD_COLOR, dev_details=f"action: ANNOUNCEMENT_CREATED\nann_id: {ann_id}\nmsg_id: {msg.id}\ntarget: {label}\nsent: {sent}\nfailed: {failed}\ntotal: {total}" ) try: await interaction.channel.send( f"ℹ️ *Diffusion MP ({label}) : {sent}/{total} envoyé(s), {failed} bloqué(s)/fermés.*", delete_after=15 ) except Exception: pass @bot.tree.command(name="sondage", description="Crée un sondage interactif et l'envoie en MP aux membres des rôles ciblés.") @app_commands.describe( question="Question du sondage", options="Choix séparés par des virgules (ex: Oui, Non, Peut-être)", role_cible="Rôle ciblé pour la diffusion en MP" ) @app_commands.choices(role_cible=[ app_commands.Choice(name="Fils du Prince (défaut)", value="prince"), app_commands.Choice(name="Inscrit Cold War", value="cold_war"), app_commands.Choice(name="Inscrit W-N", value="w_n"), app_commands.Choice(name="Tous les 3 rôles cibles", value="tous_les_roles") ]) @app_commands.default_permissions(administrator=True) async def slash_sondage(interaction: discord.Interaction, question: str, options: str, role_cible: str = "prince"): if not interaction.user.guild_permissions.administrator: await interaction.response.send_message("❌ Cette commande est réservée aux administrateurs.", ephemeral=True) return opt_list = [o.strip() for o in options.split(",") if o.strip()] if len(opt_list) < 2: await interaction.response.send_message("❌ Vous devez fournir au moins 2 options séparées par des virgules.", ephemeral=True) return if len(opt_list) > 5: await interaction.response.send_message("❌ Maximum 5 options autorisées.", ephemeral=True) return await interaction.response.defer(ephemeral=False) keys, label = resolve_target_choice(role_cible) poll_id = str(interaction.id) bot_storage["polls"][poll_id] = { "question": question, "options": opt_list, "channel_id": interaction.channel_id, "message_id": None, "target_label": label, "target_members": {}, "votes": {}, "voters": {} } init_embed = build_poll_embed(question, opt_list, {}, {}, {}, label) view = PollView(poll_id, opt_list) msg = await interaction.followup.send(embed=init_embed, view=view) bot_storage["polls"][poll_id]["message_id"] = msg.id # Broadcast DM to targeted role(s) sent, failed, total, target_members = await broadcast_dm(interaction.guild, init_embed, lambda: PollView(poll_id, opt_list), keys) bot_storage["polls"][poll_id]["target_members"] = target_members save_data(bot_storage) # Update channel message with inverted pending list final_embed = build_poll_embed(question, opt_list, {}, {}, target_members, label) await msg.edit(embed=final_embed) # Log Action await send_log( title="📊 Nouveau Sondage Créé", description=f"Sondage créé par {interaction.user.mention} dans <#{interaction.channel_id}> :\n**{question}**\n" f"Diffusion aux **{label}** : **{sent}/{total}** reçus (**{failed}** bloqués/fermés).", color=GOLD_COLOR, dev_details=f"action: POLL_CREATED\npoll_id: {poll_id}\nmsg_id: {msg.id}\ntarget: {label}\noptions: {opt_list}\nsent: {sent}\nfailed: {failed}" ) try: await interaction.channel.send( f"ℹ️ *Diffusion MP ({label}) : {sent}/{total} envoyé(s), {failed} bloqué(s)/fermés.*", delete_after=15 ) except Exception: pass @bot.tree.command(name="clear", description="Supprime tous les messages et embeds envoyés par ce bot dans ce salon.") @app_commands.describe(nombre="Nombre maximal de messages à scanner dans le salon (défaut: 100, max: 500)") @app_commands.default_permissions(administrator=True) async def slash_clear(interaction: discord.Interaction, nombre: int = 100): if not interaction.user.guild_permissions.administrator: await interaction.response.send_message("❌ Cette commande est réservée aux administrateurs.", ephemeral=True) return await interaction.response.defer(ephemeral=True) channel = interaction.channel limit = min(max(nombre, 1), 500) deleted_count = 0 deleted_ids = [] try: async for msg in channel.history(limit=limit): if msg.author.id == bot.user.id: try: await msg.delete() deleted_count += 1 deleted_ids.append(str(msg.id)) await asyncio.sleep(0.2) except Exception: pass except Exception as e: print(f"[ERROR] Erreur lors de l'exécution de /clear: {e}") # Purge memory records matching deleted messages or channel purged_storage = 0 for ann_id in list(bot_storage.get("announcements", {}).keys()): m_id = str(bot_storage["announcements"][ann_id].get("message_id")) if m_id in deleted_ids or bot_storage["announcements"][ann_id].get("channel_id") == channel.id: del bot_storage["announcements"][ann_id] purged_storage += 1 for poll_id in list(bot_storage.get("polls", {}).keys()): m_id = str(bot_storage["polls"][poll_id].get("message_id")) if m_id in deleted_ids or bot_storage["polls"][poll_id].get("channel_id") == channel.id: del bot_storage["polls"][poll_id] purged_storage += 1 save_data(bot_storage) embed = discord.Embed( title="🧹 ❯ Nettoyage Complet des Embeds", description=f"Tous les messages et embeds générés par **BOTBARBAK** ont été supprimés de <#{channel.id}>.", color=GOLD_COLOR ) embed.add_field(name="Messages Supprimés", value=f"`{deleted_count}`", inline=True) embed.add_field(name="Éléments Purgés en Mémoire", value=f"`{purged_storage}`", inline=True) embed.set_footer(text="BOTBARBAK • Salon assaini") await interaction.followup.send(embed=embed, ephemeral=True) await send_log( title="🧹 Nettoyage Global des Embeds (/clear)", description=f"{interaction.user.mention} a exécuté `/clear` dans <#{channel.id}> :\n" f"**{deleted_count}** messages supprimés, **{purged_storage}** éléments retirés de la base de données.", color=discord.Color.orange(), dev_details=f"action: CHANNEL_CLEAR\nchannel_id: {channel.id}\ndeleted_messages: {deleted_count}\npurged_records: {purged_storage}" ) @bot.tree.command(name="supprimer", description="Supprime une annonce ou un sondage par son identifiant de message et purge la mémoire.") @app_commands.describe(identifiant_message="ID du message contenant l'embed à supprimer") @app_commands.default_permissions(administrator=True) async def slash_supprimer(interaction: discord.Interaction, identifiant_message: str): if not interaction.user.guild_permissions.administrator: await interaction.response.send_message("❌ Cette commande est réservée aux administrateurs.", ephemeral=True) return await interaction.response.defer(ephemeral=True) target_id = identifiant_message.strip() found_type = None target_channel_id = None target_msg_id = None # Search in announcements for ann_id, data in list(bot_storage.get("announcements", {}).items()): if str(data.get("message_id")) == target_id or ann_id == target_id: found_type = f"Annonce ('{data.get('title')}')" target_channel_id = data.get("channel_id") target_msg_id = data.get("message_id") del bot_storage["announcements"][ann_id] break # Search in polls if not found_type: for poll_id, data in list(bot_storage.get("polls", {}).items()): if str(data.get("message_id")) == target_id or poll_id == target_id: found_type = f"Sondage ('{data.get('question')}')" target_channel_id = data.get("channel_id") target_msg_id = data.get("message_id") del bot_storage["polls"][poll_id] break save_data(bot_storage) # Delete message in Discord if found or if ID corresponds to message in channel deleted_msg = False chan_id = target_channel_id or interaction.channel_id msg_to_del = target_msg_id or target_id try: channel = bot.get_channel(chan_id) or await bot.fetch_channel(chan_id) msg = await channel.fetch_message(int(msg_to_del)) await msg.delete() deleted_msg = True except Exception as e: print(f"[WARN] Impossible de supprimer le message Discord directement: {e}") # Response embed embed = discord.Embed( title="🗑️ ❯ Purge et Nettoyage Effectués", description=f"L'élément **{found_type or 'Message ID inconnu'}** a été supprimé de la mémoire active.", color=GOLD_COLOR ) embed.add_field(name="ID Ciblé", value=f"`{target_id}`", inline=True) embed.add_field(name="Message Discord", value="✅ Supprimé du salon" if deleted_msg else "⚠️ Non trouvé / Déjà supprimé", inline=True) embed.set_footer(text="BOTBARBAK • Mémoire synchronisée") await interaction.followup.send(embed=embed, ephemeral=True) await send_log( title="🗑️ Purge d'un Élément", description=f"{interaction.user.mention} a purgé l'élément `{target_id}` ({found_type or 'Hors mémoire'}).", color=discord.Color.orange(), dev_details=f"action: CLEAR_ITEM\ntarget_id: {target_id}\nfound_type: {found_type}\nchannel_id: {chan_id}\nmsg_deleted: {deleted_msg}" ) @bot.tree.command(name="check", description="Vérifie silencieusement (sans envoyer de MP) qui a ses messages privés ouverts ou fermés.") @app_commands.describe(cible="Portée du diagnostic") @app_commands.choices(cible=[ app_commands.Choice(name="Fils du Prince", value="prince"), app_commands.Choice(name="Inscrit Cold War", value="cold_war"), app_commands.Choice(name="Inscrit W-N", value="w_n"), app_commands.Choice(name="Tous les 3 rôles cibles", value="tous_les_roles"), app_commands.Choice(name="Tout le serveur (membres réels)", value="tout_le_serveur") ]) @app_commands.default_permissions(administrator=True) async def slash_check(interaction: discord.Interaction, cible: str = "prince"): if not interaction.user.guild_permissions.administrator: await interaction.response.send_message("❌ Cette commande est réservée aux administrateurs.", ephemeral=True) return await interaction.response.defer(ephemeral=False) guild = interaction.guild if not guild: await interaction.followup.send("❌ Commande utilisable uniquement sur un serveur.", ephemeral=True) return if cible == "tout_le_serveur": members = [m for m in guild.members if not m.bot] target_desc = "Tous les membres du serveur" else: keys, label = resolve_target_choice(cible) all_roles = await get_or_create_target_roles(guild) member_set = set() for k in keys: r = all_roles.get(k) if r: for m in r.members: if not m.bot: member_set.add(m) members = list(member_set) target_desc = f"Membres ciblés : **{label}**" if not members: await interaction.followup.send(f"⚠️ Aucun membre trouvé pour : {target_desc}.") return accessible = [] bloques = [] for member in members: try: dm = await member.create_dm() await dm.typing() accessible.append(member.display_name) except (discord.Forbidden, discord.HTTPException): bloques.append(member.display_name) await asyncio.sleep(0.3) total = len(members) pct_open = (len(accessible) / total * 100) if total > 0 else 0 embed = discord.Embed( title="🔍 ❯ Diagnostic d'Accessibilité des Messages Privés", description=f"Analyse silencieuse effectuée sur **{target_desc}** ({total} membre(s)).\n*Aucun message n'a été envoyé aux membres durant ce test.*", color=GOLD_COLOR ) if accessible: acc_text = ", ".join(accessible[:30]) + (f" *et {len(accessible)-30} autres...*" if len(accessible) > 30 else "") embed.add_field( name=f"🟢 MP Accessibles ({len(accessible)})", value=f"```diff\n+ {len(accessible)}/{total} joignables ({pct_open:.1f}%)\n```\n{acc_text}", inline=False ) else: embed.add_field( name="🟢 MP Accessibles (0)", value="*Aucun membre joignable en privé.*", inline=False ) if bloques: bloq_text = ", ".join(bloques[:30]) + (f" *et {len(bloques)-30} autres...*" if len(bloques) > 30 else "") embed.add_field( name=f"🔴 MP Fermés / Bloqués ({len(bloques)})", value=f"```diff\n- {len(bloques)}/{total} injoignables\n```\n{bloq_text}\n\n*Ces membres doivent activer : Clic droit serveur ➔ Paramètres de confidentialité ➔ Messages privés : Activé.*", inline=False ) else: embed.add_field( name="🔴 MP Fermés / Bloqués (0)", value="🎉 *100% des membres ciblés ont leurs MP ouverts !*", inline=False ) embed.set_footer(text=f"BOTBARBAK • Diagnostic confidentiel • {interaction.guild.name}") embed.timestamp = discord.utils.utcnow() await interaction.followup.send(embed=embed) await send_log( title="🔍 Diagnostic MP Exécuté", description=f"{interaction.user.mention} a exécuté `/check` sur **{target_desc}**.\n" f"Résultat : **{len(accessible)}** accessibles, **{len(bloques)}** bloqués.", color=GOLD_COLOR, dev_details=f"action: SILENT_CHECK\ntarget: {cible}\ntotal: {total}\naccessible: {len(accessible)}\nblocked: {len(bloques)}" ) @bot.tree.command(name="guide", description="Affiche le guide complet d'utilisation du bot et de ses fonctionnalités.") async def slash_guide(interaction: discord.Interaction): embed = discord.Embed( title="📖 ❯ Guide d'Utilisation Officiel ・ BOTBARBAK", description="Bienvenue sur le tableau de bord des commandes de **BOTBARBAK**. Voici la documentation des fonctionnalités disponibles :", color=GOLD_COLOR ) embed.add_field( name="👑 ❯ Rôles Cibles Disponibles", value="Le bot crée et gère automatiquement 3 rôles cibles distincts :\n" "• 🟡 **Fils du Prince** (Or)\n" "• 🔵 **Inscrit Cold War** (Bleu)\n" "• 🟣 **Inscrit W-N** (Violet)\n" "*Lors de l'envoi d'une annonce, d'un sondage ou d'un check, choisissez le rôle spécifique ou les 3 en même temps.*", inline=False ) embed.add_field( name="📢 ❯ Commande /annonce [Administrateurs]", value="• **Syntaxe :** `/annonce titre: contenu: role_cible: [choix]`\n" "• Affiche un embed doré officiel dans le salon.\n" "• Envoie un MP personnalisé aux membres détenteurs du/des rôle(s) sélectionné(s).\n" "• **Affichage inversé :** liste les membres qui doivent encore valider leur lecture.", inline=False ) embed.add_field( name="📊 ❯ Commande /sondage [Administrateurs]", value="• **Syntaxe :** `/sondage question: options: role_cible: [choix]`\n" "• Supporte de 2 à 5 options séparées par des virgules.\n" "• Diffuse l'embed avec boutons interactifs dans le salon et en MP.\n" "• **Affichage inversé :** liste les membres qui n'ont pas encore répondu au sondage.", inline=False ) embed.add_field( name="🧹 ❯ Commande /clear [Administrateurs]", value="• **Syntaxe :** `/clear nombre: [100]`\n" "• Supprime tous les messages et embeds générés par le bot dans ce salon (même antérieurs au démarrage).\n" "• Purge la mémoire et la base de données.", inline=False ) embed.add_field( name="🗑️ ❯ Commande /supprimer [Administrateurs]", value="• **Syntaxe :** `/supprimer identifiant_message: `\n" "• Supprime l'annonce ou le sondage ciblé du salon Discord.\n" "• Purge instantanément l'élément de la base de données persistante.", inline=False ) embed.add_field( name="🔍 ❯ Commande /check [Administrateurs]", value="• **Syntaxe :** `/check cible: [choix]`\n" "• Analyse silencieusement l'état des MP de chaque membre **sans envoyer le moindre message**.\n" "• Indique précisément qui a ses MP ouverts et qui les a fermés.", inline=False ) embed.add_field( name="🔒 ❯ Paramètres Requis pour les Messages Privés (MP)", value="Pour recevoir les diffusions sans blocage :\n" "1. Clic droit sur l'icône du serveur ➔ **Paramètres de confidentialité**.\n" "2. Activer **Messages privés** (Vert / ON).", inline=False ) embed.add_field( name="📑 ❯ Canal de Supervision (Logs)", value=f"Toutes les actions, réponses reçues en MP, votes et erreurs techniques sont transmis sur <#{LOG_CHANNEL_ID}>.", inline=False ) embed.set_footer(text="BOTBARBAK • Système automatisé • Développé avec excellence") embed.timestamp = discord.utils.utcnow() await interaction.response.send_message(embed=embed, ephemeral=False) # Gestion globale des erreurs des slash commands @bot.tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if interaction.response.is_done(): await interaction.followup.send("❌ Une erreur est survenue lors du traitement.", ephemeral=True) else: await interaction.response.send_message("❌ Une erreur est survenue lors du traitement.", ephemeral=True) await send_log( title="⚠️ Erreur d'Exécution de Commande", description=f"Une erreur s'est produite lors de la commande exécutée par {interaction.user.mention}.", color=discord.Color.red(), dev_details=f"command: {interaction.command.name if interaction.command else 'Unknown'}\nerror_type: {type(error).__name__}\nerror_msg: {str(error)}" ) # Écoute des réponses envoyées en message privé (DM) @bot.event async def on_message(message: discord.Message): if message.author.bot: return # Si le message est envoyé en privé (hors serveur) if message.guild is None: content_text = message.content or "*(Aucun texte - média uniquement)*" attachments_info = [a.url for a in message.attachments] dev_info = ( f"user_id: {message.author.id}\n" f"user_name: {message.author.name}\n" f"display_name: {message.author.display_name}\n" f"attachments: {attachments_info}" ) await send_log( title="📩 ❯ Réponse Reçue en Message Privé", description=f"**{message.author.display_name}** ({message.author.mention}) a répondu au bot en MP :\n>>> {content_text}", color=GOLD_COLOR, dev_details=dev_info ) try: await message.channel.send("🤖 *Votre message a bien été transmis aux administrateurs dans le salon de supervision.*") except Exception: pass await bot.process_commands(message) # Synchronisation et Enregistrement des Vues persistantes @bot.event async def on_ready(): bot_status["connected"] = True bot_status["user"] = f"{bot.user.name} ({bot.user.id})" bot_status["guilds"] = len(bot.guilds) # Re-register views for existing announcements and polls for ann_id in bot_storage.get("announcements", {}): bot.add_view(AnnouncementView(ann_id)) for poll_id, p_data in bot_storage.get("polls", {}).items(): bot.add_view(PollView(poll_id, p_data.get("options", []))) # Ensure all target roles exist in each guild for guild in bot.guilds: await get_or_create_target_roles(guild) try: synced = await bot.tree.sync() print(f"[SYNC] {len(synced)} commande(s) slash synchronisée(s).") except Exception as e: print(f"[ERROR] Échec de la synchronisation des slash commands: {e}") print(f"[READY] Connecté en tant que {bot_status['user']} sur {bot_status['guilds']} serveur(s).") # Startup Log in dedicated log channel await send_log( title="🟢 Démarrage du Bot Opérationnel", description=f"Le bot est connecté et prêt sur **{bot_status['guilds']}** serveur(s).\n" f"Rôles cibles configurés : **Fils du Prince**, **Inscrit Cold War**, **Inscrit W-N**.", color=discord.Color.green(), dev_details=f"bot_name: {bot.user.name}\nbot_id: {bot.user.id}\nlatency_ms: {round(bot.latency * 1000)}\nsynced_commands: {len(bot.tree.get_commands())}" ) def run_bot(): token = os.getenv("DISCORD_TOKEN") if not token: print("[ERROR] DISCORD_TOKEN manquant.") return bot.run(token) threading.Thread(target=run_bot, daemon=True).start() # --- Gradio UI --- def get_status(): if bot_status["connected"]: ann_count = len(bot_storage.get("announcements", {})) poll_count = len(bot_storage.get("polls", {})) return ( f"🟢 En ligne\n" f"Bot : {bot_status['user']}\n" f"Serveurs : {bot_status['guilds']}\n" f"Annonces enregistrées : {ann_count}\n" f"Sondages actifs : {poll_count}\n" f"Canal de logs : {LOG_CHANNEL_ID}\n" f"Rôles cibles : Fils du Prince, Inscrit Cold War, Inscrit W-N" ) return "🔴 Hors-ligne (connexion en cours ou token manquant...)" with gr.Blocks(title="BOTBARBAK Discord Bot") as demo: gr.Markdown("# 🤖 BOTBARBAK - Tableau de Bord Discord") status_box = gr.Textbox(label="État du Bot", value=get_status, every=5) refresh_btn = gr.Button("Actualiser l'état") refresh_btn.click(fn=get_status, outputs=status_box) if __name__ == "__main__": demo.launch(server_name="0.0.0.0", server_port=7860)