如何在 discord.py 中创建有效的斜线命令
- 2025-03-21 09:05:00
- admin 原创
- 43
问题描述:
我正在尝试使用 discord.py 创建斜线命令,我试了很多方法,但似乎不起作用。如能提供帮助,我将不胜感激。
解决方案 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)
该树包含所有应用程序命令。然后您可以定义命令:
# 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!")
然后,一旦客户端准备就绪,您还必须将命令同步到 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()
并使用创建斜线命令
# 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!")
然后使用你的令牌运行机器人
bot.run(TOKEN)
解决方案 2:
# 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")
解决方案 3:
他们正在向 discord.py 添加斜线命令,但您可以在https://gist.github.com/Rapptz/c4324f17a80c94776832430007ad40e6中看到一些示例。您似乎正在使用 discord_slash,而我还没有使用过。
这些内容的主要文档是https://discordpy.readthedocs.io/en/master/interactions/api.html?highlight=dropdown#decorators但主要的“操作方法”是您必须制作一棵“树”,将命令附加到该树,然后同步您的树以使命令显示出来。discord.ext.Bot 会生成自己的树,这就是我使用它而不是客户端的原因,我认为客户端默认情况下不会生成树。
如果您指定公会,命令同步会立即进行,但如果您不指定公会,我认为需要一个小时才能更新或类似的东西,因此请指定公会,直到您准备好部署为止。
我不太清楚如何在 cogs 中执行此操作,因为我将其分成了多个组,但基本上我所做的是将主 bot 文件中的 @bot.tree.command() 与单独文件中的几个组进行组合。
这是我的主要文件
import discord
import simplegeneralgroup
from config import TOKEN
MY_GUILD = discord.Object(id=1234567890)
class MyBot(discord.ext.commands.Bot):
async def on_ready(self):
await self.tree.sync(guild=MY_GUILD)
bot: discord.ext.commands.Bot = MyBot
@bot.tree.command(guild=MY_GUILD)
async def slash(interaction: discord.Interaction, number: int, string: str):
await interaction.response.send_message(f'Modify {number=} {string=}', ephemeral=True)
bot.tree.add_command(simplegeneralgroup.Generalgroup(bot), guild=MY_GUILD)
if __name__ == "__main__":
bot.run(TOKEN)
然后是 simplegeneralgroup 文件
import discord
from discord import app_commands as apc
class Generalgroup(apc.Group):
"""Manage general commands"""
def __init__(self, bot: discord.ext.commands.Bot):
super().__init__()
self.bot = bot
@apc.command()
async def hello(self, interaction: discord.Interaction):
await interaction.response.send_message('Hello')
@apc.command()
async def version(self, interaction: discord.Interaction):
"""tells you what version of the bot software is running."""
await interaction.response.send_message('This is an untested test version')
应该有三个命令:/slash,它将提示用户输入数字和字符串、/generalgroup hello 和 /generalgroup version
解决方案 4:
就这么做
from discord import Interaction
from discord import app_commands
@app_commands.command(name="",description="")
async def ping(ctx: Interaction, have_account:bool, login_email:str=None, login_mobile:str=None):
解决方案 5:
使用 discord.py (2.0) 的斜线命令
虽然这是对一个老问题的新答案,当我第一次开始编写机器人代码时我遇到了这个问题,但没有一个答案起作用。
一些背景信息:在 discord.py 2.0 中,有两种方法可以编写斜线命令
discord.Client,+易于同步 - 无前缀命令
command.Bot, -更难同步 +前缀命令
我将展示一个我对命令更自信的例子。Bot FYI
discord.Client 斜线命令示例的一个很好的外部来源是Rapptz-app_command_examples
命令.Bot Slash Command
from typing import Literal, Optional
import discord
from discord.ext.commands import Greedy, Context
from discord import app_commands
from discord.ext import commands
#------ Bot ------
# Can add command_prefix='!', in commands.Bot() for Prefix Commands
intents = discord.Intents.default()
intents.members = True
intents.message_content = True
bot = commands.Bot(intents=intents)
#--- Bot Startup
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}') #Bot Name
print(bot.user.id) #Bot ID
#------ Slash Commands ------
#Parameters can be added in def help()
# Ex- async def help(interaction: discord.Interaction, left:int,right:int)
@bot.tree.command()
async def help(interaction: discord.Interaction):
"""Help""" #Description when viewing / commands
await interaction.response.send_message("hello")
#------ Sync Tree ------
guild = discord.Object(id='guildID')
# Get Guild ID from right clicking on server icon
# Must have devloper mode on discord on setting>Advance>Developer Mode
#More info on tree can be found on discord.py Git Repo
@bot.command()
@commands.guild_only()
@commands.is_owner()
async def sync(
ctx: Context, guilds: Greedy[discord.Object], spec: Optional[Literal["~", "*", "^"]] = None) -> None:
if not guilds:
if spec == "~":
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "*":
ctx.bot.tree.copy_global_to(guild=ctx.guild)
synced = await ctx.bot.tree.sync(guild=ctx.guild)
elif spec == "^":
ctx.bot.tree.clear_commands(guild=ctx.guild)
await ctx.bot.tree.sync(guild=ctx.guild)
synced = []
else:
synced = await ctx.bot.tree.sync()
await ctx.send(
f"Synced {len(synced)} commands {'globally' if spec is None else 'to the current guild.'}"
)
return
ret = 0
for guild in guilds:
try:
await ctx.bot.tree.sync(guild=guild)
except discord.HTTPException:
pass
else:
ret += 1
await ctx.send(f"Synced the tree to {ret}/{len(guilds)}.")
bot.run('token')
!sync
-> 全局/服务器同步 (无 ID) 或 (ID SET)
!sync ~
-> 同步当前公会 (Bot In)
!sync *
-> 将所有全局应用程序命令复制到当前公会并同步
!sync ^
-> 清除当前公会目标的所有命令并同步(删除公会命令)
!sync id_1 id_2
-> 同步 ID 为 1 和 2 的公会
如果我犯了任何错误,请评论,我会修复它们,祝你在 discord bot 之旅中好运
解决方案 6:
discord.py
不支持斜线命令。我建议您使用discord-py-interactions
斜线命令。安装方法是执行python3.exe -m pip install discord-py-interactions
。它运行良好。以下是示例代码:
import interactions
bot = interactions.Client(token="your_secret_bot_token")
@bot.command(
name="my_first_command",
description="This is the first command I made!",
scope=the_id_of_your_guild,
)
async def my_first_command(ctx: interactions.CommandContext):
await ctx.send("Hi there!")
bot.start()
扫码咨询,免费领取项目管理大礼包!