Skip to content
Advertisement

How can I send a Discord Direct Message to all users on a server on API v12?

I’m trying to update my discord bot from API v11 to API v12, and I’m having problems to send a direct message to all server users. It is not returning any error and I’m using the latest version from Discord API

This is the function:

const members = message.guild.members.cache.map((member) => member);
for (let i = 0; i < message.guild.memberCount; i++) {
 console.log(typeof members[i].id);
 if (blacklist.includes(members[i].id) === true) {
  console.log('1 usuário da BlackList não recebeu a mensagem.');
 } else {
  client.users.cache
   .get(members[i].id)
   .send('oi pepe')
   .catch(console.error);
 }
}

Could someone help me?

Advertisement

Answer

First of all, depending on the size of the server, DMing all members of a guild is in violation of Discord’s Terms of Service, and will commonly get your bot banned.

Second of all, message.guild.members.cache will only return the cached members of a guild, which is very rarely every member. Instead, use message.guild.fetch(), which will forcefully fetch every member of the guild through Discord’s API

Third of all, a lot of your code is very overcomplicated, for example, your use of map(member => member). Here’s how I would rewrite your function:

// get all members in the guild
message.guild.members.fetch().then((members) => {
  // iterate a function through every member of the guild
  // with `Array.prototype.forEach()`
  members.forEach((member) => {
     if (blacklist.includes(member.id) || member.user.bot)
      return console.log("1 usuário da BlackList não recebeu a mensagem.");
     member.send("oi pepe").catch(console.error);
  });
});
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement