如何使用on_command_error()检测AttributeError以拦截服务器外命令调用
问题原因
discord.py 的 on_command_error 事件接收到的异常默认是框架封装后的类型,命令执行过程中抛出的原生异常会被包裹在 CommandInvokeError 的 original 属性中,所以直接判断外层的 error 类型无法匹配到内层的 AttributeError。
适配你现有逻辑的修改代码
from discord.ext import commands @bot.event async def on_command_error(ctx, error): # 先匹配框架封装的命令执行异常 if isinstance(error, commands.CommandInvokeError): # 提取内层的原生报错 original_err = error.original # 同时判断异常类型和报错内容,避免误判其他场景的AttributeError if isinstance(original_err, AttributeError) and "'NoneType' has no attribute 'id'" in str(original_err): await ctx.send('You Cannot Use This Command Outside Of The Server') return # 其余异常正常打印 print(error)
更规范的优化方案
你当前的场景本质是要限制命令仅能在服务器内使用,不需要靠捕获错误实现,用框架自带的功能逻辑更严谨,不会误判其他业务场景下的空对象ID访问错误:
from discord.ext import commands # 给需要限制的命令添加guild_only装饰器 @bot.command() @commands.guild_only() async def 你的命令名(ctx): # 原有命令逻辑 pass @bot.event async def on_command_error(ctx, error): # 直接捕获框架自带的禁止私聊调用异常,精准度更高 if isinstance(error, commands.NoPrivateMessage): await ctx.send('You Cannot Use This Command Outside Of The Server') return print(error)
内容的提问来源于stack exchange,提问作者Cyber-Yosh
相关产品推荐
相关产品推荐

