ChessDebate/slowbot.py

169 lines
6.4 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import discord
from discord import app_commands
from discord.ext import commands
import asyncio
import json
intents = discord.Intents.default()
intents.message_content = True
intents.guilds = True
intents.members = True
bot = commands.Bot(command_prefix="!", intents=intents)
# Configuration par défaut
config = {
"slowmode_duration": 20,
"affected_roles": [],
"bot_name": "SlowBot",
"bot_avatar": None
}
def save_config():
with open("config.json", "w") as f:
json.dump(config, f)
def load_config():
global config
try:
with open("config.json", "r") as f:
config = json.load(f)
except FileNotFoundError:
save_config()
@bot.event
async def on_ready():
print(f"{bot.user} est en ligne.")
load_config()
# Change le nom et avatar si nécessaire
if bot.user.name != config["bot_name"]:
await bot.user.edit(username=config["bot_name"])
if config["bot_avatar"]:
with open(config["bot_avatar"], "rb") as f:
await bot.user.edit(avatar=f.read())
try:
synced = await bot.tree.sync()
print(f"Commands synced: {len(synced)}")
except Exception as e:
print(f"Erreur lors de la sync des commandes : {e}")
# Slash command : définir le slowmode
@bot.tree.command(name="setslowmode", description="Définit la durée du slowmode dans les threads (en secondes)")
@app_commands.checks.has_permissions(manage_threads=True)
@app_commands.describe(seconds="Durée du slowmode en secondes")
async def setslowmode(interaction: discord.Interaction, seconds: int):
config["slowmode_duration"] = seconds
save_config()
updated_threads = 0
failed_threads = []
for thread in interaction.guild.threads:
if not thread.archived:
try:
await thread.edit(slowmode_delay=seconds)
updated_threads += 1
except Exception as e:
failed_threads.append(thread.name)
message = f"✅ Slowmode par défaut défini à {seconds} secondes.\n"
message += f"🧵 Slowmode mis à jour dans {updated_threads} thread(s)."
if failed_threads:
message += f"\n⚠️ Impossible de modifier : {', '.join(failed_threads)}"
await interaction.response.send_message(message, ephemeral=True)
# Slash command : définir les rôles affectés par le slowmode
@bot.tree.command(name="setroles", description="Définit les rôles affectés par le slowmode")
@app_commands.checks.has_permissions(manage_roles=True)
@app_commands.describe(roles="Mentionnez les rôles (ex: @modérateur @admin)")
async def setroles(interaction: discord.Interaction, roles: str):
guild = interaction.guild
role_ids = []
for part in roles.split():
if part.startswith("<@&") and part.endswith(">"):
try:
role_id = int(part[3:-1])
role = guild.get_role(role_id)
if role:
role_ids.append(role.id)
except ValueError:
continue
if not role_ids:
await interaction.response.send_message("❌ Aucun rôle valide détecté. Veuillez mentionner les rôles.", ephemeral=True)
return
config["affected_roles"] = role_ids
save_config()
names = [guild.get_role(rid).name for rid in role_ids]
await interaction.response.send_message(f"✅ Rôles affectés mis à jour : {', '.join(names)}", ephemeral=True)
#A enlever ?
# Slash command : changer le nom du bot
@bot.tree.command(name="setbotname", description="Change le nom du bot")
@app_commands.checks.has_permissions(administrator=True)
@app_commands.describe(name="Nouveau nom du bot")
async def setbotname(interaction: discord.Interaction, name: str):
config["bot_name"] = name
save_config()
await bot.user.edit(username=name)
await interaction.response.send_message(f"✅ Nom du bot changé en {name}.", ephemeral=True)
# Slash command : aide
@bot.tree.command(name="help", description="Affiche la liste des commandes disponibles")
async def help_command(interaction: discord.Interaction):
help_text = """
**📋 Commandes Slash :**
- `/setslowmode <seconds>` : Définit la durée du slowmode dans les threads.
- `/setroles <@role1 @role2>` : Définit les rôles affectés par le slowmode.
- `/setbotname <nom>` : Change le nom du bot.
- `/setbotavatar` : Change lavatar du bot (envoyez une image avant).
- `/help` : Affiche cette aide.
"""
await interaction.response.send_message(help_text, ephemeral=True)
@bot.event
async def on_thread_create(thread):
try:
await thread.edit(slowmode_delay=config["slowmode_duration"])
print(f"✅ Slowmode de {config['slowmode_duration']}s appliqué à {thread.name}")
except Exception as e:
print(f"❌ Impossible de définir le slowmode sur {thread.name} : {e}")
@bot.event
async def on_message(message):
await bot.process_commands(message)
if message.author.bot:
return
if isinstance(message.channel, discord.Thread):
if any(role.id in config["affected_roles"] for role in message.author.roles):
now = discord.utils.utcnow()
if hasattr(message.author, "last_message_time"):
delta = (now - message.author.last_message_time).total_seconds()
if delta < config["slowmode_duration"]:
await message.delete()
remaining = int(config["slowmode_duration"] - delta)
await message.channel.send(
f"{message.author.mention}, slowmode actif. Réessaie dans {remaining} secondes.",
delete_after=5
)
return
message.author.last_message_time = now
# Gestion derreurs pour slash commands
@bot.tree.error
async def on_app_command_error(interaction: discord.Interaction, error):
if isinstance(error, app_commands.MissingPermissions):
await interaction.response.send_message("❌ Permissions insuffisantes pour cette commande.", ephemeral=True)
elif isinstance(error, app_commands.CommandOnCooldown):
await interaction.response.send_message("⏳ Cette commande est en cooldown, merci de patienter.", ephemeral=True)
else:
await interaction.response.send_message(f"❌ Une erreur est survenue : {error}", ephemeral=True)
print(f"Erreur commande slash : {error}")
# Lancer le bot (⚠️ remplace la clé par une vraie token sécurisée)
bot.run("MTM4MTk4ODA2NjUwMzQzMDI0Nw.G_7FMX.DMZ32kmoTHRnGHaQ1TEc_o1EwHAt-Tvkkb-ADQ")