如何检查作者在x服务器中是否具有x角色?

时间:2019-05-25 06:04:58

标签: python python-3.x discord.py discord.py-rewrite

我正在尝试检查作者是否在x服务器上具有x角色,以便能够使用该命令,但无法使其正常运行。我只能检查Author在该服务器中是否具有x角色。

这个想法:如果用户在x服务器中具有x角色,将能够在任何服务器上使用特殊命令。

 role_id = 569712344226201600
 author = ctx.message.author

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

2 个答案:

答案 0 :(得分:0)

内置的检查has_role在这里不起作用,因为它仅检查调用命令的上下文的角色。编写检查来检查特定服务器中的角色的检查很容易上下文:

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)

这是很多代码,但是在我们实际的机器人程序中,我们只需要这样做:

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

答案 1 :(得分:0)

您只需获取角色对象即可。

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

然后:

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

您的漫游器必须在这些服务器上。