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

如何修复Discord机器人运行时Cannot find module '.functions/handleCommands.js'错误

问题解决方案

直接报错原因修复

你当前触发MODULE_NOT_FOUND的核心原因是路径引用错误:
你在bot.js第14行的导入语句写的是require('.functions/handleCommands.js'),漏掉了相对路径的分隔符/,正确写法为require('./functions/handleCommands.js'),代表从bot.js当前所在的src目录下,查找functions文件夹内的对应文件。
如果修改路径后仍报错,检查目录结构是否符合要求:

  • src目录下必须存在functions文件夹
  • functions文件夹内的文件名为handleCommands.js,大小写完全匹配(Windows环境对大小写不敏感,但后续部署到Linux环境会因此报错)

handleCommands.js代码错误修复

你当前的handleCommands.js还有多处语法错误,会导致路径问题修复后仍无法正常运行,需要逐一修正:

  1. 缺少依赖导入:你用到了REST类但没有导入,在文件顶部添加一行const { REST } = require('@discordjs/rest');
  2. 变量拼写错误:你全程把client拼写为clinet,需要全局替换统一:
    • 导出函数的参数(clinet)改为(client)
    • 所有clinet.handleCommands、clinet.commandArray都替换为client.xxx
    • 原代码中client.commands.set这行的client未定义,拼写统一后即可正常使用
  3. 逻辑位置错误:你把REST注册命令的匿名自执行函数写在了module.exports外部,此时client.commandArray还没有被赋值,会触发undefined报错,需要把这段逻辑移到client.handleCommands方法内部的末尾,等命令数组赋值完成后再执行。

修正后的完整代码如下:

const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const fs = require('fs');
const clientId = 'redacted'; // 你的机器人ID
const guildId = 'redacted'; // 测试服务器ID

module.exports = (client) => {
    client.handleCommands = async (commandFolders, path) =>{
        client.commandArray = [];
        for(folder of commandFolders){
            const commandFiles = fs.readdirSync(`${path}/${folder}`).filter(file => file.endsWith('.js'));
            for (const file of commandFiles) {
                const command = require(`../commands/${folder}/${file}`);
                client.commands.set(command.data.name, command);
                client.commandArray.push(command.data.toJSON());
            }
        }

        const rest = new REST({ version: '9' }).setToken(process.env.token);
        try {
            console.log('Started refreshing application (/) commands.');
            await rest.put(
                Routes.applicationGuildCommands(clientId, guildId),
                { body: client.commandArray },
            );
            console.log('Successfully reloaded application (/) commands.');
        } catch (error) {
            console.error(error);
        }
    };
};

同类错误通用排查方法

  • 核对导入路径写法:
    • ./xxx代表从当前文件所在目录查找
    • ../xxx代表从当前文件的上一级目录查找
    • 没有前缀的xxx会优先到node_modules目录查找,找不到就会报错
  • 检查文件/文件夹名的拼写、大小写是否完全匹配
  • 确认目标文件确实存在于路径指向的位置
  • 如果是第三方包触发的MODULE_NOT_FOUND,直接执行npm install 对应包名重装即可

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

相关产品推荐
方舟 Agent Plan

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

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