How do i make a working slash command in discord.py

Note: I will include a version for pycord at the end because I think it’s much simpler, also it was the original answer.


discord.py version

First make sure that you have the newest version of discord.py installed.
In your code, you first import the library:

import discord
from discord import app_commands

and then you define your client and tree:

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)

The tree holds all of your application commands. Then you can define your command:

@tree.command(name = "commandname", description = "My first application Command", guild=discord.Object(id=12417128931)) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def first_command(interaction):
    await interaction.response.send_message("Hello!")

Then you also have to sync your commands to discord once the client is ready, so we do that in the on_ready event:

@client.event
async def on_ready():
    await tree.sync(guild=discord.Object(id=Your guild id))
    print("Ready!")

And at the end we have to run our client:

client.run("token")

pycord version

To install py-cord, first run pip uninstall discord.py and then pip install py-cord.
Then in your code, first import the library with

import discord
from discord.ext import commands

create you bot class with

bot = commands.Bot()

and create your slash command with

@bot.slash_command(name="first_slash", guild_ids=[...]) #Add the guild ids in which the slash command will appear. If it should be in all, remove the argument, but note that it will take some time (up to an hour) to register the command if it's for all guilds.
async def first_slash(ctx): 
    await ctx.respond("You executed the slash command!")

and then run the bot with your token

bot.run(TOKEN)

Leave a Comment