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
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.
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)