Quiero cambiar el ícono de un gremio específico en el que se encuentra mi bot. Para hacerlo, necesito usar el método guild.setIcon() . Ya tengo la identificación del gremio, pero no sé cómo debo convertirla en un objeto que pueda usar.
La constante guildId se almacena como una cadena en config.json.
Aquí está mi index.js, donde intento ejecutar el código.
// 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");el error que me sale es
myGuild.setIcon("./images/image.png"); ^ TypeError: Cannot read properties of undefined (reading 'setIcon')Necesitas hacer esto en un evento. No se almacenan gremios en caché hasta que el cliente esté listo
client.on("ready", async () => { const myGuild = client.guilds.cache.get(guildId) await myGuild.setIcon("./images/image.png") })Tus problemas provienen del hecho de que estás tratando de obtener el gremio de tu caché de bot, pero él no lo tiene en su caché.
Primero, debe esperar a que su bot se conecte correctamente
Entonces, se supone que no debe leer directamente desde el caché, use los métodos de GuildManager (aquí necesita fetch )
para resumir, reemplace las 2 últimas líneas de su index.js por
client.on("ready", async () => { const myGuild = await client.guilds.fetch(guildId) myGuild.setIcon("./images/image.png") })