Spaces:
Running

axeronis commited on
Commit
ecc63ec
Β·
1 Parent(s): 2b2e573

Fix: Add robust DNS fallback (custom IP) for Telegram API calls on HF

Browse files
Files changed (1) hide show
  1. backend/app/services/telegram_service.py +125 -101
backend/app/services/telegram_service.py CHANGED
@@ -1,5 +1,6 @@
1
  import httpx
2
- from typing import Optional, Dict, Any
 
3
  from app.core.config import settings
4
  from app.core.logging import get_logger
5
 
@@ -8,11 +9,43 @@ logger = get_logger(__name__)
8
  class TelegramService:
9
  """
10
  Service for interacting with Telegram Bot API.
 
11
  """
12
 
 
 
13
  def __init__(self):
14
  self.base_url = "https://api.telegram.org/bot"
15
  self.token = settings.TELEGRAM_NOTIFICATION_TOKEN
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
  def _get_url(self, token: str, method: str) -> str:
18
  return f"{self.base_url}{token}/{method}"
@@ -33,9 +66,8 @@ class TelegramService:
33
  }
34
 
35
  try:
36
- async with httpx.AsyncClient(timeout=5.0) as client:
37
- response = await client.post(url, json=payload)
38
- return response.status_code == 200
39
  except Exception:
40
  return False
41
 
@@ -67,16 +99,15 @@ class TelegramService:
67
  payload["reply_to_message_id"] = reply_to_message_id
68
 
69
  try:
70
- async with httpx.AsyncClient() as client:
71
- response = await client.post(url, json=payload)
72
-
73
- if response.status_code == 200:
74
- data = response.json()
75
- message_id = data.get("result", {}).get("message_id")
76
- return {"success": True, "message_id": message_id}
77
- else:
78
- logger.error(f"Telegram sendMessage failed: {response.text}")
79
- return {"success": False, "message_id": None}
80
  except Exception as e:
81
  logger.error(f"Telegram API error: {e}")
82
  return {"success": False, "message_id": None}
@@ -113,17 +144,16 @@ class TelegramService:
113
  payload["reply_to_message_id"] = reply_to_message_id
114
 
115
  try:
116
- async with httpx.AsyncClient() as client:
117
- response = await client.post(url, json=payload)
118
 
119
- if response.status_code == 200:
120
- data = response.json()
121
- message_id = data.get("result", {}).get("message_id")
122
- logger.info(f"πŸ“· Photo sent to chat {chat_id}, message_id: {message_id}")
123
- return {"success": True, "message_id": message_id}
124
- else:
125
- logger.error(f"Telegram sendPhoto failed: {response.text}")
126
- return {"success": False, "message_id": None}
127
  except Exception as e:
128
  logger.error(f"Telegram sendPhoto error: {e}")
129
  return {"success": False, "message_id": None}
@@ -178,26 +208,25 @@ class TelegramService:
178
  }
179
 
180
  try:
181
- async with httpx.AsyncClient() as client:
182
- response = await client.post(url, data=payload)
183
 
184
- if response.status_code == 200:
185
- data = response.json()
186
- # Result is array of messages. Take the first one.
187
- messages = data.get("result", [])
188
- message_id = messages[0].get("message_id") if messages else None
189
- logger.info(f"πŸ“· Media group ({len(photo_urls)} photos) sent to chat {chat_id}, first msg_id: {message_id}")
190
- return {"success": True, "message_id": message_id}
191
- else:
192
- logger.error(f"Telegram sendMediaGroup failed: {response.text}")
193
- # Fallback: send photos individually
194
- last_msg_id = None
195
- for idx, photo_url in enumerate(photo_urls):
196
- cap = caption if idx == 0 else None
197
- res = await self.send_photo(token, chat_id, photo_url, cap)
198
- if res["success"]:
199
- last_msg_id = res["message_id"]
200
- return {"success": True, "message_id": last_msg_id}
201
  except Exception as e:
202
  logger.error(f"Telegram sendMediaGroup error: {e}")
203
  return {"success": False, "message_id": None}
@@ -210,9 +239,8 @@ class TelegramService:
210
  payload = {"url": webhook_url}
211
 
212
  try:
213
- async with httpx.AsyncClient() as client:
214
- response = await client.post(url, json=payload)
215
- return response.status_code == 200
216
  except Exception as e:
217
  logger.error(f"Telegram setWebhook error: {e}")
218
  return False
@@ -236,17 +264,16 @@ class TelegramService:
236
  payload["caption"] = caption[:1024]
237
 
238
  try:
239
- async with httpx.AsyncClient(timeout=60.0) as client:
240
- response = await client.post(url, json=payload)
241
 
242
- if response.status_code == 200:
243
- data = response.json()
244
- message_id = data.get("result", {}).get("message_id")
245
- logger.info(f"🎬 Video sent to chat {chat_id}")
246
- return {"success": True, "message_id": message_id}
247
- else:
248
- logger.error(f"Telegram sendVideo failed: {response.text}")
249
- return {"success": False, "message_id": None}
250
  except Exception as e:
251
  logger.error(f"Telegram sendVideo error: {e}")
252
  return {"success": False, "message_id": None}
@@ -270,17 +297,16 @@ class TelegramService:
270
  payload["caption"] = caption[:1024]
271
 
272
  try:
273
- async with httpx.AsyncClient(timeout=60.0) as client:
274
- response = await client.post(url, json=payload)
275
 
276
- if response.status_code == 200:
277
- data = response.json()
278
- message_id = data.get("result", {}).get("message_id")
279
- logger.info(f"πŸ“„ Document sent to chat {chat_id}")
280
- return {"success": True, "message_id": message_id}
281
- else:
282
- logger.error(f"Telegram sendDocument failed: {response.text}")
283
- return {"success": False, "message_id": None}
284
  except Exception as e:
285
  logger.error(f"Telegram sendDocument error: {e}")
286
  return {"success": False, "message_id": None}
@@ -325,28 +351,27 @@ class TelegramService:
325
  url = self._get_url(token, "sendVoice")
326
 
327
  try:
328
- async with httpx.AsyncClient(timeout=30.0) as client:
329
- # Send as voice message (OGG format)
330
- files = {"voice": ("voice.ogg", ogg_bytes, "audio/ogg")}
331
- data = {"chat_id": chat_id}
332
-
333
- if caption:
334
- data["caption"] = caption[:1024]
335
-
336
- if reply_to_message_id:
337
- data["reply_to_message_id"] = reply_to_message_id
338
-
339
- response = await client.post(url, files=files, data=data)
340
-
341
- if response.status_code == 200:
342
- data = response.json()
343
- message_id = data.get("result", {}).get("message_id")
344
- logger.info(f"🎀 Voice message sent to chat {chat_id}")
345
- return {"success": True, "message_id": message_id}
346
- else:
347
- logger.error(f"Telegram sendVoice failed: {response.text}")
348
- # Fallback to audio
349
- return await self._send_audio_fallback(token, chat_id, audio_bytes, reply_to_message_id)
350
  except Exception as e:
351
  logger.error(f"Telegram sendVoice error: {e}")
352
  return {"success": False, "message_id": None}
@@ -355,20 +380,19 @@ class TelegramService:
355
  """Fallback: send as audio file if voice fails."""
356
  url = self._get_url(token, "sendAudio")
357
  try:
358
- async with httpx.AsyncClient(timeout=30.0) as client:
359
- files = {"audio": ("voice.mp3", audio_bytes, "audio/mpeg")}
360
- data = {"chat_id": chat_id}
361
- if reply_to_message_id:
362
- data["reply_to_message_id"] = reply_to_message_id
363
-
364
- response = await client.post(url, files=files, data=data)
365
 
366
- if response.status_code == 200:
367
- data = response.json()
368
- message_id = data.get("result", {}).get("message_id")
369
- logger.info(f"🎡 Audio fallback sent to chat {chat_id}")
370
- return {"success": True, "message_id": message_id}
371
- return {"success": False, "message_id": None}
 
 
372
  except:
373
  return {"success": False, "message_id": None}
374
 
 
1
  import httpx
2
+ import socket
3
+ from typing import Optional, Dict, Any, Union
4
  from app.core.config import settings
5
  from app.core.logging import get_logger
6
 
 
9
  class TelegramService:
10
  """
11
  Service for interacting with Telegram Bot API.
12
+ Includes DNS fallback for Hugging Face Spaces issues.
13
  """
14
 
15
+ TELEGRAM_API_IP = "149.154.167.220" # Hardcoded backup IP for api.telegram.org
16
+
17
  def __init__(self):
18
  self.base_url = "https://api.telegram.org/bot"
19
  self.token = settings.TELEGRAM_NOTIFICATION_TOKEN
20
+
21
+ async def _make_request(self, method: str, url: str, **kwargs) -> httpx.Response:
22
+ """
23
+ Wrapper for httpx requests with DNS fallback.
24
+ If hostname resolution fails, tries replacing hostname with hardcoded IP.
25
+ """
26
+ try:
27
+ async with httpx.AsyncClient(timeout=30.0) as client:
28
+ if method.lower() == 'get':
29
+ return await client.get(url, **kwargs)
30
+ else:
31
+ return await client.post(url, **kwargs)
32
+ except (httpx.ConnectError, OSError) as e:
33
+ if "No address associated with hostname" in str(e) or "[Errno -5]" in str(e):
34
+ logger.warning(f"⚠️ DNS failure for {url}. Switching to direct IP fallback.")
35
+ # Replace hostname with IP
36
+ fallback_url = url.replace("api.telegram.org", self.TELEGRAM_API_IP)
37
+ # We must disable SSL verification for IP-based requests OR provide the hostname in headers
38
+ headers = kwargs.get("headers", {})
39
+ headers["Host"] = "api.telegram.org"
40
+ kwargs["headers"] = headers
41
+
42
+ # Note: verify=False is needed because certificate mismatch (IP vs valid domain)
43
+ async with httpx.AsyncClient(timeout=30.0, verify=False) as client:
44
+ if method.lower() == 'get':
45
+ return await client.get(fallback_url, **kwargs)
46
+ else:
47
+ return await client.post(fallback_url, **kwargs)
48
+ raise e
49
 
50
  def _get_url(self, token: str, method: str) -> str:
51
  return f"{self.base_url}{token}/{method}"
 
66
  }
67
 
68
  try:
69
+ response = await self._make_request("POST", url, json=payload)
70
+ return response.status_code == 200
 
71
  except Exception:
72
  return False
73
 
 
99
  payload["reply_to_message_id"] = reply_to_message_id
100
 
101
  try:
102
+ response = await self._make_request("POST", url, json=payload)
103
+
104
+ if response.status_code == 200:
105
+ data = response.json()
106
+ message_id = data.get("result", {}).get("message_id")
107
+ return {"success": True, "message_id": message_id}
108
+ else:
109
+ logger.error(f"Telegram sendMessage failed: {response.text}")
110
+ return {"success": False, "message_id": None}
 
111
  except Exception as e:
112
  logger.error(f"Telegram API error: {e}")
113
  return {"success": False, "message_id": None}
 
144
  payload["reply_to_message_id"] = reply_to_message_id
145
 
146
  try:
147
+ response = await self._make_request("POST", url, json=payload)
 
148
 
149
+ if response.status_code == 200:
150
+ data = response.json()
151
+ message_id = data.get("result", {}).get("message_id")
152
+ logger.info(f"πŸ“· Photo sent to chat {chat_id}, message_id: {message_id}")
153
+ return {"success": True, "message_id": message_id}
154
+ else:
155
+ logger.error(f"Telegram sendPhoto failed: {response.text}")
156
+ return {"success": False, "message_id": None}
157
  except Exception as e:
158
  logger.error(f"Telegram sendPhoto error: {e}")
159
  return {"success": False, "message_id": None}
 
208
  }
209
 
210
  try:
211
+ response = await self._make_request("POST", url, data=payload)
 
212
 
213
+ if response.status_code == 200:
214
+ data = response.json()
215
+ # Result is array of messages. Take the first one.
216
+ messages = data.get("result", [])
217
+ message_id = messages[0].get("message_id") if messages else None
218
+ logger.info(f"πŸ“· Media group ({len(photo_urls)} photos) sent to chat {chat_id}, first msg_id: {message_id}")
219
+ return {"success": True, "message_id": message_id}
220
+ else:
221
+ logger.error(f"Telegram sendMediaGroup failed: {response.text}")
222
+ # Fallback: send photos individually
223
+ last_msg_id = None
224
+ for idx, photo_url in enumerate(photo_urls):
225
+ cap = caption if idx == 0 else None
226
+ res = await self.send_photo(token, chat_id, photo_url, cap)
227
+ if res["success"]:
228
+ last_msg_id = res["message_id"]
229
+ return {"success": True, "message_id": last_msg_id}
230
  except Exception as e:
231
  logger.error(f"Telegram sendMediaGroup error: {e}")
232
  return {"success": False, "message_id": None}
 
239
  payload = {"url": webhook_url}
240
 
241
  try:
242
+ response = await self._make_request("POST", url, json=payload)
243
+ return response.status_code == 200
 
244
  except Exception as e:
245
  logger.error(f"Telegram setWebhook error: {e}")
246
  return False
 
264
  payload["caption"] = caption[:1024]
265
 
266
  try:
267
+ response = await self._make_request("POST", url, json=payload)
 
268
 
269
+ if response.status_code == 200:
270
+ data = response.json()
271
+ message_id = data.get("result", {}).get("message_id")
272
+ logger.info(f"🎬 Video sent to chat {chat_id}")
273
+ return {"success": True, "message_id": message_id}
274
+ else:
275
+ logger.error(f"Telegram sendVideo failed: {response.text}")
276
+ return {"success": False, "message_id": None}
277
  except Exception as e:
278
  logger.error(f"Telegram sendVideo error: {e}")
279
  return {"success": False, "message_id": None}
 
297
  payload["caption"] = caption[:1024]
298
 
299
  try:
300
+ response = await self._make_request("POST", url, json=payload)
 
301
 
302
+ if response.status_code == 200:
303
+ data = response.json()
304
+ message_id = data.get("result", {}).get("message_id")
305
+ logger.info(f"πŸ“„ Document sent to chat {chat_id}")
306
+ return {"success": True, "message_id": message_id}
307
+ else:
308
+ logger.error(f"Telegram sendDocument failed: {response.text}")
309
+ return {"success": False, "message_id": None}
310
  except Exception as e:
311
  logger.error(f"Telegram sendDocument error: {e}")
312
  return {"success": False, "message_id": None}
 
351
  url = self._get_url(token, "sendVoice")
352
 
353
  try:
354
+ # Send as voice message (OGG format)
355
+ files = {"voice": ("voice.ogg", ogg_bytes, "audio/ogg")}
356
+ data = {"chat_id": chat_id}
357
+
358
+ if caption:
359
+ data["caption"] = caption[:1024]
360
+
361
+ if reply_to_message_id:
362
+ data["reply_to_message_id"] = reply_to_message_id
363
+
364
+ response = await self._make_request("POST", url, files=files, data=data)
365
+
366
+ if response.status_code == 200:
367
+ data = response.json()
368
+ message_id = data.get("result", {}).get("message_id")
369
+ logger.info(f"🎀 Voice message sent to chat {chat_id}")
370
+ return {"success": True, "message_id": message_id}
371
+ else:
372
+ logger.error(f"Telegram sendVoice failed: {response.text}")
373
+ # Fallback to audio
374
+ return await self._send_audio_fallback(token, chat_id, audio_bytes, reply_to_message_id)
 
375
  except Exception as e:
376
  logger.error(f"Telegram sendVoice error: {e}")
377
  return {"success": False, "message_id": None}
 
380
  """Fallback: send as audio file if voice fails."""
381
  url = self._get_url(token, "sendAudio")
382
  try:
383
+ files = {"audio": ("voice.mp3", audio_bytes, "audio/mpeg")}
384
+ data = {"chat_id": chat_id}
385
+ if reply_to_message_id:
386
+ data["reply_to_message_id"] = reply_to_message_id
 
 
 
387
 
388
+ response = await self._make_request("POST", url, files=files, data=data)
389
+
390
+ if response.status_code == 200:
391
+ data = response.json()
392
+ message_id = data.get("result", {}).get("message_id")
393
+ logger.info(f"🎡 Audio fallback sent to chat {chat_id}")
394
+ return {"success": True, "message_id": message_id}
395
+ return {"success": False, "message_id": None}
396
  except:
397
  return {"success": False, "message_id": None}
398