Create a simple slash command using the @bot.slash_command() decorator:
import discordbot = discord.Bot()@bot.slash_command(guild_ids=[...]) # Remove guild_ids to make it globalasync def hello(ctx: discord.ApplicationContext): """Say hello to the bot""" # This becomes the command description await ctx.respond(f"Hello {ctx.author}!")bot.run("TOKEN")
Interactions must be responded to within 3 seconds. If your command takes longer, use await ctx.defer() first.
Add parameters to your slash commands using the Option class:
from discord import option@bot.slash_command()@option("name", description="Enter your name")@option( "pokemon", description="Choose your starter Pokémon", choices=["Bulbasaur", "Squirtle", "Charmander", "Pikachu"],)@option( "age", description="Enter your age", min_value=1, max_value=99, default=18, # Makes the argument optional)async def hello( ctx: discord.ApplicationContext, name: str, pokemon: str, age: int,): await ctx.respond( f"Hello {name}! Your starter is {pokemon} and you are {age} years old." )
async def get_colors(ctx: discord.AutocompleteContext): """Returns a list of colors that match the user's input.""" colors = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"] return [color for color in colors if color.startswith(ctx.value.lower())]@bot.slash_command()@option("color", description="Pick a color", autocomplete=get_colors)async def favorite(ctx: discord.ApplicationContext, color: str): await ctx.respond(f"Your favorite color is {color}!")
math = bot.create_group("math", "Commands related to mathematics")@math.command()async def add(ctx: discord.ApplicationContext, num1: int, num2: int): """Get the sum of 2 integers.""" await ctx.respond(f"The sum is **{num1 + num2}**")@math.command()async def multiply(ctx: discord.ApplicationContext, num1: int, num2: int): """Get the product of 2 integers.""" await ctx.respond(f"The product is **{num1 * num2}**")
math = discord.SlashCommandGroup("math", "Commands related to mathematics")@math.command()async def subtract(ctx: discord.ApplicationContext, num1: int, num2: int): """Get the difference of 2 integers.""" await ctx.respond(f"The difference is **{num1 - num2}**")bot.add_application_command(math)
from discord import default_permissions@bot.slash_command()@default_permissions(administrator=True)async def setup(ctx: discord.ApplicationContext): """Only administrators can use this command.""" await ctx.respond("Setting up...")
@bot.slash_command(contexts={discord.InteractionContextType.guild})async def guild_only(ctx: discord.ApplicationContext): """This command only works in servers.""" await ctx.respond(f"Server: {ctx.guild.name}")
@bot.slash_command()async def slow(ctx: discord.ApplicationContext): await ctx.defer() # Show "Bot is thinking..." # Do something that takes time await asyncio.sleep(5) await ctx.followup.send("Done!")