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

运行Discord Bot遇MODULE_NOT_FOUND错误,寻求解决方案

Discord Bot MODULE_NOT_FOUND 错误修复方案

核心问题分析

你遇到的MODULE_NOT_FOUND错误本质是相对路径解析错误,同时代码里还有几处语法/逻辑问题需要修正:


1. 修复路径解析问题

commandHandler.js位于src/Functions/Handlers/目录下,直接使用src/Commands/${folder}会被Node.js解析为相对于当前文件的错误路径(即src/Functions/Handlers/src/Commands/...),这显然不存在。

修改commandHandler.js中的路径,使用path模块生成正确的相对路径:

const { REST } = require("@discordjs/rest");
const { Routes } = require("discord-api-types/v9");
const fs = require("fs");
const path = require("node:path");

module.exports = (client) => {
  client.handleCommands = async () => {
    // 生成Commands目录的正确路径
    const commandsDir = path.join(__dirname, "../../Commands");
    const commandFolders = fs.readdirSync(commandsDir);
    
    for (const folder of commandFolders) {
      const folderPath = path.join(commandsDir, folder);
      const commandFiles = fs
        .readdirSync(folderPath)
        .filter((file) => file.endsWith(".js"));

      const { commands, commandArray } = client;
      for (const file of commandFiles) {
        const commandPath = path.join(folderPath, file);
        const command = require(commandPath);
        commands.set(command.data.name, command);
        // 修正:只推送command.data.toJSON(),不要推送command对象
        commandArray.push(command.data.toJSON());
        console.log(`Command: ${command.data.name} has been registered`);
      }
    }

    const clientId = "1070133880671174697";
    const guildId = "1070126560004276305";
    const rest = new REST({ version: "9" }).setToken(process.env.token);

    try {
      console.log("Started refreshing commands.");

      await rest.put(Routes.applicationCommands(clientId, guildId), {
        body: client.commandArray,
      });

      console.log("Successfully refreshed commands.");
    } catch (err) {
      // 修正:变量名从error改为err
      console.error(err);
    }
  };
};

2. 修复ping.js的导入缺失

ping.js中使用了SlashCommandBuilder但未导入,会导致运行时ReferenceError,添加导入语句:

const { SlashCommandBuilder } = require("discord.js");

module.exports = {
  data: new SlashCommandBuilder()
    .setName("ping")
    .setDescription("Returns my ping"),
  async execute(interaction, client) {
    console.log("pinged");
    // 可选:给用户返回响应
    await interaction.reply(`Pong! ${client.ws.ping}ms`);
  },
};

3. 修正bot.js中的路径(可选,提升严谨性)

bot.js中导入function文件的路径可以改为绝对路径,避免潜在的路径问题:

require("dotenv").config();
const { token } = process.env;
const { Client, Collection, GatewayIntentBits } = require("discord.js");
const fs = require("fs");
const path = require("node:path");

const client = new Client({ intents: GatewayIntentBits.Guilds });
client.commands = new Collection();
client.commandArray = [];

const functionsDir = path.join(__dirname, "Functions");
const functionFolders = fs.readdirSync(functionsDir);
for (const folder of functionFolders) {
  const folderPath = path.join(functionsDir, folder);
  const functionFiles = fs
    .readdirSync(folderPath)
    .filter((file) => file.endsWith(".js"));
  for (const file of functionFiles) {
    const filePath = path.join(folderPath, file);
    require(filePath)(client);
  }
}

client.handleCommands();
client.handleEvents();

client.login(token);

验证步骤

  1. 保存所有修改后的文件
  2. 重新运行Bot:node src/bot.js
  3. 检查控制台输出,确认命令注册成功且无报错

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 12:40:21