Home > Net >  Discord.js Get all members in a guild
Discord.js Get all members in a guild

Time:12-06

I was trying to get all the member's usernames on my discord server
However, it just gave back 8-9/25 members including 6 BOTs

Here is my code

const list = client.guilds.cache.get(msg.guildId); 
list.members.cache.each(r => {
   console.log(r.user.username)
})

Besides that, I have also tried these ways

const list = client.guilds.cache.get(msg.guildId); 
   list.members.cache.array().forEach(r => {
      console.log(r.user.username)
})
const user = client.users.cache.find(u => u.username == '//The Given username')
const user = msg.guild.roles.cache.get('//The Main Role in my Server')
             .members.map(m => m.user.username == '//The given username')
let user = client.users.cache.get('username', '//The given username');

But sometimes it just returned my and my BOT's username or undefined.

I'm trying to get all the members on the server and from that, I can find out the user has the same username with the given username, not tags or IDs

I have turned on the Gateway Intents but it didn't help

Please help with my project, I really need all the suggestions from you

CodePudding user response:

Use .fetch() to cache all members, and return them. Make sure you have GUILD_MEMBERS intent:

list.members.fetch().then(m => {
  let members = m.cache.map(u => u.user.username)
  console.log(members) //array of all members
  //you can also use "m.cache.each(u => console.log(u.user.username))" to log each one individually
})

Or use async-await

const m = await list.members.fetch()
let members = m.cache.map(u => u.user.username)
console.log(members)

CodePudding user response:

you can get all ids of users in that server with this (I'm not sure)

const Guild = client.guilds.cache.get("server id");
const Members = Guild.members.cache.map(member => member.id); 
console.log(Members);

or this

const list = <Guild>.members.cache.keys();
list.forEach(id => console.log(id));
  • Related