discord.py如何在before_invoke中取消命令执行并触发on_command_error
解决方案
实现思路
discord.py的before_invoke钩子中抛出继承自commands.CommandError的自定义异常时,框架会自动终止当前命令执行,同时将异常传递给on_command_error事件处理函数,完全符合需求,不需要手动调用事件。
具体实现步骤
- 第一步:先定义自定义错误类,建议放在代码顶部导入模块之后的位置
from discord.ext import commands # 自定义配置缺失错误,继承自命令错误基类 class MissingGuildSettingsError(commands.CommandError): """服务器必填配置缺失时抛出的错误""" pass
- 第二步:修改你的
before_invoke校验逻辑,检测到缺失配置时直接抛出上面定义的错误
@bot.before_invoke async def checkguild(ctx): # 注意这里的参数是ctx不是message,before_invoke接收的是上下文对象,原代码参数写法有误 command = ctx.command if command and command.name != 'settings': # 加非空判断避免边缘情况报错 if ctx.guild and ctx.guild.id not in globaldb.servers_setup.val: for required_setting in REQUIRED_SETTINGS: if not get_guild_db(ctx.guild).settings.has(required_setting): # 抛出自定义错误,会自动中止命令执行并触发on_command_error raise MissingGuildSettingsError(f"缺失必填配置项:{required_setting},请先使用/settings命令完成服务器配置") # 所有配置校验通过才会执行到这里,加入已设置列表 globaldb.set('servers_setup', globaldb.servers_setup.val + [ctx.guild.id]) globaldb.save()
- 第三步:在你的
on_command_error事件中补充对这个自定义错误的处理逻辑即可
@bot.event async def on_command_error(ctx, error): # 判断错误类型是我们自定义的配置缺失错误 if isinstance(error, MissingGuildSettingsError): await ctx.send(str(error)) return # 其他原有错误处理逻辑保留 # ...
内容的提问来源于stack exchange,提问作者jvadair
相关产品推荐
相关产品推荐

