Search code examples
javabotsdiscorddiscord-jda

Java Discord Bot - Get Members of a role?


I am currently working on a java discord bot (net.dv8tion) and I try to create a "who" command, that should list you the people of the picked role, for example: !who admin --> list of all people with the "admin" role. So my problem is, that I couldn't actually find a method or any other way to solve this problem. I hope that some of you might help me with this problem ^^

I thought about something like this, or similar:

list <> members = guild.getMembersByRole(roleName);

or:

role rolename;
String[] members = rolename.getMembers();

Solution

  • This can be done with 2 steps:

    1. Get the target role
    2. Get the members of that role

    To get the role you can either use getRolesByName or getRoleById.

    For example:

    List<Role> roles = guild.getRolesByName("admin", true);
    Role role = guild.getRoleById(698231912904523796L);
    

    Once you have the role(s) you can use getMembersWithRoles.

    List<Member> members = guild.getMembersWithRoles(roles);
    

    If the resulting list of members is empty or missing members despite the roles being correct, it is possible that the members are not cached. See this answer for further details on that.