【问题标题】:How to check if the author has x role in x server?如何检查作者是否在 x 服务器中具有 x 角色?
【发布时间】:2019-05-25 06:04:57
【问题描述】:

我正在尝试检查作者是否在 x 服务器上具有 x 角色以便能够使用该命令但无法使其工作。我只能检查作者是否在该服务器中具有 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")

【问题讨论】:

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


    【解决方案1】:

    你可以只获取角色对象。

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

    那么就:

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

    您的机器人必须在这些服务器上。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-05-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-20
        • 2019-11-17
        • 1970-01-01
        • 2020-09-14
        相关资源
        最近更新 更多