ShahRiz Marks
ShahRiz Marks

Reputation: 33

Discord.py Slash commands don't work in cogs

I am building a discord bot, and want to use slash commands inside cogs, but the commands don't show or work, here is the code


## cog
guild_ids = [858573429787066368, 861507832934563851]

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

    @cog_ext.cog_slash(name="test", guild_ids=guild_ids, description="test")
    async def _test(self, ctx: SlashContext):
        embed = Embed(title="Embed Test")
        await ctx.send(embed=embed)


## bot
bot = discord.ext.commands.Bot(command_prefix = "!")

@bot.event
async def on_ready():
  print(f'{bot.user} has logged in.')
  bot.load_extension('slash_music_cog')

bot.run("bot-token")

Upvotes: 3

Views: 8867

Answers (3)

Sajid Zakaria
Sajid Zakaria

Reputation: 1

After much hassle, I've finally found out how to do it. Your main.py/bot.py should look something like this:

bot = commands.Bot(command_prefix=commands.when_mentioned_or('!'), intents=intents)
slash = SlashCommand(bot, sync_commands=True)

You need to use sync_commands=True, otherwise the commands don't appear or sync, both in the main module and the cogs.

Upvotes: 0

Jakob Møller
Jakob Møller

Reputation: 171

After working at this issue for myself for way longer than I'd like to admit, I've finally found the culprit:
You have to load your cogs before running the bot.
For some reason, it won't register your commands with discord, if you load the cogs in the on_ready function, so the solution here, is to move your extension-loading code to right before your bot.run("bot-token") statement.

So the finished code should look something like

## cog
guild_ids = [858573429787066368, 861507832934563851]

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

    @cog_ext.cog_slash(name="test", guild_ids=guild_ids, description="test")
    async def _test(self, ctx: SlashContext):
        embed = Embed(title="Embed Test")
        await ctx.send(embed=embed)


## bot
bot = discord.ext.commands.Bot(command_prefix = "!")

@bot.event
async def on_ready():
  print(f'{bot.user} has logged in.')


bot.load_extension('slash_music_cog')
bot.run("bot-token")

Upvotes: 5

Seon
Seon

Reputation: 3975

You'll need to slightly modify the bot.py file to initialize a SlashCommand object. Take a look at the library's README for a slightly more detailed example of a bot using cogs.

# bot
from discord_slash import SlashCommand

bot = discord.ext.commands.Bot(command_prefix = "!")
slash = SlashCommand(bot)

@bot.event
async def on_ready():
  print(f'{bot.user} has logged in.')
  bot.load_extension('slash_music_cog')

bot.run("bot-token")

Upvotes: 0

Related Questions