Search code examples
pythondiscorddiscord.py

decorator @bot.tree.command in Cog


How should I use decorator @bot.tree.command in class?

My main file:

import os
import discord
from dotenv import load_dotenv
from discord.ext import commands, tasks

extens = ["cogs.slash_commands"]


class MyBot(commands.Bot):

    def __init__(self):
        super().__init__(command_prefix='/', intents=discord.Intents.all())

    async def on_ready(self):
        print(f'{self.user} is now running!')
        for cog in extens:
            try:
                await bot.load_extension(cog)
                print(f"{cog} was loaded.")
            except Exception as e:
                print(e)
bot = MyBot()
load_dotenv()
bot.run(os.getenv('TOKEN'))

And my cog look like this

import discord
from discord import app_commands
from discord.ext import commands


class SlashCommands(commands.Cog):
    
    def __init__(self, bot):
        self.bot = bot

    @commands.tree.command
    async def hello(self, interaction: discord.Interaction, thing_to_say: str):
        await interaction.response.send_message(f"{thing_to_say}")


async def setup(bot):
    await bot.add_cog(SlashCommands(bot))

When I compile it says:

Extension 'cogs.slash_commands' raised an error: AttributeError: module 'discord.ext.commands' has no attribute 'tree'

What should I do? What should I add in my main file and edit in my cog file?


Solution

  • To add a slash command in a cogs class, we use the @app_commands.command() decorator.

    import discord
    from discord import app_commands
    from discord.ext import commands
    
    
    class SlashCommands(commands.Cog):
        def __init__(self, bot):
            self.bot = bot
    
        @app_commands.command()
        async def hello(self, interaction: discord.Interaction, thing_to_say: str):
            await interaction.response.send_message(f"{thing_to_say}")
    
    
    async def setup(bot):
        await bot.add_cog(SlashCommands(bot))
    

    This is similar to how we add prefix commands in cogs with the @commands.command() decorator. This is because we are not just adding a singular command to the command tree like with bot.tree.command, we are adding the entire Cog class with the commands inside of it.