François Mari
François Mari

Reputation: 61

Get the list of all user on a server discord.js

I'm trying to get all users from my server with a bot using discord.js, I wrote this code but it's not working, it's telling me : TypeError: client.guilds.get is not a function. Here is my code :

'use strict';
const Discord = require('discord.js');
const client = new Discord.Client();
const list = client.guilds.get("myServerID"); 
list.members.forEach(member => console.log(member.user.username)); 
client.login('myTokenID');

Thanks

Upvotes: 6

Views: 30807

Answers (2)

Syntle
Syntle

Reputation: 5174

Update ( 25 Feb 2023 ):

For discord v14+,

  1. Make sure you have GatewayIntentBits.GuildMembers or something like this to intents.
  2. Before using guild.members.cache, call guild.members.fetch() atleast once. I think subsequent calls can be made using cache.
const client = new Client({
    intents: [
        GatewayIntentBits.GuildMembers,  // MAKE SURE TO ADD THIS
    ],
});


client.on(Events.ClientReady, async (client) => {
    console.log("client ready");
    const guild = client.guilds.cache.get("<guild_id>");

    console.log("fetching users");
    let res = await guild.members.fetch();
    res.forEach((member) => {
        console.log(member.user.username);
    });
})


Since discord.js v12,

you now need to access the guilds collection using .cache and I can also see that you're trying to access the members collection so your solution would be:

'use strict';
const Discord = require('discord.js');
const client = new Discord.Client();
const list = client.guilds.cache.get("myServerID"); 
list.members.cache.forEach(member => console.log(member.user.username)); 
client.login('myTokenID');

Upvotes: 5

Samculo
Samculo

Reputation: 109

just use .fetch()

const guild = await client.guilds.fetch('your_id')
const members = await guild.members.fetch() // returns Collection

Upvotes: 1

Related Questions