如何在discord.py中使用Bot配置斜杠命令组与子斜杠命令?
问题排查与解决
你的代码无法显示/foo命令,主要有几个常见原因和对应的修复方案:
1. 命令同步的核心问题
- 确保
ServerId是整数类型,传入字符串会导致服务器匹配失败,同步命令无效。 on_ready事件会在机器人重连时重复触发,重复执行同步操作可能引发异常,建议添加标记避免重复同步。
2. 命令组的注册与参数规范
- 斜杠命令组的子命令需接收
discord.Interaction对象作为参数,而非传统的commands.Context,且必须使用交互响应方法发送消息(如interaction.response.send_message)。 - 直接使用
@bot.tree.group装饰器定义命令组,比手动创建Group对象后添加更稳妥,能避免注册遗漏问题。
修正后的完整代码
import discord from discord import app_commands from discord.ext import commands # 替换为你的服务器ID(整数)和机器人令牌 SERVER_ID = 123456789012345678 TOKEN = "your-bot-token-here" intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='!', intents=intents) # 标记是否已完成命令同步 synced = False # 定义根命令组/foo @bot.tree.group(name="foo", description="foo命令组") async def foo_group(interaction: discord.Interaction): # 用户仅输入/foo时发送提示 if not interaction.data.get("options"): await interaction.response.send_message("请使用/foo的子命令,例如/foo bar") # 定义子命令/foo bar @foo_group.command(name="bar", description="bar子命令") async def bar(interaction: discord.Interaction): await interaction.response.send_message("bar") # 定义带参数的子命令/foo baz @foo_group.command(name="baz", description="带参数的baz子命令") async def baz(interaction: discord.Interaction, arg1: str, arg2: int): await interaction.response.send_message(f"收到参数:arg1={arg1}, arg2={arg2}") @bot.event async def on_ready(): global synced if not synced: # 同步指定服务器的命令 await bot.tree.sync(guild=discord.Object(id=SERVER_ID)) synced = True print(f"{bot.user} 已上线运行!") bot.run(TOKEN)
额外注意事项
- 确保机器人在目标服务器中拥有应用程序命令权限(可在服务器设置→集成→机器人面板中开启)。
- 若同步后仍看不到命令,可尝试重启机器人,或先执行
bot.tree.clear_commands(guild=discord.Object(id=SERVER_ID))清除旧命令后再同步。
内容的提问来源于stack exchange,提问作者Josh
相关产品推荐
相关产品推荐

