简体   繁体   中英

Discord.py - Check if user has specific role to make the command

I want to check if user that does command has a Admin role

That is my code:

@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")

But when I try to do the command without an Admin role it shows me this error:

    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.

How to check if user has role Admin in his role list and then he could do this command?

Using the decorator @commands.has_role(name='Admin') is protecting the method from non Admin users already.

It is raising an exception when calling the method, not inside the method.

EDIT: As mentionned by Patrick in the comments, you will need to implement error handling in order to catch the error: https://discordpy.readthedocs.io/en/rewrite/ext/commands/commands.html#error-handling

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM