discord机器人开发:如何在on_command事件中取消命令执行?
解决方案
你可以用以下两种方法实现需求,都不需要给单个命令加额外校验:
方法1:直接在现有on_command事件中终止命令执行
discord.py的命令处理逻辑会在on_command事件跑完后才执行命令函数,你只需要在判断到命令被禁用时,给ctx对象的command属性赋值为None即可,框架会判定没有匹配到可执行的命令,自动终止后续流程。修改后的代码如下:
@bot.event async def on_command(ctx): try: with open('serverdata.json', 'r') as f: data = json.load(f) await update_server_data(data, ctx.channel.guild) storage = data[f'{ctx.channel.guild.id}']["channels"][f'{ctx.channel.id}']["disabled_commands"] if str(ctx.command) in storage: await ctx.channel.send(f'{ctx.command} is disabled in this channel!') # 新增这一行即可终止命令运行 ctx.command = None except: pass
方法2:使用全局检查器(更推荐)
你还可以用discord.py提供的全局检查器功能,这是官方更推荐的全局校验实现方案,检查器返回False时命令会自动终止,还能配套on_command_error事件统一处理错误提示,示例代码如下:
@bot.check async def global_command_check(ctx): try: with open('serverdata.json', 'r') as f: data = json.load(f) await update_server_data(data, ctx.guild) disabled = data[f'{ctx.guild.id}']["channels"][f'{ctx.channel.id}']["disabled_commands"] return str(ctx.command) not in disabled except: # 出现异常默认放行命令,你可以按需调整逻辑 return True # 可选:配套错误事件发送提示 @bot.event async def on_command_error(ctx, error): if isinstance(error, commands.CheckFailure): await ctx.send(f'{ctx.command} is disabled in this channel!')
注意:如果你的json读写逻辑是高频调用的,建议把数据缓存到内存中,避免每次调用命令都读磁盘影响性能。
内容的提问来源于stack exchange,提问作者chairiscute7
相关产品推荐
相关产品推荐

