Discord.js运行报错Client.Collection is not a Constructor如何解决
错误修复方案
你遇到的TypeError: Client.Collection is not a constructor错误核心原因是:Discord.js v12及以上版本中,Collection已从Client类下剥离,为独立导出的工具类,需要单独引入后实例化。除此之外你的代码还有3处高版本兼容/语法错误,全部修改步骤如下:
- 第一步:调整discord.js导入项,新增
Collection引入
把首行代码修改为:const { Client, Intents, Collection } = require('discord.js'); - 第二步:修正Collection实例化代码
把client.commands = new Client.Collection();修改为:client.commands = new Collection(); - 第三步:修复命令文件路径的语法错误
你当前用单引号包裹了模板字符串,无法正确解析变量${file},需要把单引号替换为反引号,修改为:const command = require(`./commands/${file}`); - 第四步:适配高版本Discord.js的消息事件名
高版本中message事件已重命名为messageCreate,把事件监听代码修改为:client.on('messageCreate', message => {
修改后完整的main.js代码如下:
const { Client, Intents, Collection } = require('discord.js'); const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] }); const prefix = '!'; const fs = require('fs'); 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.name, command); } client.once('ready', () => { console.log('Bot is Online!'); }); client.on('messageCreate', 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代码无需修改,修改完成后即可正常启动机器人。
内容的提问来源于stack exchange,提问作者Jewel Wildmoon
相关产品推荐
相关产品推荐

