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

Discord Bot报错:Cannot read property 'name' of undefined 版本兼容排查

Discord Bot 报错:Cannot read property 'name' of undefined

错误详情

报错提示:Cannot read property 'name' of undefined,错误指向代码中props.help.name行。

错误截图:
错误截图

相关代码

const client = require("../bot");
const { Collection } = require("discord.js")
const fs = require("fs")
const config = require("../config.js")
let prefix = config.prefix

client.on("ready", () => {
  client.komutlar = new Collection();
  client.aliases = new Collection();
  fs.readdir("./komutlar/", (err, files) => {
    if (err) 
      console.error(err);

    files.forEach(f => {
      let props = require(`../komutlar/${f}`);
      client.komutlar.set(props.help.name, props);
      props.conf.aliases.forEach(alias => {
        client.aliases.set(alias, props.help.name);
      });
    });
  });
});

推测原因

怀疑是discord.js v13与v14版本混用导致的兼容性问题。

排查与解决步骤

1. 统一discord.js版本

  • 执行命令查看当前项目的discord.js版本及依赖树:
    npm list discord.js
    
  • 若存在多版本混用,先卸载现有依赖:
    npm uninstall discord.js
    
  • 重新安装指定版本(按需选择v13或v14):
    # 安装v14最新版
    npm install discord.js@latest
    # 或安装v13稳定版
    npm install discord.js@13.17.1
    

2. 检查命令模块的导出结构

报错直接原因是某个命令文件未正确导出help对象,导致props.help为undefined。需逐个检查./komutlar/目录下的文件,确保每个文件都包含正确的导出结构:

module.exports = {
  help: {
    name: "your-command-name" // 必须存在且为字符串类型
  },
  conf: {
    aliases: ["alias1", "alias2"] // 无需别名可设为空数组
  },
  // 命令执行逻辑
  execute(client, message, args) {
    // ...
  }
};

3. 添加错误捕获与文件过滤

修改加载命令的代码,增加错误处理逻辑,同时只加载.js文件避免无效文件干扰:

client.on("ready", () => {
  client.komutlar = new Collection();
  client.aliases = new Collection();
  fs.readdir("./komutlar/", (err, files) => {
    if (err) 
      console.error(err);

    // 仅过滤JavaScript文件
    const jsFiles = files.filter(file => file.endsWith(".js"));
    jsFiles.forEach(f => {
      try {
        let props = require(`../komutlar/${f}`);
        
        // 校验help对象及name字段有效性
        if (!props.help || typeof props.help.name !== "string") {
          console.warn(`[警告] 命令文件 ${f} 未配置有效的help.name,已跳过加载`);
          return;
        }

        client.komutlar.set(props.help.name, props);
        
        // 安全处理别名数组
        if (Array.isArray(props.conf?.aliases)) {
          props.conf.aliases.forEach(alias => {
            client.aliases.set(alias, props.help.name);
          });
        }
      } catch (loadErr) {
        console.error(`[错误] 加载命令文件 ${f} 失败:`, loadErr);
      }
    });
  });
});

内容的提问来源于stack exchange,提问作者NOVA PATTİS

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 09:07:35