Discord.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
如何在运行命令之前检测机器人本身是否具有管理员权限?我不想在每个命令中都放置try / except块。
答案 0 :(得分:0)
您可以使用内置的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