You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.js音乐机器人开发遇Collection相关TypeError错误如何解决?

报错原因

你触发TypeError: Cannot read properties of undefined (reading 'Collection')的核心问题出在discord.js的导入语句写法错误:
你当前的导入行是:

const { discord, Client, Intents } = require('discord.js');

discord.js的模块导出中不存在名为discord的属性,因此你解构得到的discord变量值为undefined,后续执行new discord.Collection()时自然会触发读取undefined属性的报错。


修复方案(二选一即可)

方案1:直接解构导入Collection(推荐)

  1. 修改导入语句,将Collection加入解构列表,删除不存在的discord解构项:
const { Client, Intents, Collection } = require('discord.js');
  1. 修改实例化Collection的代码,直接调用导入的Collection类:
client.commands = new Collection();

方案2:保留命名空间调用写法

如果你希望保持discord.xxx的调用习惯,就不要用解构写法导入模块:

  1. 把导入行改为全量导入:
const discord = require('discord.js');
  1. 后续所有discord.js导出的类都通过discord命名空间调用:
const myIntents = new discord.Intents();
myIntents.add(discord.Intents.FLAGS.GUILDS, discord.Intents.FLAGS.GUILD_MESSAGES, discord.Intents.FLAGS.GUILD_VOICE_STATES);

const client = new discord.Client({ intents: myIntents });

修改后可运行的完整代码(采用方案1)
const fs = require('fs');
const { Client, Intents, Collection } = 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 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);

内容的提问来源于stack exchange,提问作者Eighteen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 16:24:03