Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
797 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

<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('
'));
        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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...