开发基于Google Bard的Discord聊天机器人遇TypeError错误求助及修正
问题分析
- 核心偏差与API错误:你需求是基于Google Bard的机器人,但代码错误引入了Dialogflow服务;且@google-cloud/dialogflow v6.1.0已移除
Dialogflow构造函数,改用SessionsClient类,直接实例化Dialogflow必然触发TypeError: Dialogflow is not a constructor。 - 过滤逻辑失效:
const ignore = '!' && '?'逻辑错误,实际仅会排除以?开头的消息,无法过滤!开头的内容。 - 未定义变量:
conversationState未声明就使用,会引发ReferenceError。 - 消息内容处理错误:
${msg}会将整个Discord Message对象转为字符串,而非用户输入的文本,应该用msg.content。
修正后的完整代码
说明:Google Bard已整合入Gemini系列,我们使用官方Gemini API实现对话功能,需先安装依赖discord.js和@google/generative-ai。
首先安装依赖:
npm install discord.js @google/generative-ai
完整代码:
// 导入Discord.js客户端和必要的意图 const { Client, GatewayIntentBits } = require('discord.js'); // 导入Google Gemini API客户端 const { GoogleGenerativeAI } = require('@google/generative-ai'); // 配置你的Discord Bot Token和Gemini API Key const DISCORD_BOT_TOKEN = '你的Discord机器人Token'; const GEMINI_API_KEY = '你的Google Gemini API Key'; const BOT_CHANNEL_ID = '1155186010485960909'; // 初始化Gemini客户端 const genAI = new GoogleGenerativeAI(GEMINI_API_KEY); // 选择对应原Bard对话能力的Gemini模型 const model = genAI.getGenerativeModel({ model: 'gemini-pro' }); // 初始化Discord客户端 const client = new Client({ intents: [ GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent ] }); // 机器人就绪事件 client.on('ready', () => { console.log(`机器人已登录:${client.user.tag}`); }); // 消息创建事件 client.on('messageCreate', async (msg) => { // 过滤条件:机器人消息忽略、非指定频道忽略、以!或?开头的消息忽略 if (msg.author.bot || msg.channelId !== BOT_CHANNEL_ID || /^[!?]/.test(msg.content)) { return; } try { // 调用Gemini API生成回复 const result = await model.generateContent(msg.content); const response = await result.response; const replyText = response.text(); // 回复用户消息 await msg.reply(replyText); } catch (error) { console.error('生成回复时出错:', error); await msg.reply('抱歉,我现在无法回复你的消息,请稍后再试。'); } }); // 登录Discord机器人 client.login(DISCORD_BOT_TOKEN);
使用说明
- 前往Google AI Studio创建API Key,替换代码中的
GEMINI_API_KEY。 - 前往Discord开发者门户获取机器人Token,替换
DISCORD_BOT_TOKEN。 - 确保机器人已被邀请到你的服务器,并拥有发送消息的权限。
- 运行代码:
node bot.js。
内容的提问来源于stack exchange,提问作者average discord bot maker
相关产品推荐
相关产品推荐

