Command.ext decorators not responding in subclass

Yorumlar

1 yorum

  • cereales

    Hello,

    I ran into the same issue, an nobody seems to answer to this on the net.
    Even if this post is more than 2 years old, let me share what I learned for people who will fall into this page.

    As suggested by the owner of discord.py API, you should use Cogs.

     

    Explanations

    There are two different ways to declare discord bot.

    1. Using an instance of commands.Bot and bot.command() decorator on top of methods declared in the main script.
    2. Creating a subclass of commands.Bot and override methods.

    But the second way seems not able to support custom commands as the self or bot object does not exist. And the commands.command() decorator does not work.

    As suggested in discord.py issues, you should use Cogs. Here is the example I am using. I am not sure this is the best way to do, but it works as expected.

    import discord
    from discord.ext import commands
    
    
    class PersonalBot(commands.Bot):
        def __init__(self):
            intents = discord.Intents.all()     # Giving all permissions for the example
            super().__init__(command_prefix="!", intents=intents)
    
        # First Event: when discord bot is ready
        async def on_ready(self):
            await self.add_cog(CommandGroup(self)) # Register 1 group (Cog) of commands
    
        #################################################
        async def hello(self, ctx):                    ## <----- cannot trigger
            await ctx.channel.send("Hello i am bot")   ##
        #################################################
    
        # Second Event: Natural Language Processor
        async def on_message(self, message):
            await super().on_message(message)   # Forward event to Bot, not to block commands detection, etc
            # Do things...
    
    
    class CommandGroup(commands.Cog, name="group1"):
        @commands.command(name="hello")
        async def hello(self, ctx):
            await ctx.send("Hello I am a bot.")
    
    
    client = PersonalBot()
    client.run(DISCORD_TOKEN, reconnect=True)

     

    Useful Links:

    - discord.py issue #5153 : https://github.com/Rapptz/discord.py/issues/5153
    - discord.py issue #2031 : https://github.com/Rapptz/discord.py/issues/2031#issuecomment-478205413
    - How to use Cogs : https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
    - API Reference - Cogs documentation : https://discordpy.readthedocs.io/en/latest/ext/commands/api.html#cogs
     

    0

Yorum yazmak için lütfen oturum açın.