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

新手上路,请多包涵

我正在尝试使用 discord.py 创建一个斜杠命令我已经尝试了很多它似乎没有用的东西。帮助将不胜感激。

原文由 Adamyoboy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 1.3k
1 个回答

注意:我将在最后包含一个 pycord 版本,因为我认为它更简单,而且它是原始答案。


discord.py 版本

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

 import discord
from discord import app_commands

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

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

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

 @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!")

然后,一旦客户端准备就绪,您还必须将命令同步到 discord,因此我们在 on_ready 事件中执行此操作:

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

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

 client.run("token")


pycord 版本

要安装 py-cord,首先运行 pip uninstall discord.py 然后运行 --- pip install py-cord 。然后在您的代码中,首先导入库

import discord
from discord.ext import commands

创建你的机器人类

bot = commands.Bot()

并使用创建斜杠命令

@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!")

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

bot.run(TOKEN)

原文由 Chuaat 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题