How to check is an user has a role on discord

前端 未结 2 867
情深已故
情深已故 2021-01-24 09:29

I am struggling to find a way to check if an user has a role. I know how to find a certain role:

public Role findRole(Guild guild, String name) {
    List

        
相关标签:
2条回答
  • 2021-01-24 10:02

    The Member object puts a user in the guild context. You can get the member with Guild#getMember(user). This gives you the option to retrieve guild information of this user:

    Member member = guild.getMember(user);
    Member member = guild.getMemberById(userId);
    List<Member> member = guild.getMembersByName(name, true);
    List<Member> member = guild.getMembersByRoles(role);
    
    public Role findRole(Member member, String name) {
        List<Role> roles = member.getRoles();
        return roles.stream()
                    .filter(role -> role.getName().equals(name)) // filter by role name
                    .findFirst() // take first result
                    .orElse(null); // else return null
    }
    

    Other ways to access a member instance are outlined in the See Also section of the member documentation: Member. Some events also offer a getMember() alternative if the event could happen in a guild context.

    0 讨论(0)
  • 2021-01-24 10:05

    Since there's no such feature in the doc yet, you can do this:

    boolean hasRole;
      for(int i=0; i<builder.getGuildById(guild).getMemberById(userId).getRoles().size(); i++){
        if("RoleName".equals(builder.getGuildById(guild).getMemberById(userId).getRoles().get(i).getName())){
          hasRole = true;
        }
      }
    

    Then, for true if (hasRole) or false if (!hasRole)

    0 讨论(0)
提交回复
热议问题