codeBOKER commited on
Commit
7891d5f
·
1 Parent(s): 109d656

Refine Telegram DNS fallback to use explicit IP send URL

Browse files

Increase client timeout, build direct-IP sendMessage URL with token on DNS failure, and set Host/Content-Type headers for the fallback path.

Made-with: Cursor

Files changed (1) hide show
  1. telegram_handlers.py +15 -8
telegram_handlers.py CHANGED
@@ -44,7 +44,9 @@ async def telegram_webhook(data: WebhookData):
44
 
45
  if TELEGRAM_URL:
46
  try:
47
- async with httpx.AsyncClient(timeout=30.0, verify=False, follow_redirects=True) as client:
 
 
48
  payload = {
49
  "chat_id": telegram_id,
50
  "text": ai_answer,
@@ -54,19 +56,24 @@ async def telegram_webhook(data: WebhookData):
54
  try:
55
  response = await client.post(TELEGRAM_URL, json=payload)
56
  except Exception as dns_err:
57
- print(f"--- DNS Failed (Errno -5), trying direct IP routing... ---")
58
- ip_url = TELEGRAM_URL.replace("api.telegram.org", TELEGRAM_IP)
59
- headers = {"Host": "api.telegram.org"}
60
 
61
- response = await client.post(ip_url, json=payload, headers=headers)
 
 
 
 
 
 
 
62
 
63
  if response.status_code == 200:
64
- print(f"--- Success: Message delivered to {first_name} ---")
65
  else:
66
- print(f"--- Telegram Error: {response.status_code} - {response.text} ---")
67
 
68
  except Exception as send_error:
69
- print(f"--- Critical: All sending attempts failed: {str(send_error)} ---")
70
 
71
  return {"status": "ok"}
72
  except Exception as e:
 
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,
 
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)} ---")
77
 
78
  return {"status": "ok"}
79
  except Exception as e: