如何创建带空格分类的斜杠命令并兼容无斜杠调用?
实现分类式斜杠命令+双调用方式的解决方案
核心方案:命令组+复用执行逻辑
混合命令(hybrid_command)无法直接实现/<category> <command>的分层格式,因为它的命令名是单一字符串。正确的做法是用**命令组(Group)**分别管理斜杠命令的分类结构,同时给前缀命令绑定相同的执行逻辑,实现/react angry和!angry的等效效果。
实现示例(基于discord.py 2.0+)
以下代码同时支持分类斜杠命令和短前缀命令,逻辑复用:
import discord from discord.ext import commands from discord import app_commands # 初始化Bot,开启消息内容权限(前缀命令必需) intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix="!", intents=intents) # ------------------------------ # 复用的命令执行逻辑(兼容两种触发方式) # ------------------------------ async def exec_angry(context): # 区分前缀命令的Context和斜杠命令的Interaction if isinstance(context, discord.Interaction): await context.response.send_message("😠 触发愤怒反应!") else: await context.send("😠 触发愤怒反应!") async def exec_happy(context): if isinstance(context, discord.Interaction): await context.response.send_message("😊 触发开心反应!") else: await context.send("😊 触发开心反应!") # ------------------------------ # 配置斜杠命令组(对应category) # ------------------------------ # 创建斜杠命令组 react_slash_group = app_commands.Group( name="react", description="表情反应类命令集合" ) # 给斜杠组添加子命令 @react_slash_group.command(name="angry", description="发送愤怒表情") async def slash_react_angry(interaction: discord.Interaction): await exec_angry(interaction) @react_slash_group.command(name="happy", description="发送开心表情") async def slash_react_happy(interaction: discord.Interaction): await exec_happy(interaction) # 将斜杠组注册到Bot bot.tree.add_command(react_slash_group) # ------------------------------ # 配置前缀命令(直接绑定执行逻辑) # ------------------------------ @bot.command(name="angry") async def prefix_angry(ctx): await exec_angry(ctx) @bot.command(name="happy") async def prefix_happy(ctx): await exec_happy(ctx) # ------------------------------ # 启动Bot # ------------------------------ @bot.event async def on_ready(): # 手动同步斜杠命令(可选,首次启动需要) await bot.tree.sync() print(f"Logged in as {bot.user}") bot.run("你的Bot Token")
更规整的前缀命令组(可选)
如果想让前缀命令也支持!react angry格式,同时保留!angry的短调用,可以给前缀命令也添加组结构:
# 创建前缀命令组 react_prefix_group = commands.Group( name="react", description="表情反应类命令集合" ) # 给前缀组添加子命令 @react_prefix_group.command(name="angry") async def prefix_group_angry(ctx): await exec_angry(ctx) @react_prefix_group.command(name="happy") async def prefix_group_happy(ctx): await exec_happy(ctx) # 将前缀组注册到Bot bot.add_command(react_prefix_group)
这样用户既可以用!angry快速调用,也可以用!react angry的分类格式调用。
关键注意事项
- 必须开启
message_content意图,否则前缀命令无法读取用户消息。 - 斜杠命令需要同步到Discord服务器,首次启动后可能需要几分钟生效,或者在
on_ready事件中调用await bot.tree.sync()手动同步。 - 执行函数要兼容
Context(前缀命令)和Interaction(斜杠命令)两种对象,两者的消息发送方法略有不同。
内容的提问来源于stack exchange,提问作者p4rfait
相关产品推荐
相关产品推荐

