From d7dfc6556dc32f068ea42d910fc4f27c76bb89ed Mon Sep 17 00:00:00 2001 From: dhabyap Date: Tue, 14 Apr 2026 12:35:51 +0700 Subject: [PATCH] Implement 10s rate limiting for AI processing (Closes #27) --- handlers/nlp_message.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/handlers/nlp_message.py b/handlers/nlp_message.py index 54c2f4a..9bf3844 100644 --- a/handlers/nlp_message.py +++ b/handlers/nlp_message.py @@ -1,5 +1,10 @@ import database from ai_brain import get_json_data_from_text +import time + +# Dictionary untuk menyimpan timestamp pemrosesan AI terakhir per user (Rate Limiting) +last_ai_calls = {} +RATE_LIMIT_COOLDOWN = 10 # detik def register_handlers(bot): # Gunakan lambda yang menangkap semua teks, tapi pastikan bukan command @@ -20,6 +25,18 @@ def handle_text(message): # Show typing status while processing bot.send_chat_action(message.chat.id, 'typing') + # --- RATE LIMITING CHECK --- + now = time.time() + if user_id in last_ai_calls: + elapsed = now - last_ai_calls[user_id] + if elapsed < RATE_LIMIT_COOLDOWN: + remaining = int(RATE_LIMIT_COOLDOWN - elapsed) + bot.reply_to(message, f"⚠️ *Terlalu cepat!* Mohon tunggu {remaining} detik lagi sebelum mencatat transaksi baru... 🙏", parse_mode='Markdown') + return + + # Update timestamp pemrosesan terakhir + last_ai_calls[user_id] = now + # Process text with AI data = get_json_data_from_text(text)