How to check is an user has a role on discord

☆樱花仙子☆ 提交于 2020-12-26 11:48:20

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/58924386/how-to-check-is-an-user-has-a-role-on-discord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!