How I Protected My Telegram Bot's AI Quota From Spam Users
说明与用途
通过每用户速率限制、全局每日上限和响应缓存,保护Telegram机器人免受Gemini API配额滥用,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