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:
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.
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:
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.