Home > OS >  How to get guild object using guild ID
How to get guild object using guild ID

Time:12-10

I want to change the icon of a specific guild that my bot is in. To do so, I need to use the guild.setIcon() method. I already have the guild's ID but I don't know how I should go about turning it into an object that I can use.

The guildId constant is stored as a string in config.json.

Here is my index.js, where I'm trying to run the code.

// Require the necessary discord.js classes
const { Client, Collection, Intents } = require("discord.js");
const { token, guildId } = require("./config.json");
const fs = require("fs");

// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });

client.commands = new Collection();
const commandFiles = fs
  .readdirSync("./commands")
  .filter((file) => file.endsWith(".js"));

for (const file of commandFiles) {
  const command = require(`./commands/${file}`);
  client.commands.set(command.data.name, command);
}

const eventFiles = fs
  .readdirSync("./events")
  .filter((file) => file.endsWith(".js"));

for (const file of eventFiles) {
  const event = require(`./events/${file}`);
  if (event.once) {
    client.once(event.name, (...args) => event.execute(...args));
  } else {
    client.on(event.name, (...args) => event.execute(...args));
  }
}

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isCommand()) return;

  const command = client.commands.get(interaction.commandName);

  if (!command) return;

  try {
    await command.execute(interaction);
  } catch (error) {
    console.error(error);
    await interaction.reply({
      content: "There was an error while executing this command!",
      ephemeral: true,
    });
  }
});

client.login(token);

const myGuild = client.guilds.cache.get(guildId)
myGuild.setIcon("./images/image.png");

The error I get is

myGuild.setIcon("./images/image.png");
        ^

TypeError: Cannot read properties of undefined (reading 'setIcon')

CodePudding user response:

You need to do this in an event. No guilds are cached until the client is ready

client.on("ready", async () => {
  const myGuild = client.guilds.cache.get(guildId)
  await myGuild.setIcon("./images/image.png")
})

CodePudding user response:

Your issues comes from the fact that you're trying to get the guild from your bot cache, but he doesn't have it in it's cache

First, you have to wait for your bot to be successfully connected
Then, you're not supposed to read from the cache directly, use the GuildManager methods (here you need fetch)

to summarize, replace the 2 lasts lines of your index.js by

client.on("ready", async () => {
    const myGuild = await client.guilds.fetch(guildId)
    myGuild.setIcon("./images/image.png")
})
  • Related