How do I list all Members with a Role In Discord.Js

<Role>.members returns a collection of GuildMembers. Simply map this collection to get the property you want.

Here’s an example according to your scenario:

message.guild.roles.get('415665311828803584').members.map(m=>m.user.tag);

This will output an array of user tags from members that have the “go4” role. Now you can .join(...) this array to your desired format.

Also, guild.member(message.mentions.users.first()).addRole('415665311828803584'); could be shortened down to: message.mentions.members.first().addRole('415665311828803584');

Here’s a rough example of how it would look as a result:

client.on("message", message => {

    if(message.content.startsWith(`${prefix}go4-add`)) {
        message.mentions.members.first().addRole('415665311828803584'); // gets the <GuildMember> from a mention and then adds the role to that member                     
    }

    if(message.content == `${prefix}go4-list`) {
        const ListEmbed = new Discord.RichEmbed()
            .setTitle('Users with the go4 role:')
            .setDescription(message.guild.roles.get('415665311828803584').members.map(m=>m.user.tag).join('\n'));
        message.channel.send(ListEmbed);                    
    }
});

As @Wright mentioned in his answer, if there are over many members it will throw an error as an embed can only hold 2048 characters maximum, so you may want to do some checks before sending out the embed and then handle oversized embeds by either splitting them into multiple embed messages, or using reaction based pages maybe.

Leave a Comment