Zain-ul-din / whatsapp-ai-bot

This is a WhatsApp AI bot that uses various AI models, including Gemini, GPT, DALL-E, and StabilityAI, to generate responses to user input.
https://wa-ai-seven.vercel.app/
MIT License
161 stars 89 forks source link

Is it possible to add request limitations #23

Open Deplyapp opened 5 months ago

Deplyapp commented 5 months ago

The gemini free api Provides can it is possible to add a message limit of 3 mer minute per person.

Zain-ul-din commented 5 months ago

yes, you can if you know how to write code.

this is place from where you can start https://github.com/Zain-ul-din/whatsapp-ai-bot/blob/master/src/models/GeminiModel.ts

Basic Overview:

const useLimitedRequests = (timeInMs, requestAllowed) => {
  const map = {};

  return (sender) => {
    if (map[sender] == undefined) {
      map[sender] = {
        count: 0,
        lastRequestTime: new Date(),
      };
    }

    const { count, lastRequestTime } = map[sender];
    const elapsedTime = new Date() - lastRequestTime;

    if (elapsedTime >= timeInMs) {
      map[sender] = { count: 1, lastRequestTime: new Date() };
      return true;
    }

    if (count >= requestAllowed) {
      return false;
    }

    map[sender] = { count: count + 1, lastRequestTime };
    return true;
  };
};

// usage
const isUserAllowed = useLimitedRequests(60000, 3) // 60000ms = 1min

if(!isUserAllowed(msg.from)) return; // quota exceed

from string- ID for the Chat that this message was sent to, except if the message was sent by the current user.

Appendix

Whatspp Js Docs link: https://docs.wwebjs.dev/Message.html

vpsbykaif commented 5 months ago

I can paste this code in gemini.ts to get the function

zain-ul-din-zafar commented 5 months ago

I added a rate-limiting feature to this branch but it has not been tested yet. check this out

https://github.com/zainuldeen/whatsapp-ai-bot/tree/issue_23