Discord.js v11无法获取服务器全部成员日志问题求助
Hey there! I see you're stuck with only 2 server members showing up in your console, even when switching between map() and forEach(). Let's sort this out together.
Why This Happens
In Discord.js v11, your bot doesn't automatically cache every single member of a server by default. It only stores members that have interacted with the bot (like sending a message, joining recently, or sharing a voice channel) in its local cache. That's exactly why you're only seeing those 2 users right now.
The Fix: Fetch All Members Explicitly
To get the full list of server members, you need to ask the Discord API directly for the complete member roster using msg.guild.fetchMembers(). This method returns a Promise, so we'll use .then() to make sure we have all the data before logging anything.
Here's your updated code:
if (cmd === "members") { console.log("Server: " + msg.guild.name); // Fetch all members from Discord's API msg.guild.fetchMembers() .then(updatedGuild => { // Now iterate over every member in the server updatedGuild.members.forEach(member => { console.log(green(member.user.username)); }); }) .catch(error => { // Catch and log any errors that pop up during the fetch console.error("Failed to load members:", error); }); }
Quick Tips
- After running
fetchMembers()once, the bot's cache will be updated with all server members, so future commands might not need to re-fetch (though it's still safe to do so). - If you're working with a huge server, keep an eye out for Discord API rate limits—this method works smoothly for small to medium-sized servers.
- A quick heads-up: Discord.js v11 is no longer maintained. If you can, consider upgrading to a newer version (v14 is the latest as of now) for better features and security, but this fix will work perfectly for your v11 setup.
内容的提问来源于stack exchange,提问作者user14023978

