Fetching a guild using its ID returns every available guild in discord.js

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Fetching a guild using its ID returns every available guild in discord.js on this date .

I am trying to fetch a guild using its ID which the bot is in, but it doesn’t seem to work. Whenever I run this, it outputs a collection of every guild the client is in.

e is read from a JSON file, the id property is a direct copy from the server.

client.guilds.fetch(e.id).then((guild) => {
  // logs every available guild instead of the one where id is e.id
  console.log(guild)
})

Here are my intents and partials

const client = new Discord.Client({
  intents: [
    Intents.FLAGS.GUILDS,
    Intents.FLAGS.GUILD_MESSAGES,
    Intents.FLAGS.DIRECT_MESSAGES, 
    Intents.FLAGS.GUILD_MESSAGE_REACTIONS, 
    Intents.FLAGS.DIRECT_MESSAGE_REACTIONS
  ],
  partials: ['MESSAGE', 'CHANNEL', 'REACTION'], 
});

Answer

There are two options; either your id is undefined or it’s a number.

As fetch only accepts a GuildResolvable, or a FetchGuildOptions/FetchGuildsOptions object as its parameter. If you pass something else, it’s just ignored and every available guild gets fetched (just like you mentioned).

I think your id is a snowflake, as you mentioned that it’s coming from a JSON file. Snowflakes should always be strings. If you store these IDs as numbers, JS has difficulty interpreting them. Any number greater than the MAX_SAFE_INTEGER becomes a different number, and if you provide a different ID, again, every available guild gets fetched.

For example, if your snowflake is 921423246421811231, it becomes 921423246421811200. Try to run the snippet below, you’ll see that it logs the second number, not what the value of e.id:

let e = {
  id: 921423246421811231
}

console.log(e.id)

To solve this, make sure you store the id as a string in your JSON file:

{
  "id": "921423246421811231"
}