2

I try to make a simple bot that just lists all members that have a specific role.

I went through most of the similar questions I could find, but their answers seem outdated. So I tried this but end up with the result 'undefined', although the role exists.

const discord = require('discord.js');
const { Client, Intents } = require('discord.js');
const client = new discord.Client(
    { intents: [
        Intents.FLAGS.GUILDS, 
        Intents.FLAGS.GUILD_MESSAGES,
        Intents.FLAGS.GUILD_MEMBERS
    ] });


const prefix ="!";
const MemberID = "912852591023628371";

client.on('ready', () => {
    console.log('Connected to the bot');

  

});

client.on('messageCreate', msg => {
    if (msg.content === 'hi') {
        msg.reply('Hi to you too!');
    }
  
});

client.on('messageCreate', async message => {
    if (message.content === prefix + 'list') {
        let list = client.guilds.cache.get(MemberID);
        console.log(list);
        }
    }
);
Juno
  • 211
  • 5
  • 17

1 Answers1

1

Just use this:

    message.guild.roles.cache.get('Your role id here').members.map(m=>m.user.tag);

This will return an array of all users with the role.

Ascent
  • 86
  • 8
  • 1
    Thanks! I am actually pretty confused by the discord.js docs... tried to wrap it like this, but still gives "undefined". ```client.on('messageCreate', async message => { let getAllMemberWithRoles = async () => { let list = await client.guilds.cache.get(MemberID); console.log(list); } if (message.content === prefix + 'list') { getAllMemberWithRoles(); } } );``` – Juno Feb 05 '22 at 00:20
  • Hah, looks like my answer about promises was absolute rubbish! The discord js guide says to use a method instead. Updating answer. If that doesn't work, take a look at this: https://stackoverflow.com/questions/48897574/how-do-i-list-all-members-with-a-role-in-discord-js – Ascent Feb 05 '22 at 01:48
  • 1
    Thanks, but I tried these. Seems as if they are outdated? Throws error: "get is not a function" – Juno Feb 05 '22 at 10:17
  • 1
    Hmm. After doing a little testing on my own, `message.guild.roles.cache.get('role-id').members.map(m=>m.user.tag);` works for me. I got the same error as you , but adding .cache fixed it. – Ascent Feb 05 '22 at 16:46