How I Protected My Telegram Bot's AI Quota From Spam Users
The Problem
Free AI APIs have hard daily limits. One aggressive user can consume the entire quota. There's no native protection unless you build it.
I needed:
- Per-user rate limiting
- Global daily cap
- Response caching for common questions
The Fix - 3 Layers
Layer 1: Per-User Rate Limit
def check_rate_limit(user_id):
now = time.time()
hour_ago = now - 3600
uid = str(user_id)
user_requests.setdefault(uid, [])
user_requests[uid] = [t for t in user_requests[uid] if t > hour_ago]
if len(user_requests[uid]) >= 20:
return False
user_requests[uid].append(now)
return True
20 messages per hour per user. 99% of users never hit this.
Layer 2: Global Daily Cap
global_counter = {"date": "...", "count": 0}
def check_global_limit():
today = datetime.utcnow().strftime("%Y-%m-%d")
if global_counter["date"] != today:
global_counter["date"] = today
global_counter["count"] = 0
if global_counter["count"] >= 1400:
return False
global_counter["count"] += 1
return True
Cap at 1,400 - 100 buffer below the 1,500 limit.
Layer 3: Response Cache
answer_cache = {}
cached = answer_cache.get(question.lower().strip())
if cached:
return cached
answer_cache[question.lower().strip()] = answer
Common questions like What is Bitcoin? get cached. Repeat users hit the cache, not the API.
The Results
- Spam blocked: 20 msg/hour limit, 99% users unaffected
- Quota saved: 50-70% via caching
- Zero extra cost: All in-memory, no database
What I Learned
Free tiers are fragile. Build protection before you scale. Rate limiting + caching is the cheapest fix - no infrastructure needed.
Want the Full Script?
I packaged this as a production-tested template. Includes:
- Complete
quota_protection.py - Bot integration example
- Setup guide
- Multi-provider fallback ready
I'm building an automated Telegram empire in public. Follow along for real code, real numbers, no hype.
Top Comments
(0)
Comments
No comments yet. Start the discussion.