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

ChatGPT API对接Discord机器人报错:require未定义的解决求助

问题修复方案

错误原因

你的项目因package.json中设置了"type": "module",所有.js文件会被当作ES模块处理,而ES模块不支持require()语法,必须使用import。代码中同时混用import和require,导致报错。

修复步骤

  1. 删除重复的require('discord.js')语句,改用ES模块的解构导入方式获取Client和Intents。

原代码中重复导入且使用了不被支持的require:

import Discord from 'discord.js';
// ...
const { Client, Intents } = require('discord.js');

直接修改为:

import { Client, Intents } from 'discord.js';

如果需要用到discord.js的其他导出,也可以合并为:

import Discord, { Client, Intents } from 'discord.js';
  1. 代码中readline和ChatGPTAPI的导入已经是正确的ES模块写法,无需修改。

修改后的完整代码

import { Client, Intents } from 'discord.js';
import { ChatGPTAPI } from 'chatgpt';
import readline from 'readline';

const apiKey = 'hidden';
const api = new ChatGPTAPI({ apiKey });

const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES] });
  
let conversationId;
let parentMessageId;

async function sendMessage(message, channel) {
  let res = await api.sendMessage(message, {
    conversationId: conversationId,
    parentMessageId: parentMessageId
  });

  conversationId = res.conversationId;
  parentMessageId = res.id;

  console.log('\nBot:', res.text, '\n');

  if (channel) {
    await channel.send(res.text);
  }
}

client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

client.on('message', async (message) => {
  if (message.author.bot) return;

  if (message.content === 'quit') {
    process.exit();
  }

  await sendMessage(message.content, message.channel);
});

async function main() {
  await sendMessage('Hello World!');

  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });

  function askQuestion() {
    rl.question('\nYou: ', async (question) => {
      if (question === 'quit') {
        rl.close();
        process.exit();
      }

      await sendMessage(question);
      askQuestion();
    });
  }

  askQuestion();
}

client.login('hidden');
main();

额外注意事项

  • 后续导入其他模块时,统一使用import语法,避免混用require。
  • 若坚持使用CommonJS语法,可将文件后缀改为.cjs,但不推荐在同一项目中混用两种模块规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 19:35:44