【发布时间】:2022-08-04 01:54:33
【问题描述】:
我今天尝试在 discord.js 上执行斜杠命令,但我的控制台抛出了一些错误,它无法读取属性 toJSON 可能的解决方案是什么?
这是我的错误:
~/.../stuff/hazy $ node hazy.js
/storage/emulated/0/stuff/hazy/hazy.js:163
commands.push(command.data.toJSON());
^
TypeError: Cannot read properties of undefined (reading \'toJSON\')
at Object.<anonymous> (/storage/emulated/0/stuff/hazy/hazy.js:163:30)
at Module._compile (node:internal/modules/cjs/loader:1099:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
Node.js v17.9.0
这是我的代码:
const { REST } = require(\'@discordjs/rest\');
const { Routes } = require(\'discord-api-types/v9\');
const { token } = require(\'./config.json\');
const fs = require(\'node:fs\');
const commands = [];
const commandFiles = fs.readdirSync(\'./commands\').filter(file => file.endsWith(\'.js\'));
// Place your client and guild ids here
const clientId = \'913559840780091453\';
const guildId = \'912552644462121050\';
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: \'9\' }).setToken(token);
(async () => {
try {
console.log(\'Started refreshing application (/) commands.\');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log(\'Successfully reloaded application (/) commands.\');
} catch (error) {
console.error(error);
}
})();
-
command.data.toJSON在此对象上不存在。试试JSON.stringify(command.data)。 -
你要我写
commands.push(command.data.JSON.stringify(command.data);吗? -
或
commands.push(JSON.stringify(command.data));? -
好吧,在这种情况下,我会尝试两种方法,哈哈
-
@Vincent 错误表明
command.data未定义。如果该对象上不存在toJSON,则错误将是“...不是函数”。 @coco bar 你的循环遇到了一个没有data属性的command对象。检查您的所有命令文件和对象,并确保它们每个都有一个。
标签: javascript node.js discord discord.js slash