javascript 错误[错误请求ESM]:ES模块的require()用于导入chatgpt

b5buobof  于 2023-03-21  发布在  Java
关注(0)|答案(1)|浏览(209)

我想要求chatgpt包,但它抛出一个错误。我已经安装了node fetch 2.6.6或2.6.1,但它不工作。我已经添加了"type": "module"到我的package.json文件,机器人也没有上线。
我的代码:

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

const Discord = require("discord.js");
const client = new Discord.Client(
    { intents: 32767 },
    { partials: ["MESSAGE", "CHANNEL", "REACTION", "GUILD_MEMBER"] }
);
module.exports = client;

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

// Other Stuff

const ChatGPTAPI = require('chatgpt');
const api = new ChatGPTAPI({
    apiKey: process.env.OPENAI_API_KEY
})
  
require("dotenv").config();

// Other Stuff

client.on("messageCreate", async (message) => {

    if (message.channel.id == '1063790255880286269' && !message.author.bot) {
        const res = await api.sendMessage(message.content)
        message.channel.send({ content: `<@${message.author.id}> ${res.text}` })
    } else return;
})

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);
nvbavucw

nvbavucw1#

要将ESM模块导入CommonJS,您需要使用import()函数。您需要解析promise以获取模块。

client.on("messageCreate", async (message) => {
    const { ChatGPTAPI } = await import("chatgpt");
    const api = new ChatGPTAPI({
       apiKey: process.env.OPENAI_API_KEY
    });

    if (message.channel.id == '1063790255880286269' && !message.author.bot) {
        const res = await api.sendMessage(message.content)
        message.channel.send({ content: `<@${message.author.id}> ${res.text}` })
    } else return;
})

相关问题