TypeError:无法读取未定义的属性(读取‘Collection’)
2021-09-14
1068
今天我正在编写一个小型 discord.js 音乐机器人,但后来我遇到了一个错误,我真的不知道如何修复它。有人知道解决办法吗?
这是我的代码
const fs = require('fs');
const { discord, Client, Intents } = require('discord.js');
const myIntents = new Intents();
myIntents.add(Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES, Intents.FLAGS.GUILD_VOICE_STATES);
const client = new Client({ intents: myIntents });
const { Player } = require('discord-player');
client.player = new Player(client);
client.config = require('./config/bot');
client.emotes = client.config.emojis;
client.filters = client.config.filters;
client.commands = new discord.Collection();
fs.readdirSync('./commands').forEach(dirs => {
const commands = fs.readdirSync(`./commands/${dirs}`).filter(files => files.endsWith('.js'));
for (const file of commands) {
const command = require(`./commands/${dirs}/${file}`);
console.log(`Loading command ${file}`);
client.commands.set(command.name.toLowerCase(), command);
};
});
const events = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
const player = fs.readdirSync('./player').filter(file => file.endsWith('.js'));
for (const file of events) {
console.log(`Loading discord.js event ${file}`);
const event = require(`./events/${file}`);
client.on(file.split(".")[0], event.bind(null, client));
};
for (const file of player) {
console.log(`Loading discord-player event ${file}`);
const event = require(`./player/${file}`);
client.player.on(file.split(".")[0], event.bind(null, client));
};
client.login(client.config.discord.token);
1个回答
错误源自此特定行
client.commands.set(command.name.toLowerCase(), command);
为什么?因为这个:
const { discord, Client, Intents } = require('discord.js');
因此,您正在尝试从 discord.js 解构
discord
,但模块无法使用,如下所示,discord.js 模块具有以下函数和属性:
现在,如果您想
解构
它,您必须获取
Collection
本身,而不是
discord
,然后再获取
discord.Collection
。在文件的最顶部,您正在从模块 discord.js 解构一些组件,因此您也非常需要解构
Collection
!像这样:
const { Client, Intents, DiscordAPIError, Collection } = require('discord.js');
// then you may define it like so
client.commands = new Collection()
// then you may further use
client.commands.set(command.name.toLowerCase(), command);
这绝对有效,正如您在此处所见:
Zero
2021-09-15