user9682247
user9682247

Reputation:

How to list all members from a specific server?

My code is

const list = client.guilds.find("id", "335507048017952771")
       for (user of list.users){
         console.log(user[1].username);
       }

This does literally nothing. There is no error or anything.

I just want the bot to find a server and then log all members from said server.

Displaying all connected users Discord.js The answers in this question didn't really help me at all. I did try using message.guild.users but that also did nothing. Can't seem to find anything on the Discord.js site to help me either.

Upvotes: 4

Views: 65412

Answers (2)

Shyne
Shyne

Reputation: 339

Updated Answer

Since Discord.js v12, the members property of Guild changed from a Collection to a GuildMemberManager. This means you cannot iterate over it anymore like in the previous answer.

Using GuildMemberManager

You can use the fetch property to get the member list as a collection. Note that fetch is an asynchronous function and you'll have to handle it accordingly.

// Get the target guild
const guild = client.guilds.resolve("335507048017952771");

// Fetch the members of the guild and log them
guild.members.fetch()
    .then(console.log)
    .catch(console.error);

You can force discord.js to ignore the cache and query all the data from the API for the most up-to-date data, but i would not encourage it for large bots/servers.

// Fetch the members of the guild from the API and log them
guild.members.fetch({ force: true })
    .then(console.log)
    .catch(console.error);

Member Count

Considering that some begineers might look at this, note that Guild has a property named memberCount that allows you to get the number of members in the guild rather than fetching the list if this is what you're trying to achieve.

Upvotes: 3

newbie
newbie

Reputation: 1571

Firstly, don't use .find("id", "335507048017952771"), you should be using .get("335507048017952771"), as it says on the discord.js documentation.

All collections used in Discord.js are mapped using their id property, and if you want to find by id you should use the get method. See MDN for details.

A Guild does not have a users property, where as it has a members property, which returns a Collection of GuildMembers. Now to get the username from each member you can obtain that from the user property of the GuildMember. So, you will need to iterate through the collection of GuildMembers, and get the <GuildMember>.user.username.

There are several ways to do this, I will be using the forEach() method. Here's what that would look like as a result:

// Get the Guild and store it under the variable "list"
const list = client.guilds.get("335507048017952771"); 

// Iterate through the collection of GuildMembers from the Guild getting the username property of each member 
list.members.forEach(member => console.log(member.user.username)); 

Upvotes: 11

Related Questions