【问题标题】:PYTHON DISCORD.PY Can you catch permissions errors from the decoratorsPYTHON DISCORD.PY 你能从装饰器中捕获权限错误吗
【发布时间】:2020-08-28 04:02:07
【问题描述】:

我正在使用 discord.py 为我的服务器编写一个不和谐的机器人,并且想知道当有人没有正确的权限来执行命令时如何向服务器发送消息

我正在使用装饰器:

@client.command()
@commands.has_any_role("Administrator", "BOT SQUAD")

显然,当我使用我的测试帐户运行命令时,它会给出一个错误,说它没有正常的权限

我想要做的是,当这个错误发生时,它不会在日志中打印出用户没有权限,而是告诉用户在他发信息的频道中,甚至私信他们说他们没有执行命令的权限。

我是 discord.py 的新手,所以我不知道如何实现这一点。我浏览了所有文档,这对我没有帮助,我也没有看过任何其他问题。

如果有人可以帮助我做到这一点,那将是完美的。如果您保留我已经获得的装饰器,则可以加分,因为这是我目前知道如何为函数实现单独角色的唯一方法!

【问题讨论】:

    标签: python python-3.x discord.py


    【解决方案1】:

    在 d.py 中有一个名为 on_command_error() 的事件,顾名思义,它在运行命令时出现错误时执行。这是一个例子:

    @client.event
    async def on_command_error(ctx, error):
        if isinstance(error, discord.ext.commands.errors.CheckFailure): # checking which type of error it is
            missing_roles = error.missing_roles # returns tuple
            linebreak = "\n"
            await ctx.send(f":x: Check failure!\nYou are missing the following roles:\n{linebreak.join(missing_roles)}")
        else:
            await ctx.send(error) # I can recommend popping this in here also if you wish to catch other errors
    

    Here's a list 的所有不同异常。

    在上面的示例中,这将是您希望在代码中进行的检查。 CheckFailure 指的是你的函数上的任何检查装饰器。

    【讨论】:

    • 一个问题!我得到那个错误存储了错误是什么,但是我将如何从错误变量中获得权限
    • @LegacyCoding 相应地编辑了答案。
    • 最后一件事。我收到一条错误消息,提示 \n 不能在 f 字符串中使用。主要问题在{'\n'.join(missing_roles)} 内部。我该如何解决这个问题?
    • @LegacyCoding 抱歉完全忘记了!已编辑!
    • 谢谢!你帮了大忙!
    猜你喜欢
    • 2018-05-14
    • 1970-01-01
    • 2011-01-11
    • 2016-02-26
    • 2013-06-06
    • 2013-06-08
    • 1970-01-01
    • 2021-07-25
    • 2011-08-15
    相关资源
    最近更新 更多