How I Protected My Telegram Bot's AI Quota From Spam Users
Описание и применение
Защита Telegram‑бота от злоупотребления квотой Gemini: реализованы лимиты на пользователя, глобальный дневной лимит и кэш ответов, что позволяет 99% пользователей пользоваться ботом без ошибок и экономит 50‑70% запросов.
Задача
A single aggressive user sent 1,400 messages in 3 hours, exhausting the free-tier Gemini API quota of 1,500 requests per day and causing 999+ users to receive quota exceeded errors.
Результат
Spam blocked by per‑user limit; 99% users unaffected; 50‑70% quota saved via caching; no extra cost as all logic runs in memory.
Рабочий процесс
- Implement per‑user rate limit (20 msgs/hr) using in‑memory timestamp list.
- Implement global daily counter with 1,400 request cap and 100‑request buffer.
- Add in‑memory response cache keyed by normalized question text.
- Integrate checks into bot command handler before calling Gemini API.
- Return cached answer if available; otherwise call API and cache result.
- Reset daily counter at UTC midnight.
- Monitor and log quota usage for future adjustments.
Доказательства
20 messages per hour per user. 99% users never hit this.
Cap at 1,400 — 100 buffer below the 1,500 limit.
Quota saved: 50-70% via caching
- Дата записи: 2026-09-22T07:00:36.206Z