Search code examples
pythonchatbotdiscord.py

Calling a command from another command discord.py


I'm using discord.py and wanted to call a command from another command. There are many questions like that in stack overflow but the difference in mine is that I don't want the command that is going to be called to be available for the user to call.

For Example:

Let's say that I have an animals category and have two commands in that category such as (jokes, pictures) as an example. Then if the command prefix was !.

The user would type !animals joke or !animals pictures.

This should return the desired results.

I thought I could do that by:

animals.py:

@commands.command
async def animals(self, ctx, com_name):
    await ctx.invoke(self.bot.get_command(com_name))

jokes.py

@commands.command
async def joke(self, ctx):
   await ctx.send('a random joke')

Now if the user types !animals joke it will work but they would then be able to type !joke and that would also work. How could I only let the command be called if the category is also present.

Thanks.


Solution

  • You can create an animals Group and then have joke be a subcommand:

    @commands.group()
    async def animals(self, ctx):
        pass
    
    @animals.command()
    async def joke(self, ctx):
       await ctx.send('a random joke')
    

    Another option would be adding a check on joke that is always false

    fail = commands.check(lambda ctx: False)
    
    @fail
    @commands.command()
    async def joke(self, ctx):
       await ctx.send('a random joke')