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

使用require导入chatgpt包遇ERR_REQUIRE_ESM错误,多种方案无效

解决ERR_REQUIRE_ESM错误及Discord机器人无法上线问题

问题根源

chatgpt包是纯ESM模块,当你在package.json中添加"type": "module"后,所有.js文件默认采用ESM语法,不能再使用CommonJS的require()和module.exports,否则会引发语法冲突,导致机器人无法正常启动。

解决方案

将代码中所有CommonJS语法替换为ESM语法,具体修改如下:

修改后的完整代码

// <--- Discord Stuff --->

import Discord from 'discord.js';
const client = new Discord.Client(
    { intents: 32767 },
    { partials: ["MESSAGE", "CHANNEL", "REACTION", "GUILD_MEMBER"] }
);
export default client;

// <--- Discord Stuff --->

// Other Stuff

import { ChatGPTAPI } from 'chatgpt';
import dotenv from 'dotenv';

dotenv.config();

const api = new ChatGPTAPI({
    apiKey: process.env.OPENAI_API_KEY
})

// Other Stuff

client.on("messageCreate", async (message) => {
    if (message.channel.id === '1063790255880286269' && !message.author.bot) {
        try {
            const res = await api.sendMessage(message.content);
            await message.channel.send({ content: `<@${message.author.id}> ${res.text}` });
        } catch (err) {
            console.error('ChatGPT请求失败:', err);
            await message.channel.send('抱歉,暂时无法处理你的请求,请稍后再试。');
        }
    }
})

process.on("unhandledRejection", (reason, p) => {
    console.log(" [antiCrash] :: Unhandled Rejection/Catch");
    console.log(reason, p);
});
process.on("uncaughtException", (err, origin) => {
    console.log(" [antiCrash] :: Uncaught Exception/Catch");
    console.log(err, origin);
});
process.on("uncaughtExceptionMonitor", (err, origin) => {
    console.log(" [antiCrash] :: Uncaught Exception/Catch (MONITOR)");
    console.log(err, origin);
});

client.login(process.env.DISCORD_TOKEN);

关键修改点说明

  1. 把const Discord = require("discord.js")替换为import Discord from 'discord.js'
  2. 把module.exports = client替换为export default client
  3. 把const ChatGPTAPI = require('chatgpt')替换为import { ChatGPTAPI } from 'chatgpt'
  4. 把require("dotenv").config()替换为import dotenv from 'dotenv' + dotenv.config()
  5. 给ChatGPT请求添加try/catch捕获异常,避免API调用失败导致机器人崩溃

额外注意事项

  • 确保Node.js版本在16.14.0及以上,低版本对ESM支持不完善
  • 无需手动指定node-fetch版本,chatgpt包会自动处理依赖,避免版本冲突

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 02:00:32