我想更改我的機器人所在的特定公會的圖示。為此,我需要使用該guild.setIcon()方法。我已經有了公會的 ID,但我不知道如何將它變成我可以使用的物件。
該guildId常數被存盤為在config.json字串。
這是我的 index.js,我試圖在其中運行代碼。
// 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");
我得到的錯誤是
myGuild.setIcon("./images/image.png");
^
TypeError: Cannot read properties of undefined (reading 'setIcon')
uj5u.com熱心網友回復:
您需要在活動中執行此操作。在客戶端準備好之前,不會快取任何公會
client.on("ready", async () => {
const myGuild = client.guilds.cache.get(guildId)
await myGuild.setIcon("./images/image.png")
})
uj5u.com熱心網友回復:
你的問題來自這樣一個事實,即你試圖從你的機器人快取中獲取公會,但他的快取中沒有它
首先,你必須等待你的機器人成功連接
然后,你不應該直接從快取中讀取,使用 GuildManager 方法(這里你需要fetch)
總結一下,更換2持續的行index.js通過
client.on("ready", async () => {
const myGuild = await client.guilds.fetch(guildId)
myGuild.setIcon("./images/image.png")
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/378836.html
下一篇:將物件拆分為兩個并重新列舉鍵
