如何全局同步Discord斜杠命令?自定义sync命令报错求助
问题分析与修复方案
你的代码存在三个关键问题,导致运行报错:
变量名不匹配
函数参数定义的是ctx:discord.Interaction,但函数内部使用的是interaction变量,两者不一致,Python找不到interaction这个变量,会抛出NameError。装饰器使用错误
@commands.is_owner()是Discord.py前缀命令的装饰器,不适用于斜杠命令(@bot.tree.command定义的命令),斜杠命令需要使用discord.app_commands.checks.is_owner()来做所有者校验。冗余的权限判断
既然已经使用了所有者校验装饰器,没必要再单独写if interaction.user.id == ...的判断,可以去掉这部分逻辑,或者保留其中一种方式即可。
修复后的代码如下:
import discord from discord import app_commands @bot.tree.command(name='sync', description='Owner only') @app_commands.checks.is_owner() async def sync(interaction: discord.Interaction): await bot.tree.sync() print('Command tree synced.') await interaction.response.send_message('命令树已同步完成!') # 可选:添加权限不足的错误处理 @sync.error async def sync_error(interaction: discord.Interaction, error): if isinstance(error, app_commands.errors.NotOwner): await interaction.response.send_message('你必须是机器人所有者才能使用此命令!', ephemeral=True)
另外补充两点注意事项:
- 如果你还是想保留指定ID的判断,可以去掉装饰器,直接在函数里判断,但要确保变量名正确:
@bot.tree.command(name='sync', description='Owner only') async def sync(interaction: discord.Interaction): if interaction.user.id == 616438322864193553: await bot.tree.sync() print('Command tree synced.') await interaction.response.send_message('命令树已同步完成!') else: await interaction.response.send_message('你必须是机器人所有者才能使用此命令!', ephemeral=True) - 使用
ephemeral=True可以让回复仅命令执行者可见,避免无关人员看到权限提示。
内容的提问来源于stack exchange,提问作者xAGTx47 0047
相关产品推荐
相关产品推荐

