Discord.js bot error: Unable to iterate through guilds

Hey everyone! I’m working on a Discord bot and I’m stuck. I want to print out the names of all the servers my bot is in. But when I run my code, I get this error: TypeError: client.guilds.forEach is not a function. Here’s my code:

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

bot.on('ready', () => {
  console.log('Bot is online as: ' + bot.user.tag);

  bot.user.setActivity('my pet hamster', {type: 'PLAYING'});

  bot.guilds.forEach((server) => {
    console.log(server.name);
  });
});

bot.login('token_here');

What am I doing wrong? How can I fix this so I can see all the server names? Thanks for any help!

yo, try this instead:

bot.guilds.cache.forEach(server => {
console.log(server.name);
});

the cache property is key here. discord.js changed things up in newer versions. this should do the trick for ya. lmk if u need anything else!

I ran into a similar issue when I was first learning Discord.js. The problem is that client.guilds isn’t an array, it’s actually a collection. To iterate through it, you need to use the cache property.

Try changing your code to this:

bot.guilds.cache.forEach((server) => {
  console.log(server.name);
});

This should work for you. Alternatively, if you prefer using modern JavaScript syntax, you could use:

for (const [id, server] of bot.guilds.cache) {
  console.log(server.name);
}

Both methods will accomplish the same thing. Just remember that when working with Discord.js v12 and above, many properties that were previously arrays are now collections, so you’ll often need to use the cache property to iterate through them.

I encountered this issue when upgrading to a newer version of Discord.js. The API changed, so client.guilds is now a Manager rather than a Collection. To fix it, you need to access the cache property:

bot.guilds.cache.forEach((server) => {
  console.log(server.name);
});

Alternatively, you could use the more concise map() method:

const serverNames = bot.guilds.cache.map(server => server.name);
console.log(serverNames);

This will give you an array of all server names. Remember to always check the documentation when updating libraries, as breaking changes like this are common.