简体   繁体   中英

How to check is an user has a role on discord

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<Role> roles = guild.getRolesByName(name, true);

    if (roles.size() <= 0) {
        throw new RuntimeException("Role with name " + name + " on Guild " + guild.getName() + " not found!");
    } else {
        return roles.get(0);
    }
}

and i have a role: Role neededEole=findRole(event.getGuild(),"Admin");

I know how to search an user: String user=event.getAuthor().getId(); or: User user=event.getAuthor();

But i don't know how to get those two work together in JDA to check if that user has that role.

Can please someone help me?

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.

I know this post is 1+ year old but for the people coming here to check this you can just do this (I did static in this code because I was putting it in another class):

public static boolean hasRole(Member member, Role role) {
  List<Role> memberRoles = member.getRoles();
  return memberRoles.contains(role);
}

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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