ChatGPT API对接Discord机器人报错:require未定义的解决求助
问题修复方案
错误原因
你的项目因package.json中设置了"type": "module",所有.js文件会被当作ES模块处理,而ES模块不支持require()语法,必须使用import。代码中同时混用import和require,导致报错。
修复步骤
- 删除重复的
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';
- 代码中
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
相关产品推荐
相关产品推荐

