Mon bot discord fonctionne mais n'exécute aucune commandes

Bonjour ou bonsoir, alors voici le probleme. J'ai crée un bot discord, je peux le lancer, il y a marqué qu'il est en ligne et j'ai le message "En marche!" qui s'affiche. Le probleme c'est que des que je fais une commande du style !fishA ou une autre, de un, la commande ne s'exécute pas et de deux, je n'ai pas le message dans le terminal qui me prouve que la commande a ete effectué. 

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. 


Windows / Chrome 122.0.0.0

5 réponses

  1. Modérateur

    Bonjour,

    Avant d'entrer dans le vif du sujet, je te déconseille tes propres messages, c'est le meilleur moyen que les gens pensent à tort que quelqu'un interagit déjà avec toi. À l'avenir, il vaudrait mieux corriger le message initial pour que le fil de discussion apparaisse sans réponse. 

    Concernant ton code, je vois que des fonctions dont certaines ont un nom comportant des caractères accentués, ce qui est une cause probable de ton problème. Pour éviter cet écueil, je te recommande d'ailleurs de plutôt coder en anglais, c'est une bonne habitude pour la suite.

    En réponse à #5 : tu peux également tracer ce qui se passe avec le module logging comme expliqué ici. Cela te permettra de voir si tu traverses bien une fonction, la valeur des variables locales, etc... comme tu l'avais d'ailleurs fait dans #4 pour qu'on sache où tu en es et ce qu'il reste à déboguer. 

    Bonne chance

    1
    1. UPDATE, j'ai change le code, mais toujours rien. Je vous mets quand meme le code pour vous appuyer dessus ou meme voir si vous voyer la moindre erreur ou autres.

      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

      Je met aussi ce que me marque mon cmd comme indication

      0
      1. Salut, en cherchant le warning :

        https://duckduckgo.com/?t=ffab&q=privileged+message+content+intent+is+missing&ia=web

        Qui indique majoritairement d'ajouter

        intent.message_content = True

        Et il manque les parenthèses à bot.run dans ton code, donc forcément rien ne se passe.

        0
        1. Merci, je vais essayer ca. Et pour le bot.run ne vous inquiétez pas, j'ai enlevé délibérément le token. Sinon il est bien mis.

          0
      2. 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 !')
              
        
        # 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()
        
        
        @bot.event
        async def on_message(message):
            print("Message reçu:", message.content) 
        
            if message.author == bot.user:
                return
        
            # Vérifier si le message commence par une commande valide
            if message.content.startswith(tuple(intervalles.keys())):
                # Récupérer la commande à partir du message
                command = message.content.split()[0]
                
                # Vérifier si la commande est dans le dictionnaire des intervalles
                if command in intervalles:
                    interval = intervalles[command]
                    await pêcher(message.channel, interval)
                else:
                    await message.channel.send("Type de pêche invalide !")
            else:
                # Si ce n'est pas une commande, répondre à tous les messages
                await message.channel.send("Je suis un bot Discord et je réponds à tous les messages !")
                
        # Démarrer le bot
        bot.run(TOKEN)
        
        
        
        
        

        Bonsoir, après avoir essayer rien n'a changé. Je vous mets mon code modifié mais ca ne marche toujours pas. Le terminal me renvoie ca tout le temps: 


        2024-03-02 22:07:16 WARNING  discord.ext.commands.bot Privileged message content intent is missing, commands may not work as expected.
        2024-03-02 22:07:16 INFO     discord.client logging in using static token
        2024-03-02 22:07:16 INFO     discord.gateway Shard ID None has connected to Gateway (Session ID: 22d68492fd3f2157e069224e21b25271).
        Connecté en tant que BotFish#5865
        Message reçu: Bot prêt à pêcher !

        Le probleme c'est que tout fonctionne, quand je rentre un message le bot arrive a le lire et me reponds "Je suis un bot Discord et je réponds à tous les messages !" mais des qu'il s'agit d'une commande, rien ne se passe et renvoie Message recu: 
        Sans rien derriere. Je ne comprends pas, je suis bloqué je vais voir si il n'y a pas eu de modification au niveau de la bibliotheque Discord.py

        Bonne soirée

        0
        1. 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

          0