Mi bot de Discord funciona pero no ejecuta ningún comando
Hola o buenas noches, así que aquí está el problema. He creado un bot de Discord, puedo iniciarlo, aparece en línea y tengo el mensaje "En marcha!" que se muestra. El problema es que tan pronto como hago un comando del estilo !fishA o alguno otro, primero, el comando no se ejecuta y segundo, no tengo el mensaje en el terminal que me demuestre que el comando se ha realizado.
import discord from discord.ext import commands, tasks intents = discord.Intents.default() intents.typing = False intents.presences = False intents.messages = True bot = commands.Bot(command_prefix='!', intents=intents) global current_command current_command = ***@*** async def on_ready(): print("En marche !") @bot.command(name='fishA') async def fishA(ctx): global current_command current_command = 'A' fish.change_interval(seconds=3.5) fish.start() @bot.command(name='fishB') async def fishB(ctx): global current_command current_command = 'B' fish.change_interval(seconds=3.2) fish.start() @bot.command(name='fishC') async def fishC(ctx): global current_command current_command = 'C' fish.change_interval(seconds=3.0) fish.start() @tasks.loop(seconds=3.0) async def fish(): global running, current_command if not running: return print(f"Running fish command: {current_command}") await bot.get_channel(1212683308635267112).send('/fish') @bot.command(name='stopfish') async def stopfish(ctx): global running running = ***@***d(name='fish') async def fish(ctx, letter: str): global running if letter not in bot.command: await ctx.send(f'Invalid fish command: {letter}') return running = True fish.change_interval(seconds=bot.command[letter]) fish.start() bot.run("") Merci d'avance pour votre aide.
5 respuestas
-
Hola,
Antes de entrar en materia, te desaconsejo tus propios mensajes, es la mejor forma de que la gente piense erróneamente que alguien ya está interactuando contigo. En el futuro, sería mejor corregir el mensaje inicial para que el hilo de la conversación aparezca sin respuesta.
Con respecto a tu código, veo que hay funciones, y algunas tienen nombres con caracteres acentuados, lo cual es una causa probable de tu problema. Para evitar este obstáculo, te recomiendo además que compiles en inglés; es una buena costumbre para la continuación.
En respuesta a #5 : también puedes trazar lo que sucede con el módulo logging como explicado aquí. Eso te permitirá ver si atraviesas una función, el valor de las variables locales, etc... como ya lo habías hecho en #4 para que sepamos dónde te encuentras y qué queda por depurar.
Buena suerte
-
UPDATE, I changed the code, but still nothing. I’m putting the code here anyway to support you or even see if you notice any error or other.
import discord from discord.ext import commands, tasks import asyncio intents = discord.Intents.default() intents.typing = False intents.presences = False intents.messages = True bot = commands.Bot(command_prefix='/', intents=intents) # Les commandes et leurs intervalles commands = { 'A': 3.5, 'B': 3.2, 'C': 3.0, 'D': 2.7, 'E': 2.4 } @bot.event async def on_ready(): print("En marche !") # Dictionnaire pour stocker les tâches en cours d'exécution running_tasks = {} # La fonction qui envoie le message async def send_message(channel, command): await channel.send(f'/fish {command}') # Les commandes fishA, fishB, fishC, fishD, ***@***d(name='fishA') async def fishA(ctx): interval = commands.get('A') await start_fishing(ctx, 'A', interval) @bot.command(name='fishB') async def fishB(ctx): interval = commands.get('B') await start_fishing(ctx, 'B', interval) @bot.command(name='fishC') async def fishC(ctx): interval = commands.get('C') await start_fishing(ctx, 'C', interval) @bot.command(name='fishD') async def fishD(ctx): interval = commands.get('D') await start_fishing(ctx, 'D', interval) @bot.command(name='fishE') async def fishE(ctx): interval = commands.get('E') await start_fishing(ctx, 'E', interval) # Fonction pour démarrer la tâche de pêche avec l'intervalle spécifié async def start_fishing(ctx, command, interval): if command not in running_tasks: running_tasks[command] = bot.loop.create_task(fish_loop(ctx, command, interval)) await ctx.send(f'La commande fish{command} a été démarrée avec un intervalle de {interval} secondes.') else: await ctx.send(f'La commande fish{command} est déjà en cours.') # Fonction pour boucler l'envoi de la commande à l'intervalle spécifié async def fish_loop(ctx, command, interval): channel = ctx.channel while True: await send_message(channel, command) await asyncio.sleep(interval) # Le code qui arrête les tâ***@***d(name='stopfish') async def stopfish(ctx): global running_tasks for task in running_tasks.values(): task.cancel() running_tasks = {} await ctx.send('Toutes les tâches de pêche ont été arrêtées.') # Lancement du bot bot.run -
Hola, al buscar la advertencia:
https://duckduckgo.com/?t=ffab&q=privileged+message+content+intent+is+missing&ia=web
Que indica principalmente añadir
intent.message_content = True
Y faltan los paréntesis en bot.run en tu código, así que obviamente no pasa nada.
-
Buenas noches, Aquí tienes una traducción fiel al texto original:
import discord import asyncio from discord import Intents from discord.ext import commands # Crea un objeto Intents para definir las intenciones intents = Intents( messages=True, guilds=True, reactions=True, presences=True, members=True ) # Inicialización del bot con el prefijo de comando bot = commands.Bot(command_prefix='/', intents=intents) # ID canal Discord ID_DE_CANAL = # Token bot Discord TOKEN = # Intervalo por defecto para la pesca en segundos INTERVALLE_PAR_DEFAUT = 3.5 # Diccionario para almacenar los intervalos especificados para cada comando intervalles = { "/fishA": 3.5, # Ejemplo: Pescar cada 3.5 segundos con el comando /fishA "/fishB": 3.2, # Ejemplo: Pescar cada 3.2 segundos con el comando /fishB "/fishC": 3, # Ejemplo: Pesc ar cada 3 segundos con el comando /fishC "/fishD": 2.7, # Ejemplo: Pesc ar cada 2.7 segundos con el comando /fishD "/fishE": 2.4, # Ejemplo: Pesc ar cada 2.4 segundos con el comando /fishE } async def pêcher(channel, interval): while True: await asyncio.sleep(interval) await channel.send('/fish') # Evento disparado cuando el bot está listo***@*** async def on_ready(): print(f'Conectado como {bot.user}') channel = bot.get_channel(int(ID_DE_CANAL)) await channel.send('Bot listo para pescar !') # Comando para empezar la pê***@***d() async def fish(ctx, type): if type in intervalles: interval = intervalles[type] await pêcher(ctx.channel, interval) else: await ctx.send("Tipo de pesca inválido !") # Comando para detener la pê***@***d() async def stopfish(ctx): await ctx.send('Pesca detenida.') for task in asyncio.all_tasks(): task.cancel() @bot.event async def on_message(message): print("Mensaje recibido:", message.content) if message.author == bot.user: return # Verificar si el mensaje empieza por un comando válido if message.content.startswith(tuple(intervalles.keys())): # Obtener el comando a partir del mensaje command = message.content.split()[0] # Verificar si el comando está en el diccionario de intervalos if command in intervalles: interval = intervalles[command] await pêcher(message.channel, interval) else: await message.channel.send("Tipo de pesca inválido !") else: # Si no es un comando, responder a todos los mensajes await message.channel.send("Soy un bot de Discord y respondo a todos los mensajes !") # Iniciar el bot bot.run(TOKEN)Buenas noches,
-
import discord import asyncio from discord import Intents from discord.ext import commands # Crée un objet Intents pour définir les intentions intents = Intents( messages=True, guilds=True, reactions=True, presences=True, members=True ) # Initialisation du bot avec le préfixe de commande bot = commands.Bot(command_prefix='/', intents=intents) # ID canal Discord ID_DE_CANAL = # Token bot Discord TOKEN = # Intervalle par défaut pour la pêche en secondes INTERVALLE_PAR_DEFAUT = 3.5 # Dictionnaire pour stocker les intervalles spécifiés pour chaque commande intervalles = { "/fishA": 3.5, # Exemple : Pêcher toutes les 3.5 secondes avec la commande /fishA "/fishB": 3.2, # Exemple : Pêcher toutes les 3.2 secondes avec la commande /fishB "/fishC": 3, # Exemple : Pêcher toutes les 3 secondes avec la commande /fishC "/fishD": 2.7, # Exemple : Pêcher toutes les 2.7 secondes avec la commande /fishD "/fishE": 2.4, # Exemple : Pêcher toutes les 2.4 secondes avec la commande /fishE } async def pêcher(channel, interval): while True: await asyncio.sleep(interval) await channel.send('/fish') # Événement déclenché lorsque le bot est prê***@*** async def on_ready(): print(f'Connecté en tant que {bot.user}') channel = bot.get_channel(int(ID_DE_CANAL)) await channel.send('Bot prêt à pêcher !') # Commandes de pêche spé***@***d() async def fishA(ctx): interval = intervalles['/fishA'] await pêcher(ctx.channel, interval) @bot.command() async def fishB(ctx): interval = intervalles['/fishB'] await pêcher(ctx.channel, interval) @bot.command() async def fishC(ctx): interval = intervalles['/fishC'] await pêcher(ctx.channel, interval) @bot.command() async def fishD(ctx): interval = intervalles['/fishD'] await pêcher(ctx.channel, interval) @bot.command() async def fishE(ctx): interval = intervalles['/fishE'] await pêcher(ctx.channel, interval) # Commande pour démarrer la pê***@***d() async def fish(ctx, type): if type in intervalles: interval = intervalles[type] await pêcher(ctx.channel, interval) else: await ctx.send("Type de pêche invalide !") # Commande pour arrêter la pê***@***d() async def stopfish(ctx): await ctx.send('Pêche arrêtée.') for task in asyncio.all_tasks(): task.cancel() # Démarrer le bot bot.run(TOKEN)J'ai encore modifié le code, mais toujours rien. Ne vous inquiétez pas le problème n'est pas au niveau de ID_DE_CANAL et de TOKEN, je les ai délibérément enlevé.
Bonne soirée
