How to code sub commands for discord.py but they are slash commands and in a cog file

992 Views Asked by At

So I am making a sub command group named set. Then the commands that are in that group are, profile, introduction, birthday etc. These commands should be slash commands (interaction commands) But I cannot figure out how to do this.

I've tried this from watching some youtube videos but the videos were explaining how to do this when it is written in the main file and when it is a ctx command.

@app_commands.group(name='set')
    async def set(self, interaction:discord.Interaction):
        if interaction.invoked_subcommand is None:
            await interaction.response.send_message('Please specify a subcommand. Available subcommands: helpchat, helpvoice, helpnotif, helpchannel')
@set.command(name="introduction", description="Set your introduction so that other people can know who you are!")
async def introduction(self, interaction: discord.Interaction):
    await interaction.response.send_modal(IntroModal())
1

There are 1 best solutions below

0
On
import discord
from discord import app_commands
from discord.ext import commands


class MyCog(commands.Cog):
  def __init__(self, bot: commands.Bot) -> None:
    self.bot = bot
    
  group = app_commands.Group(name="parent", description="...")
  # Above, we declare a command Group, in discord terms this is a parent command
  # We define it within the class scope (not an instance scope) so we can use it as a decorator.
  # This does have namespace caveats but i don't believe they're worth outlining in our needs.

  @app_commands.command(name="top-command")    # a command outside the group
  async def my_top_command(self, interaction: discord.Interaction) -> None:
    """ /top-command """
    await interaction.response.send_message("Hello from top level command!", ephemeral=True)

  @group.command(name="sub-command")    # we use the declared group to make a command.
  async def my_sub_command(self, interaction: discord.Interaction) -> None:
    """ /parent sub-command """
    await interaction.response.send_message("Hello from the sub command!", ephemeral=True)

async def setup(bot: commands.Bot) -> None:
  await bot.add_cog(MyCog(bot))

Reference: