discord.py中on_command_error遇无效命令/CheckFailure未触发求助
问题原因
你使用的是discord.py的斜杠命令(app_commands),但on_command_error事件仅对传统前缀命令生效,对斜杠命令的错误不会触发该事件,这就是你的事件函数没执行、错误直接打印到控制台的原因。
解决方案
针对斜杠命令的错误,需要使用专门的错误处理机制,以下是两种常用方式:
1. 全局斜杠命令错误处理
通过client.tree.error事件捕获所有斜杠命令的错误:
import discord from discord import app_commands AUTHORIZED_USERS = [] def is_authorized(): async def predicate(ctx): return ctx.user.id in AUTHORIZED_USERS return app_commands.commands.check(predicate) @client.tree.error async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): # 处理权限检查失败的情况 if isinstance(error, app_commands.CheckFailure): # ephemeral=True 让消息仅当前用户可见 await interaction.response.send_message("你没有权限使用这个命令!", ephemeral=True) # 处理命令不存在的情况 elif isinstance(error, app_commands.CommandNotFound): await interaction.response.send_message("不存在该斜杠命令!", ephemeral=True) else: # 打印其他未处理的错误 print(f"斜杠命令错误: {error}") # 可选:给用户发送通用提示 await interaction.response.send_message("命令执行出错,请稍后再试!", ephemeral=True) @client.tree.command(name="ping", description="Pong!") @is_authorized() async def ping(ctx): embed = discord.Embed(title="Pong! :ping_pong:", description=f"Latency is `{str(round(client.latency, 4))}`.") await ctx.response.send_message(embed=embed)
2. 单个命令的错误处理
如果只想针对某个特定命令处理错误,可以给该命令添加错误处理装饰器:
# 原有的AUTHORIZED_USERS、is_authorized定义及ping命令不变 @ping.error async def ping_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): if isinstance(error, app_commands.CheckFailure): await interaction.response.send_message("你无权执行ping命令!", ephemeral=True) else: print(f"ping命令错误: {error}")
注意事项
- 斜杠命令的错误处理接收的第一个参数是
Interaction对象,而非传统前缀命令的Context对象,注意参数类型匹配。 - 如果错误发生时已经对交互做出过响应,需要用
interaction.followup.send()而非interaction.response.send_message(),可通过interaction.is_done()判断状态。
内容的提问来源于stack exchange,提问作者Marc
相关产品推荐
相关产品推荐

