我如何在discord.py中创建一个有效的斜杠命令

Ada*_*boy 23 python discord discord.py

我正在尝试使用 discord.py 创建斜杠命令,我已经尝试了很多东西,但它似乎不起作用。如有帮助,将不胜感激。

Loa*_*ahL 34

注意:我将在最后包含 pycord 的版本,因为我认为它更简单,也是最初的答案。


不和谐.py版本

首先确保您安装了最新版本的discord.py。在您的代码中,首先导入该库:

import discord
from discord import app_commands
Run Code Online (Sandbox Code Playgroud)

然后定义你的客户端和树:

intents = discord.Intents.default()
client = discord.Client(intents=intents)
tree = app_commands.CommandTree(client)
Run Code Online (Sandbox Code Playgroud)

该树包含所有应用程序命令。然后你可以定义你的命令:

# 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!")
Run Code Online (Sandbox Code Playgroud)

然后,一旦客户端准备好,您还必须同步您的命令以进行不一致,因此我们在以下on_ready情况下这样做:

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

最后我们必须运行我们的客户端:

client.run("token")
Run Code Online (Sandbox Code Playgroud)

pycord版本

要安装 py-cord,请先运行pip uninstall discord.py,然后运行pip install py-cord​​. 然后在您的代码中,首先使用以下命令导入库

import discord
from discord.ext import commands
Run Code Online (Sandbox Code Playgroud)

创建你的机器人

bot = commands.Bot()
Run Code Online (Sandbox Code Playgroud)

并创建你的斜杠命令

# 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!")
Run Code Online (Sandbox Code Playgroud)

然后用你的令牌运行机器人

bot.run(TOKEN)
Run Code Online (Sandbox Code Playgroud)


小智 7

# 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")
Run Code Online (Sandbox Code Playgroud)