繁体   English   中英

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

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

我正在尝试检查作者是否在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")

内置的检查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):
    ...

您可以只获取角色对象。

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

然后:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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