首页 > 解决方案 > Discord.js 出现“TypeError:Client.Collection 不是构造函数”错误

问题描述

这是我第一次使用 Discord.js,因为我正在尝试为我朋友的服务器创建个人音乐机器人。首先,我正在阅读 CodeLyon 的教程,但我遇到了一个错误,我不知道如何修复它,因为视频是在网关意图添加到 Discord.js 之前发布的

我目前收到的错误状态:

TypeError: Client.Collection is not a constructor at Object.<anonymous> (C:\Users\Jewel Wildmoon\Downloads\My Discord Bots\Music Bots\Bot\main.js:9:19) 在 Module._compile(节点: internal/modules/cjs/loader:1101:14) 在 Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10) 在 Module.load (node:internal/modules/cjs/loader :981:32) 在 Function.Module._load (node:internal/modules/cjs/loader:822:12) 在 Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12) 在节点:内部/主/run_main_module:17:47

这是我的 main.js 文件中的代码:

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

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });

const prefix = '!';

const fs = require('fs');

client.commands = new Client.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.name, command);
}

client.once('ready', () => {
    console.log('Bot is Online!');
});

client.on('message', message => {
    if(!message.content.startsWith(prefix) || message.author.bot) return;

    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();

    if(command === 'ping'){
        client.commands.get('ping').execute(message, args);
    } else if(command == 'youtube'){
        message.channel.send('LINK');
    }
});


client.login('TOKEN');

这是我在 ping.js 文件中的当前代码:

module.exports = {
    name: 'ping',
    description: "This is a ping command",
    execute(message, args){
        message.channel.send('pong!');
    }
}

不太清楚在这里做什么,我没有使用 Discord.js,也不熟悉网关意图。那我还是 JavaScript 新手。

标签: javascriptnode.jsdiscorddiscord.js

解决方案


Collection由库导出,它不是客户端属性。您需要在顶部与Client和一起解构它Intents

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


client.commands = new Collection();

推荐阅读