簡體   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