【问题标题】:discord.py rewrite - checking if the bot has a certain permission through @command.before_invoke decoratordiscord.py 重写 - 通过 @command.before_invoke 装饰器检查机器人是否具有一定的权限
【发布时间】:2019-11-16 13:13:54
【问题描述】:

Discord.py 重写

在我的 sn-p 代码中,我试图在运行不和谐的实际命令之前运行一个简单的检查命令:

@command.before_invoke
async def check_perms(self, ctx): # being defined in a class
    # if 'administrator' in bot.permissions <<< My goal
        # pass and let the following command run
    # else:
        # Make the bot say it can't run an admin only action and raise a custom exception

如何在运行命令之前检测机器人本身是否具有管理员权限?我不想在每个命令中都放置 try/except 块。

【问题讨论】:

    标签: python discord discord.py python-3.7 discord.py-rewrite


    【解决方案1】:

    你可以使用内置的bot_has_permissions

    from discord.ext.commands import bot_has_permissions, Bot, BotMissingPermissions
    
    class CustomException(Exception):
        pass
    
    bot = Bot('!')
    
    @bot.command()
    @bot_has_permissions(administrator=True)
    async def example(ctx):
        ...
    
    @example.error
    async def error_handler(ctx, error):
        if isinstance(error, BotMissingPermissions):
            await ctx.send(f"I need the permissions: {' '.join(error.missing_perms)}")
            raise CustomException() from error
        else:
            raise error
    

    【讨论】:

    • 我希望机器人在没有管理员权限时做出响应。在这种情况下,除非它响应,否则它无法响应。我确实想要在这个命令中尝试/除。
    • 您可以编写一个错误处理程序来检查检查引发的错误。我将用一个例子来编辑我的答案。
    • 我在帖子中的目标是做一个运行if 'admin' in bot.permissions 的条件语句。就我而言,我不能使用 try/except 块。我的意思是 if/else 在我之前的评论中。
    猜你喜欢
    • 2019-03-06
    • 2023-02-20
    • 2021-04-24
    • 2021-09-14
    • 1970-01-01
    • 2021-07-15
    • 2011-07-26
    • 2021-05-13
    • 1970-01-01
    相关资源
    最近更新 更多