首页 > 解决方案 > Discordpy CheckFailure:命令测试的检查功能失败

问题描述

我用我的代码几乎一字不差地遵循了文档CheckFailure,但是在我的控制台中显示了当用户不是管理员时(即当predicate返回时False)。返回时什么都没有显示True。为什么我会收到此错误,如何修复它以使其不显示错误?据我了解,它不应该一开始就显示错误。

def is_admin_role():
    async def predicate(ctx):
        admin_roles = [admin_role_id, admin_role_test_id]
        role_list = [x for x in ctx.message.author.roles] # get list of roles
        role_id_list = [x.id for x in role_list] # get their id's

        # false = user doesn't have admin role, true = user has admin role.
        has_admin_role = any(item in admin_roles for item in role_id_list)
            
        if not has_admin_role:
            # Create an embed to let the user know they can't run this command.
            embed = utils.ErrorEmbed("You must be an admin to run this command.")
            await ctx.send(embed = embed.print()) # Send the embed.
            return False # Return false since the user can't run it.
        return True # User is able to run it

    return commands.check(predicate)

@bot.command()
@is_admin_role()
async def test(ctx):
    ...
    # do whatever this code does.

我得到的错误:

Traceback (most recent call last):
  File "/opt/anaconda3/lib/python3.8/site-packages/discord/client.py", line 333, in _run_event
    await coro(*args, **kwargs)
  File "bot.py", line 125, in on_command_error
    raise error
  File "/opt/anaconda3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 903, in invoke
    await ctx.command.invoke(ctx)
  File "/opt/anaconda3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 851, in invoke
    await self.prepare(ctx)
  File "/opt/anaconda3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 779, in prepare
    raise CheckFailure('The check functions for command {0.qualified_name} failed.'.format(self))
discord.ext.commands.errors.CheckFailure: The check functions for command test failed.

标签: pythondiscord.py

解决方案


如果检查函数返回False,commands.CheckFailure则引发(您可以在错误处理程序中捕获它)。如果它返回 aTrue则调用命令,来自文档:

当发生错误时,错误会传播到错误处理程序。如果您不引发自定义CommandError派生异常,那么它将被包装到CheckFailure异常中。


推荐阅读