简体   繁体   中英

Discord bot not getting all users

I have written a discord bot using Discord.js and it used to get all the users of the discord server (I have the bot in one discord server only), but now it only gets 59 members. I have 300+ discord users in the server.

var Discord = require('discord.js');
var bot = new Discord.Client();

function getUsers() {
  let users = bot.users.array();

  for (let i = 0; i < users.length; i++) {
    let username = `${users[i].username}#${users[i].discriminator}`;
    console.log(`[${i}] ${username}`);
  }
}

There's a discord-side setting that may be relevant here.

If your bot tracks server members or downloads the entire member list, you may need the server members intent to receive member events and the member list.

Go to https://discord.com/developers/ and select your Discord application, go to the Bot settings, and enable "Server members intent" under "Priviliged gateway intents".

特权网关意图 > 服务器成员意图

Source: https://github.com/discordjs/discord.js/issues/3774#issuecomment-717824144

You have to use the method .fetchMembers() for every discord server the bot is in.

Try to use the following code:

function getUsers() {
  let guilds = bot.guilds.array();

  for (let i = 0; i < guilds.length; i++) {
    bot.guilds.get(guilds[i].id).fetchMembers().then(r => {
      r.members.array().forEach(r => {
        let username = `${r.user.username}#${r.user.discriminator}`;
        console.log(`${username}`);
      });
    });
  }
}

Bit late to the party here, but <Client>.users only returns the cached users at that point. Discord.js caches a member when they, for example, send a message or when you fetch that particular member. You would have to go through each member of the guild using <Guild>.fetchMembers() which returns the member objects of each and every one of them.

如果您使用的是guild.members.fetch() v12,它应该是guild.members.fetch()它将缓存所有成员。

var usersCount = client.guilds.cache.reduce((a, g) => a + g.memberCount, 0)

这对我有用...

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