简体   繁体   中英

How to check if the author has x role in x server?

I'm trying to check if the author has x role on x server to be able to use the command but can not make it work. I only can check if Author has x role in that server.

The idea: If the user has x role in x server will be able to use the special command on any servers.

 role_id = 569712344226201600
 author = ctx.message.author

 if role_id in [role.id for role in author.roles]:
     await ctx.send("message")

The built-in check has_role won't work here, because that only checks the roles of the context the command was invoked in. It's easy enough to write a check that examines roles from a specific server no matter the context:

from discord.utils import get
from discord.ext.commands import check, MissingRole, CommandError

class GuildNotFound(CommandError):
    def __init__(self, guild):
        self.missing_guild = guild
        message = f"I could not resolve guild: {guild}"
        super().__init__(message)


class IsNotMember(CommandError):
    def __init__(self, user, guild):
        self.user = user
        self.guild = guild
        message = f"{user} is not a member of guild {guild}"
        super().__init__(message)

def has_role_elsewhere(guild, role):
    def predicate(ctx):
        # Resolve the guild
        if isinstance(guild, int):
            resolved_guild = get(ctx.bot.guilds, id=guild)
        else:
            resolved_guild = get(ctx.bot.guilds, name=guild)
        if resolved_guild is None:
            raise GuildNotFound(guild)

        # Resolve the member
        member = resolved_guild.get_member(ctx.author.id)
        if member is None:
            raise IsNotMember(ctx.author, resolved_guild)

        # Check for the role
        if isinstance(role, int):
            resolved_role = get(member.roles, id=role)
        else:
            resolved_role = get(member.roles, name=role)
        if resolved_role is None:
            raise MissingRole(role)

        return True
    return check(predicate)

That's a lot of code, but in means in our actual bot we just have to do:

@bot.command()
@has_role_elsewhere(guild=123456, role=569712344226201600)
async def mycommand(ctx):
    ...

You can just get the role object.

role = discord.utils.get(ctx.guild.roles, id=role_id_here)

Then just:

if role in ctx.author.roles:
...

Your bot would have to be on those servers.

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