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

Discord接入ChatGPT机器人无响应问题排查求助

问题排查:Discord机器人上线正常但无消息回复

核心问题分析

你的代码存在两个关键错误,导致机器人无法响应消息:

  • Discord.js事件名称错误:Discord.js v14及以上版本已弃用message事件,改用messageCreate事件监听消息发送,原事件不会被触发。
  • OpenAI API调用方法错误:openai.promise()不是合法的调用方式,正确的文本补全调用应为openai.createCompletion();同时engine参数已被废弃,无需指定,model参数已足够。

修正后的完整代码

const Discord = require("discord.js");
const dotenv = require("dotenv");

dotenv.config();

const { Client, GatewayIntentBits } = require('discord.js'); 
const { Configuration, OpenAIApi } = require('openai');
const client = new Client({ intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent,
]});

const configuration = new Configuration({
    organization: process.env.OPENAI_ORG,
    apiKey: process.env.OPENAI_KEY,
});

const openai = new OpenAIApi(configuration);

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

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

  try {
    const result = await openai.createCompletion({
      prompt: message.content,
      model: "text-davinci-002",
      temperature: 0.7,
      max_tokens: 1024,
      n: 1,
      stop: "",
    });
    message.reply(result.data.choices[0].text.trim());
  } catch (error) {
    console.error(error);
    message.reply("处理请求时出现错误,请稍后再试。");
  }
});

client.login(process.env.DISCORD_TOKEN);

额外优化说明

  • 改用async/await替代then/catch,代码可读性更强
  • 对返回的文本调用trim()去除多余空白字符
  • 增加错误提示,方便用户知道请求失败

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 07:02:34