2
votes

I have created a discord bot by taking reference from this digital ocean link.
Now I can send message to any channel using the bot but my requirement is to send dm to user of that server.
For that I have tried many SO answers and followed other links, but all the solutions end up to be same.
I have tried this two way to get the users of a guild and send dm to any one selected user.
1st way - Get all users of guild (server)

const client_notification = new Discord.Client();
client_notification.on('ready', () => {
    console.log("Notification manager ready");
    let guild = client_notification.guilds.cache.get("Server ID");
    guild.members.cache.forEach(member => console.log("===>>>", member.user.username));
});
client_notification.login("login");

Output

Notification manager ready
===>>> discord notification

By this way it only returns me the bot name itself. Although the membersCount is 6.

2nd way - send dm to user directly (server)

client.users.cache.get('<id>').send('<message>');

It gives me undefined in output.

My configs,
Node version: 10.16.3
discord.js version: 12.5.1

My question is how to get all the guild members in discord.js?

2

2 Answers

2
votes

I think the problem is related to updating the bot policy for discord. Do you have this checkbox checked in the bot settings? https://discord.com/developers/applications

Some info about client.users.cache: Its a cache collection, so if you restart bot, or bot never handle user message or actions before, this collection will be empty. Better use guild.members.cache.get('')

enter image description here

3
votes

Discord added privileged gateway intents recently. So to fetch all member data you need to enable that in the developer portal. After that you need to fetch all the members available, for that we can use the fetchAllMembers client option, and then we need to filter out bot users, so that we don't message them.

const client_notification = new Discord.Client({fetchAllMembers:true}); //Fetches all members available on startup.
client_notification.on('ready', () => {
    console.log("Notification manager ready");
    let guild = client_notification.guilds.cache.get("Server ID");
    guild.members.cache.filter(member => !member.user.bot).forEach(member => console.log("===>>>", member.user.username));
});
client_notification.login("login");

The .filter() method filters out all the bots and gives only the real users. You should avoid using fetchAllMembers when your bot gets larger though, as it could slow down your bot and use lots of memory.