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

时间:2018-10-31 16:14:36

标签: python discord roles discord.py

我要检查执行命令的用户是否具有Admin role

那是我的代码:

@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.

如何检查用户是否在其角色列表中具有角色Admin,然后他可以执行此命令?

1 个答案:

答案 0 :(得分:0)

使用装饰器 try(BufferedReader bufferedReader= Files.newBufferedReader(Paths.get("test.csv"))) { CSVParser parser = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(bufferedReader); Map<String,Integer> hearders = parser.getHeaderMap(); Map<String,List<Double>> data = new HashMap<>(); parser.getRecords().stream().forEach(rec -> { hearders.entrySet().forEach( head ->{ data.computeIfAbsent(head.getKey(), k-> new ArrayList<>()).add(Double.parseDouble(rec.get(head.getValue()))); }); }); System.out.println(data); } 已经在保护该方法不受非Admin用户的攻击。<​​/ p>

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

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

相关问题