Skip to content

Instantly share code, notes, and snippets.

@http-nova
Forked from AbstractUmbra/00-deprecation.md
Created February 19, 2024 18:08
Show Gist options
  • Save http-nova/0048382e705783dff46fc6c28d6e1b4f to your computer and use it in GitHub Desktop.
Save http-nova/0048382e705783dff46fc6c28d6e1b4f to your computer and use it in GitHub Desktop.
discord.py 2.0+ slash command info and examples

Slash Commands and you

This short example will cover how to make slash commands within an ext.commands.Bot's extension and Cog ecosystem.

There will be 3 examples:

  • A Cog Group, which will house all sub-commmands and the Cog is the parent.

    • This means the Cog class is regarded as the parent command, and all commands defined are "sub" commands. e.g. /cog sub_cmd
  • A free Cog, where all commands will be top-level.

    • This means like: i.e /my_cmd
  • A hybrid of the two, for when you want to group them accordingly.

    • So this will allow: i.e /parent sub_1, /parent sub_2 and /hello
from discord import app_commands
from discord.ext import commands
class MyCog(commands.Cog):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
@app_commands.command(name="command-1")
async def my_command(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message("Hello from command 1!", ephemeral=True)
@app_commands.command(name="command-2")
@app_commands.guilds(discord.Object(id=...), ...)
async def my_private_command(self, interaction: discord.Interaction) -> None:
await interaction.response.send_message("Hello from private command!", ephemeral=True)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog(bot))
# for simplicity, these commands are all global. You can add `guild=` or `guilds=` to `Bot.add_cog` in `setup` to add them to a guild.
from discord import app_commands
from discord.ext import commands
class MyCog(commands.Cog, app_commands.Group, name="parent"):
def __init__(self, bot: commands.Bot) -> None:
self.bot = bot
super().__init__() # this is now required in this context.
@app_commands.command(name="sub-1")
async def my_sub_command_1(self, discord.Interaction) -> None:
await interaction.response.send_message("Hello from sub command 1", ephemeral=True)
@app_commands.command(name="sub-2")
async def my_sub_command_2(self, discord.Interaction) -> None:
await interaction.response.send_message("Hello from sub command 2", ephemeral=True)
async def setup(bot: commands.Bot) -> None:
await bot.add_cog(MyCog(bot))
# or if you want guild/guilds only...
await bot.add_cog(MyCog(bot), guilds=[discord.Object(id=...)])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment