不和.py重写检查bot是否通过@调用前的命令d

2024-09-30 16:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

在不和.py重写

在我的代码片段中,我尝试在不一致运行实际命令之前运行一个简单的check命令:

@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

在运行命令之前,如何检测bot本身是否具有管理员权限?我不想在每个命令中都添加try/except块。在


Tags: andtherun代码inpy命令async
1条回答
网友
1楼 · 发布于 2024-09-30 16:22:19

您可以使用内置的^{}

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

相关问题 更多 >