Hfzune commited on
Commit
7564bb1
·
verified ·
1 Parent(s): 9b29d2c

Create bot/webhook.py

Browse files
Files changed (1) hide show
  1. bot/webhook.py +92 -0
bot/webhook.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import logging
3
+ import time
4
+
5
+ from bot.telegram_api import send_message, edit_message
6
+ from bot.onboarding import (
7
+ handle_start,
8
+ handle_token_command,
9
+ handle_reset,
10
+ handle_help,
11
+ handle_stats,
12
+ )
13
+ from bot.streaming import stream_reply
14
+ from db import models as dbm
15
+
16
+ log = logging.getLogger("webhook")
17
+
18
+ # Per-user soft rate limit: 1 message / 2 seconds
19
+ _last_msg = {}
20
+ RATE_SECONDS = 2.0
21
+
22
+
23
+ async def handle_update(update: dict):
24
+ msg = update.get("message") or update.get("edited_message")
25
+ if not msg:
26
+ return
27
+
28
+ chat = msg.get("chat", {})
29
+ chat_id = chat.get("id")
30
+ from_user = msg.get("from", {})
31
+ user_id = from_user.get("id")
32
+ username = from_user.get("username")
33
+ first_name = from_user.get("first_name")
34
+
35
+ text = (msg.get("text") or "").strip()
36
+ if not text:
37
+ await send_message(chat_id, "⚠️ Only text messages are supported.")
38
+ return
39
+
40
+ # Upsert user record
41
+ dbm.upsert_user(user_id, username, first_name)
42
+
43
+ # Command routing
44
+ if text.startswith("/start"):
45
+ await handle_start(chat_id, user_id, username)
46
+ return
47
+ if text.startswith("/token"):
48
+ parts = text.split(maxsplit=1)
49
+ arg = parts[1].strip() if len(parts) > 1 else ""
50
+ await handle_token_command(chat_id, user_id, arg)
51
+ return
52
+ if text.startswith("/reset"):
53
+ await handle_reset(chat_id, user_id)
54
+ return
55
+ if text.startswith("/help"):
56
+ await handle_help(chat_id)
57
+ return
58
+ if text.startswith("/stats"):
59
+ await handle_stats(chat_id, user_id)
60
+ return
61
+
62
+ # Rate limit
63
+ now = time.time()
64
+ last = _last_msg.get(user_id, 0)
65
+ if now - last < RATE_SECONDS:
66
+ await send_message(chat_id, "⏳ Slow down a moment.")
67
+ return
68
+ _last_msg[user_id] = now
69
+
70
+ # Auth check
71
+ if not dbm.user_has_valid_token(user_id):
72
+ await send_message(
73
+ chat_id,
74
+ "🔒 You need a valid access token.\nSend <code>/token &lt;your-token&gt;</code> to activate.",
75
+ )
76
+ return
77
+
78
+ # Daily limit check
79
+ try:
80
+ daily_limit = int(dbm.get_setting("daily_turn_limit", "100"))
81
+ except Exception:
82
+ daily_limit = 100
83
+ user = dbm.get_user(user_id)
84
+ if user and user.get("total_turns", 0) >= daily_limit:
85
+ await send_message(chat_id, "⚠️ Daily message limit reached. Try again tomorrow.")
86
+ return
87
+
88
+ # Persist user turn
89
+ dbm.add_message(user_id, "user", text)
90
+
91
+ # Stream reply
92
+ await stream_reply(chat_id, user_id, text)