python - Discord.py - 检查用户是否具有执行命令的特定角色

标签 python discord roles discord.py

我想检查执行命令的用户是否具有管理员角色

这是我的代码:

@client.command(pass_context=True)
@commands.has_role(name='Admin')
async def unban(self, ctx, user):
    """
    unbans a user name
    :user: user name not mentioned
    """
    try:
        ban_list = await client.get_bans(ctx.message.server)
        if not ban_list:
            await self.client.send_message(ctx.message.channel, 'Ban list is empty')
            return
        for bans in ban_list:
            if user.lower() in str(bans).lower():
                try:
                    await self.client.unban(ctx.message.server, bans)
                    await self.client.send_message(ctx.message.channel, 'Unbanned')
                except discord.Forbidden:
                    await client.send_message(ctx.message.channel, "I don't have permissions to unban")
                    return
                except discord.HTTPException:
                    await client.send_message(ctx.message.channel, 'Unban failed')
                    return
            else:
                await client.send_message(ctx.message.channel, 'This user is not banned from this server')
    except:
        await client.send_message(ctx.message.channel, "You don't have ``Admin`` role")

但是当我尝试在没有 Admin 角色的情况下执行该命令时,它会显示此错误:

    Ignoring exception in command unban
Traceback (most recent call last):
  File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 846, in process_commands
    yield from command.invoke(ctx)
  File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 367, in invoke
    yield from self.prepare(ctx)
  File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 344, in prepare
    self._verify_checks(ctx)
  File "C:\Users\danyb\Anaconda3\lib\site-packages\discord\ext\commands\core.py", line 339, in _verify_checks
    raise CheckFailure('The check functions for command {0.qualified_name} failed.'.format(self))
discord.ext.commands.errors.CheckFailure: The check functions for command unban failed.

如何检查用户的角色列表中是否具有管理员角色,然后他可以执行此命令?

最佳答案

使用装饰器 @commands.has_role(name='Admin') 已经可以保护该方法免受非管理员用户的攻击。<​​/p>

它在调用方法时引发异常,而不是在方法内部引发异常。

编辑:正如帕特里克在评论中提到的,您需要实现错误处理才能捕获错误:https://discordpy.readthedocs.io/en/rewrite/ext/commands/commands.html#error-handling

关于python - Discord.py - 检查用户是否具有执行命令的特定角色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53087813/

相关文章:

python - 如何判断字符串中的单词是否为双字?

python - pandas 如何在所有浮点列均为 NaN 时删除行

python - 按出现顺序获取 numpy 数组索引

python - discord.py 类型错误 : 'property' object is not iterable

c# - 从 Roles 授权更改为 Claims 授权

ansible - 在运行角色之前动态运行 "ansible-galaxy install -r requirement.yml -p roles/"作为先决条件

python - 如何检查当前时间是否在python的范围内?

javascript - ValidationError > s.string 应为接收到的字符串原语 : | undefined

python - send_message 函数不适用于 python discord bot

symfony - 如何在 Twig 中使用多个角色(Symfony2)