NanduWasTaken / Gemini-Chat-Bot

Simple Discord chat bot built using the Gemini Pro Model from Google
https://replit.com/@NanduWasTaken/Gemini-Discord-Chat-Bot
2 stars 0 forks source link

please help me (My internet works fine, but it always reports this error) #2

Open KaMiYiLu opened 1 month ago

KaMiYiLu commented 1 month ago

PS D:\gits\git.github.com.KaMiYiLu.remote-rep\Gemini-Chat-Bot-main> npm install discord.js

added 26 packages, and audited 27 packages in 20s

7 packages are looking for funding run npm fund for details

found 0 vulnerabilities PS D:\gits\git.github.com.KaMiYiLu.remote-rep\Gemini-Chat-Bot-main> npm run start

gemini-discord-bot@1.0.0 start node index.js

node:internal/process/promises:391 triggerUncaughtException(err, true / fromPromise /); ^

ConnectTimeoutError: Connect Timeout Error at onConnectTimeout (D:\gits\git.github.com.KaMiYiLu.remote-rep\Gemini-Chat-Bot-main\node_modules\undici\lib\core\connect.js:190:24) at D:\gits\git.github.com.KaMiYiLu.remote-rep\Gemini-Chat-Bot-main\node_modules\undici\lib\core\connect.js:133:46
at Immediate._onImmediate (D:\gits\git.github.com.KaMiYiLu.remote-rep\Gemini-Chat-Bot-main\node_modules\undici\lib\core\connect.js:172:33) at process.processImmediate (node:internal/timers:478:21) { code: 'UND_ERR_CONNECT_TIMEOUT' }

YockerFX commented 1 month ago

Maybe try the given code below:

  1. Message Fetching and Logging: • Fixed the forEach loop logic to correctly handle message authors and avoid undefined variables. • Ensured message.author.bot condition correctly handles bot messages.
    1. Generating Content: • Awaited the text method from result.response to ensure the response text is properly fetched.
    2. Chunking Large Messages: • Corrected the substring logic within the loop to avoid incorrect slicing of the response text. • Ensured await is used when sending replies to handle asynchronous execution correctly.

By applying these adjustments, the bot should be more robust and handle message creation and API responses effectively. Ensure that the API_KEY, TOKEN, and CHANNEL_ID in your config file are correctly set.

const { Client, IntentsBitField, Events } = require("discord.js");
const {
  GoogleGenerativeAI,
  HarmCategory,
  HarmBlockThreshold,
} = require("@google/generative-ai");
const { API_KEY, TOKEN, CHANNEL_ID } = require("./config");

const client = new Client({
  intents: [
    IntentsBitField.Flags.Guilds,
    IntentsBitField.Flags.GuildMessages,
    IntentsBitField.Flags.MessageContent,
  ],
});

const genAI = new GoogleGenerativeAI(API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-pro" });

const generationConfig = {
  temperature: 0.9,
  topK: 1,
  topP: 1,
  maxOutputTokens: 2048,
};

const safetySettings = [
  {
    category: HarmCategory.HARM_CATEGORY_HARASSMENT,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
  {
    category: HarmCategory.HARM_CATEGORY_HATE_SPEECH,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
  {
    category: HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
  {
    category: HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT,
    threshold: HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE,
  },
];

client.on(Events.ClientReady, () => {
  console.log("The bot is online!");
});

client.on(Events.MessageCreate, async (message) => {
  if (message.author.bot) return;
  if (message.channel.id !== CHANNEL_ID) return;
  if (message.content.startsWith("!")) return;

  let conversationLog = [];
  let prevRole = "model";

  try {
    await message.channel.sendTyping();
    let prevMessages = await message.channel.messages.fetch({ limit: 5 });
    prevMessages = prevMessages.reverse();

    prevMessages.forEach((msg, index, array) => {
      if (msg.content.startsWith("!")) return;
      if (msg.author.bot && msg.author.id !== client.user.id) return;

      if (index === array.length - 1) return;

      if (msg.author.id === client.user.id && prevRole === "user") {
        prevRole = "model";
        conversationLog.push({
          role: "model",
          parts: [{ text: msg.content }],
        });
      }

      if (msg.author.id === message.author.id && prevRole === "model") {
        prevRole = "user";
        conversationLog.push({
          role: "user",
          parts: [{ text: msg.content }],
        });
      }
    });

    console.log(conversationLog);

    const result = await model.generateContent({
      contents: conversationLog,
      generationConfig,
      safetySettings,
    });

    const finalText = await result.response.text(); // Await the text method
    const chunkSize = 2000;
    const stringArray = [];

    for (let i = 0; i < finalText.length; i += chunkSize) {
      stringArray.push(finalText.substring(i, i + chunkSize));
    }

    for (const string of stringArray) {
      await message.reply(string);
    }
  } catch (error) {
    console.log(error);
    message.reply("Something went wrong in the procedure....");
  }
});

client.login(TOKEN);

Hope this helps