codeBOKER commited on
Commit
ae1bd8b
·
1 Parent(s): 437b54a

Consolidate Telegram webhook fixes and debugging improvements

Browse files
Files changed (3) hide show
  1. ai_service.py +3 -7
  2. config.py +2 -2
  3. telegram_handlers.py +56 -22
ai_service.py CHANGED
@@ -10,17 +10,11 @@ MODEL_NAME = HF_MODEL
10
  def clean_ai_response(text: str):
11
  if not text: return ""
12
  text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)
13
- # Remove HTML tags
14
  text = re.sub(r'<br\s*/?>', '\n', text)
15
  text = re.sub(r'<[^>]+>', '', text)
16
- # Remove markdown tables (lines that start and end with |)
17
  text = re.sub(r'^\|.*\|\s*$', '', text, flags=re.MULTILINE)
18
  text = re.sub(r'^[\s|:-]+$', '', text, flags=re.MULTILINE)
19
- # Remove markdown bold/italic
20
- text = re.sub(r'[*_]{1,3}(.*?)[*_]{1,3}', r'\1', text)
21
- # Remove markdown headers
22
  text = re.sub(r'^#{1,6}\s*', '', text, flags=re.MULTILINE)
23
- # Clean up extra blank lines
24
  text = re.sub(r'\n{3,}', '\n\n', text)
25
  return text.strip()
26
 
@@ -105,7 +99,9 @@ async def get_ai_response(user_query: str, telegram_id: int):
105
  completion = await loop.run_in_executor(None, lambda: call_hf(messages))
106
  response_message = completion.choices[0].message
107
 
108
- final_response = clean_ai_response(response_message.content)
 
 
109
 
110
  if db_manager:
111
  db_manager.save_message(telegram_id, user_query, "user")
 
10
  def clean_ai_response(text: str):
11
  if not text: return ""
12
  text = re.sub(r'<think>.*?</think>', '', text, flags=re.DOTALL)
 
13
  text = re.sub(r'<br\s*/?>', '\n', text)
14
  text = re.sub(r'<[^>]+>', '', text)
 
15
  text = re.sub(r'^\|.*\|\s*$', '', text, flags=re.MULTILINE)
16
  text = re.sub(r'^[\s|:-]+$', '', text, flags=re.MULTILINE)
 
 
 
17
  text = re.sub(r'^#{1,6}\s*', '', text, flags=re.MULTILINE)
 
18
  text = re.sub(r'\n{3,}', '\n\n', text)
19
  return text.strip()
20
 
 
99
  completion = await loop.run_in_executor(None, lambda: call_hf(messages))
100
  response_message = completion.choices[0].message
101
 
102
+ final_response = clean_ai_response(response_message.content if response_message.content else "")
103
+ print(f"--- AI Raw Response: {repr(response_message.content)} ---")
104
+ print(f"--- AI Final Response: {repr(final_response)} ---")
105
 
106
  if db_manager:
107
  db_manager.save_message(telegram_id, user_query, "user")
config.py CHANGED
@@ -12,10 +12,10 @@ HF_TOKEN = os.environ.get("HF_TOKEN") or os.environ.get("HF_API_KEY")
12
  TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")
13
  SUPABASE_URL = os.environ.get("SUPABASE_URL")
14
  SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
15
- TELEGRAM_DOMAIN = os.environ.get("TELEGRAM_DOMAIN")
16
 
17
  # Only create TELEGRAM_URL if token exists
18
- TELEGRAM_URL = f"{TELEGRAM_DOMAIN}/bot{TELEGRAM_TOKEN}/sendMessage" if TELEGRAM_TOKEN else None
19
 
20
  EMBED_MODEL = os.environ.get("EMBED_MODEL", "multilingual-e5-large")
21
  HF_MODEL = os.environ.get(
 
12
  TELEGRAM_TOKEN = os.environ.get("TELEGRAM_TOKEN")
13
  SUPABASE_URL = os.environ.get("SUPABASE_URL")
14
  SUPABASE_KEY = os.environ.get("SUPABASE_KEY")
15
+ TELEGRAM_DOMAIN = os.environ.get("TELEGRAM_DOMAIN", "https://api.telegram.org").rstrip("/")
16
 
17
  # Only create TELEGRAM_URL if token exists
18
+ TELEGRAM_URL = f"{TELEGRAM_DOMAIN}/bot{TELEGRAM_TOKEN}/sendMessage" if TELEGRAM_TOKEN and TELEGRAM_DOMAIN else None
19
 
20
  EMBED_MODEL = os.environ.get("EMBED_MODEL", "multilingual-e5-large")
21
  HF_MODEL = os.environ.get(
telegram_handlers.py CHANGED
@@ -1,11 +1,28 @@
1
- from fastapi import Request
2
  from pydantic import BaseModel
3
  import httpx
 
4
  from config import TELEGRAM_URL
5
  from ai_service import get_ai_response
6
  from database import db_manager
7
 
8
  TELEGRAM_IP = "149.154.167.220"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  class ChatInfo(BaseModel):
11
  id: int
@@ -35,42 +52,59 @@ async def telegram_webhook(data: WebhookData):
35
 
36
  if db_manager:
37
  db_manager.create_or_update_user(telegram_id, username, first_name, data.message.chat.last_name)
38
- db_manager.save_message(telegram_id, user_text, "user")
39
 
40
  ai_answer = await get_ai_response(user_text, telegram_id)
41
 
42
- if db_manager:
43
- db_manager.save_message(telegram_id, ai_answer, "assistant")
44
 
45
  if TELEGRAM_URL:
46
  try:
47
  from config import TELEGRAM_TOKEN
48
 
49
- async with httpx.AsyncClient(timeout=40.0, verify=False, follow_redirects=True) as client:
 
 
 
 
 
 
 
50
  payload = {
51
  "chat_id": telegram_id,
52
- "text": ai_answer,
53
- "parse_mode": "Markdown"
54
  }
55
-
56
- try:
57
- response = await client.post(TELEGRAM_URL, json=payload)
58
- except Exception as dns_err:
59
- print(f"--- DNS Failed. Forcing Direct IP Routing to 149.154.167.220 ---")
60
-
61
- forced_ip_url = f"https://149.154.167.220/bot{TELEGRAM_TOKEN}/sendMessage"
62
-
 
 
63
  headers = {
64
  "Host": "api.telegram.org",
65
- "Content-Type": "application/json"
 
66
  }
67
-
68
- response = await client.post(forced_ip_url, json=payload, headers=headers)
69
-
 
 
 
 
70
  if response.status_code == 200:
71
- print(f"--- Success: Message delivered via Direct IP Pipeline ---")
72
  else:
73
- print(f"--- Telegram Rejected Request: {response.status_code} - {response.text} ---")
 
 
 
 
 
74
 
75
  except Exception as send_error:
76
  print(f"--- Emergency: Network Blockage Detected: {str(send_error)} ---")
@@ -78,4 +112,4 @@ async def telegram_webhook(data: WebhookData):
78
  return {"status": "ok"}
79
  except Exception as e:
80
  print(f"Error in webhook: {str(e)}")
81
- return {"status": "error", "message": str(e)}
 
 
1
  from pydantic import BaseModel
2
  import httpx
3
+ import json
4
  from config import TELEGRAM_URL
5
  from ai_service import get_ai_response
6
  from database import db_manager
7
 
8
  TELEGRAM_IP = "149.154.167.220"
9
+ MAX_TELEGRAM_MESSAGE_LENGTH = 4096
10
+
11
+
12
+ def _sanitize_telegram_text(text: str) -> str:
13
+ if text is None:
14
+ return ""
15
+
16
+ normalized = str(text).replace("\r\n", "\n").replace("\r", "\n")
17
+
18
+ # Remove control/surrogate chars that Telegram can reject.
19
+ cleaned = "".join(
20
+ ch
21
+ for ch in normalized
22
+ if (ch in ("\n", "\t") or ord(ch) >= 32) and not (0xD800 <= ord(ch) <= 0xDFFF)
23
+ )
24
+ return cleaned.strip()
25
+
26
 
27
  class ChatInfo(BaseModel):
28
  id: int
 
52
 
53
  if db_manager:
54
  db_manager.create_or_update_user(telegram_id, username, first_name, data.message.chat.last_name)
55
+
56
 
57
  ai_answer = await get_ai_response(user_text, telegram_id)
58
 
59
+
 
60
 
61
  if TELEGRAM_URL:
62
  try:
63
  from config import TELEGRAM_TOKEN
64
 
65
+ async with httpx.AsyncClient(timeout=40.0, verify=False) as client:
66
+ prepared_text = _sanitize_telegram_text(
67
+ ai_answer or "Sorry, I couldn't generate a response. Please try again."
68
+ )
69
+ if not prepared_text:
70
+ prepared_text = "Sorry, I couldn't generate a response. Please try again."
71
+
72
+ final_text = prepared_text[:MAX_TELEGRAM_MESSAGE_LENGTH]
73
  payload = {
74
  "chat_id": telegram_id,
75
+ "text": final_text if final_text.strip() else ".",
 
76
  }
77
+
78
+ print(f"--- Sending Telegram message (chars={len(payload['text'])}) ---")
79
+
80
+ try:
81
+ response = await client.post(TELEGRAM_URL, data=payload)
82
+ except Exception:
83
+ print(f"--- DNS Failed. Forcing Direct IP Routing to {TELEGRAM_IP} ---")
84
+
85
+ forced_ip_url = f"https://{TELEGRAM_IP}/bot{TELEGRAM_TOKEN}/sendMessage"
86
+ json_body = json.dumps(payload, ensure_ascii=False).encode("utf-8")
87
  headers = {
88
  "Host": "api.telegram.org",
89
+ "Content-Type": "application/json; charset=utf-8",
90
+ "Content-Length": str(len(json_body)),
91
  }
92
+
93
+ response = await client.post(
94
+ forced_ip_url,
95
+ content=json_body,
96
+ headers=headers,
97
+ )
98
+
99
  if response.status_code == 200:
100
+ print("--- Success: Telegram message delivered ---")
101
  else:
102
+ print("--- Telegram payload rejected ---")
103
+ print(f"--- Payload: {payload} ---")
104
+ print(
105
+ f"--- Telegram Rejected Request: "
106
+ f"{response.status_code} - {response.text} ---"
107
+ )
108
 
109
  except Exception as send_error:
110
  print(f"--- Emergency: Network Blockage Detected: {str(send_error)} ---")
 
112
  return {"status": "ok"}
113
  except Exception as e:
114
  print(f"Error in webhook: {str(e)}")
115
+ return {"status": "error", "message": str(e)}