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

Discord.js机器人加载命令文件报错Collection is not a function问题求助

报错原因与修复方案

存在的问题

  • 拼写不统一:初始化时定义的属性为client.command(单数),加载命令时调用的是client.commands.set()(复数),执行命令时又换回client.command.get(),属性不匹配会直接触发未定义错误。
  • Collection调用方式错误:
    1. Collection是构造类,必须使用new关键字实例化,直接作为函数调用会抛出不是函数的错误
    2. discord.js v12及更高版本中,Collection不再挂载在Client类下,需要单独从discord.js包中导入

修复后的代码示例

// 顶部导入时引入Collection
const { Client, Collection } = require('discord.js');
const fs = require('fs');
// 初始化客户端,保留你原有的配置即可
const client = new Client({
  intents: [/* 你的网关意图配置 */]
});

// 统一使用复数commands属性,正确实例化Collection
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);
}

// 调用命令时统一使用commands属性
} else if (command === 'ping'){
    client.commands.get('ping').execute(message,args);
}

内容的提问来源于stack exchange,提问作者Vítor Grilo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:45:01