I am trying to make a slash command with discord.py I have tried a lot of stuff it doesn't seem to be working. Help would be appreciated.
Note: I will include a version for pycord at the end because I think it's much simpler, also it was the original answer.
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:
# 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.
@tree.command(
name="commandname",
description="My first application Command",
guild=discord.Object(id=12417128931)
)
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")
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 your bot with
bot = commands.Bot()
and create your slash command with
# 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.
@bot.slash_command(
name="first_slash",
guild_ids=[...]
)
async def first_slash(ctx):
await ctx.respond("You executed the slash command!")
and then run the bot with your token
bot.run(TOKEN)
# This is new in the discord.py 2.0 update
# imports
import discord
import discord.ext
# setting up the bot
intents = discord.Intents.all()
# if you don't want all intents you can do discord.Intents.default()
client = discord.Client(intents=intents)
tree = discord.app_commands.CommandTree(client)
# sync the slash command to your server
@client.event
async def on_ready():
await tree.sync(guild=discord.Object(id=Your guild ID here))
# print "ready" in the console when the bot is ready to work
print("ready")
# make the slash command
@tree.command(name="name", description="description")
async def slash_command(interaction: discord.Interaction):
await interaction.response.send_message("command")
# run the bot
client.run("token")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With