如何为Discord机器人的@bot.tree.command()实现全局异常处理?
全局处理Discord斜杠命令错误的方案
问题背景
此前使用文本命令时,可通过监听on_command_error()事件实现简单错误处理,但该事件对斜杠命令无效。需要全局捕获斜杠命令执行时的错误,并向用户发送自定义交互响应,说明错误情况及可能原因。
文本命令错误处理代码示例:
@bot.event async def on_command_error(ctx, error): if isinstance(error, discord.ext.commands.errors.MissingPermissions): await ctx.reply("You don't have the perms to do that.")
斜杠命令示例(若未及时延迟响应会导致404错误):
import asyncio import discord @bot.tree.command(name="test_command") async def test(interaction: discord.Interaction): await interaction.response.defer(ephemeral=True) await asyncio.sleep(5) await interaction.followup.send("Command works.")
解决方案:使用on_app_command_error全局事件
Discord.py为斜杠命令(应用命令)提供了独立的全局错误处理器——on_app_command_error事件,专门用于捕获斜杠命令执行过程中的异常。
全局错误处理实现代码
import discord from discord import app_commands @bot.event async def on_app_command_error(interaction: discord.Interaction, error: app_commands.AppCommandError): # 处理缺少权限的错误 if isinstance(error, app_commands.MissingPermissions): # 先检查是否已发送过初始响应,避免重复响应报错 if interaction.response.is_done(): await interaction.followup.send("你没有执行该命令的权限。", ephemeral=True) else: await interaction.response.send_message("你没有执行该命令的权限。", ephemeral=True) # 处理响应超时(未及时defer导致的404错误) elif isinstance(error, discord.errors.NotFound): # 此时交互窗口已关闭,无法向用户发送消息,仅做日志记录 print(f"命令响应超时,无法通知用户:{str(error)}") # 处理其他通用错误 else: error_msg = f"命令执行出错:{str(error)}" if not interaction.response.is_done(): await interaction.response.send_message(error_msg, ephemeral=True) else: await interaction.followup.send(error_msg, ephemeral=True)
核心注意点
- 斜杠命令的错误类属于
app_commands模块,比如权限错误是app_commands.MissingPermissions,和文本命令的discord.ext.commands.errors.MissingPermissions不是同一类,判断时要区分。 - 发送响应前必须通过
interaction.response.is_done()检查是否已完成初始响应(如调用过defer或send_message),否则会触发新的错误。 - 若出现
NotFound错误(404),说明Discord的交互响应窗口已关闭,此时无法再向用户发送消息,只能通过日志记录等方式处理。
内容的提问来源于stack exchange,提问作者Zaid Hussain
相关产品推荐
相关产品推荐

