Spaces:
Sleeping
Sleeping
Refine Telegram DNS fallback to use explicit IP send URL
Browse filesIncrease 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
- 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 |
-
|
|
|
|
|
|
|
| 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
|
| 58 |
-
ip_url = TELEGRAM_URL.replace("api.telegram.org", TELEGRAM_IP)
|
| 59 |
-
headers = {"Host": "api.telegram.org"}
|
| 60 |
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
if response.status_code == 200:
|
| 64 |
-
print(f"--- Success: Message delivered
|
| 65 |
else:
|
| 66 |
-
print(f"--- Telegram
|
| 67 |
|
| 68 |
except Exception as send_error:
|
| 69 |
-
print(f"---
|
| 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:
|