简体   繁体   中英

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

How I can list members in a role using Discord.js .

My code:

client.on("message", message => {
    var guild = message.guild;
    let args = message.content.split(" ").slice(1);
    if (!message.content.startsWith(prefix)) return;
    if (message.author.bot) return; 
    if(message.content.startsWith(prefix + 'go4-add')) {
        guild.member(message.mentions.users.first()).addRole('415665311828803584');                     
    }
});

How would I go about listing all the members that have the go4 role in an embed. When the message .go4-list is entered in a channel I would like the bot to respond with the embed.

<Role>.members returns a collection of GuildMember s. 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.

if(message.content.startsWith("//inrole")){
    let roleName = message.content.split(" ").slice(1).join(" ");

    //Filtering the guild members only keeping those with the role
    //Then mapping the filtered array to their usernames
    let membersWithRole = message.guild.members.filter(member => { 
        return member.roles.find("name", roleName);
    }).map(member => {
        return member.user.username;
    })

    let embed = new discord.RichEmbed({
        "title": `Users with the ${roleName} role`,
        "description": membersWithRole.join("\n"),
        "color": 0xFFFF
    });

    return message.channel.send({embed});
}

Example use on discord:

角色命令

Do note though that if there are a lot of members with the role, you may get an error telling you that you have exceeded the number of chars you can put in an embed. In such a case, you can decide to send multiple embeds splitting the users.

I tried Newbie's solution, but it didnt work

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

Gave me an error that .get is not a function maybe something changed with discord.js,

Adding cache after roles made it work.

message.guild.roles.cache.find(r => r.name === args[0]);

从 Discord v12 开始,您现在必须使用roles.add()而不是addRole()

要在嵌入中提及用户(这看起来比仅文本好得多)删除.tag所以它只是

(m => m.user).join('\n')

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