User: const axios = require('axios');
const { sendMessage } = require('../handles/sendMessage');

const conversationHistory = new Map();
const timeouts = new Map();

const persona = "you're rick , you're an ai assistant, you're the best and the best, use emojies in u're answers, you speak just arabic";

module.exports = {
  name: 'gpt4',
  description: 'Interact with Gemini API with images support',
  usage: 'gpt4 [your message]',
  author: 'coffee',

  async execute(senderId, args, pageAccessToken) {
    const prompt = args.join(' ');
    if (!prompt) return sendMessage(senderId, { text: "Usage: gpt4 <question>" }, pageAccessToken);

    if (!conversationHistory.has(senderId)) {
      conversationHistory.set(senderId, []);
    }

    let chatHistory = conversationHistory.get(senderId);
    if (chatHistory.length === 0) {
      chatHistory.push(`Instruction: ${persona}`);
    }

    chatHistory.push(`User: ${prompt}`);

    if (chatHistory.length > 6) {
      chatHistory.shift();
    }

    const fullConversation = chatHistory.join("\");

    try {
      const { data } = await axios.get(`http://sgp1.hmvhostings.com:25721/gemini?question=${encodeURIComponent(fullConversation)}`);

      let responseText = data.answer ? data.answer : "لم أتمكن من فهم الإجابة.";

      chatHistory.push(`Bot: ${responseText}`);

      if (chatHistory.length > 6) {
        chatHistory.shift();
      }

      
      await sendMessage(senderId, { text: responseText }, pageAccessToken);

      
      if (data.web_images && data.web_images.length > 0) {
        for (let imageUrl of data.web_images) {
          await sendMessage(senderId, {
            attachment: {
              type: "image",
              payload: { url: imageUrl, is_reusable: true }
            }
          }, pageAccessToken);
        }
      }

    
      if (timeouts.has(senderId)) {
        clearTimeout(timeouts.get(senderId));
      }

      const timeout = setTimeout(() => {
        conversationHistory.delete(senderId);
        timeouts.delete(senderId);
      }, 10 * 60 * 1000);

      timeouts.set(senderId, timeout);

    } catch (error) {
      console.error("Error fetching data:", error);
      sendMessage(senderId, { text: 'حدث خطأ أثناء معالجة الطلب. حاول مرة أخرى لاحقًا.' }, pageAccessToken);
    }
  }
};
Assistant: It looks like you've posted a JavaScript code snippet for a module that interacts with a Gemini API using Axios to send messages and handle conversations for a chatbot. Below are some comments on the code along with potential improvements:

### Overview of the Code
1. **Imports**: It imports Axios for making HTTP requests and a `sendMessage` function for sending responses back to the user.
  
2. **Conversation Management**: 
   - The `conversationHistory` Map keeps track of the conversation history for each sender.
   - The `timeouts` Map manages session timeouts, allowing the chat context to persist for a duration of 10 minutes.

3. **Persona**: A persona string defines the bot's character and response language. In this case, it's a playful character called Rick who responds in Arabic.

4. **Execution Logic**:
   - The bot listens for a message and constructs a prompt based on user input.
   - It checks if there’s existing conversation history; if not, it initializes one.
   - The conversation history is updated, and when it surpasses 6 messages, the oldest message is discarded.

5. **API Interaction**: The bot constructs a full prompt and sends it to the specified Gemini API, handling the response appropriately.

6. **Error Handling**: There are catch blocks for logging errors and sending error messages back to the user.

### Improvements & Suggestions
1. **String Interpolation**:
   There seems to be a syntax error in the line where the full conversation string is constructed:
   ```javascript
   const fullConversation = chatHistory.join("\");
   ```
   It should be fixed as:
   ```javascript
   const fullConversation = chatHistory.join("\n");
   ```

2. **Encapsulation of Persona Logic**: Consider encapsulating the persona definition and chat history management into a separate module to make the code cleaner and more maintainable.

3. **Error Handling**: Enhance error messages based on different error types (e.g., network errors vs. invalid responses) to provide better feedback.

4. **Timeout Configurability**: Instead of hardcoding the timeout duration, consider making it a configurable parameter to allow for flexibility (e.g., through environment variables).

5. **Image Handling**: When sending images, check if the `sendMessage` function can process messages in bulk to reduce the number of sending calls.

6. **Logging**: Enhance your logging functionality for better debugging and monitoring of user interactions.

By implementing these improvements, you'll make the bot more robust, maintainable, and user-friendly. If you have specific questions or requests about expanding on certain aspects or adding features, feel free to ask!
User: مرحبا
User: مرحبا
Assistant: