telegram_service.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  1. import asyncio
  2. from contextlib import asynccontextmanager
  3. from datetime import datetime
  4. from enum import Enum
  5. from functools import wraps
  6. from typing import Any, Optional
  7. from urllib.parse import urlparse
  8. from loguru import logger
  9. from telethon import TelegramClient, errors
  10. from telethon.tl.types import InputPeerUser, User
  11. def parse_http_proxy_url(proxy_url: str) -> dict[str, Any] | None:
  12. """
  13. Convert HTTP proxy URL to Telethon proxy dict
  14. Args:
  15. proxy_url: HTTP proxy URL (http://user:pass@host:port or http://host:port)
  16. Returns:
  17. Dict compatible with Telethon proxy format, or None if invalid
  18. Example:
  19. "http://proxy.example.com:8080" -> {
  20. "proxy_type": "http",
  21. "addr": "proxy.example.com",
  22. "port": 8080
  23. }
  24. "http://user:pass@proxy.example.com:8080" -> {
  25. "proxy_type": "http",
  26. "addr": "proxy.example.com",
  27. "port": 8080,
  28. "username": "user",
  29. "password": "pass"
  30. }
  31. """
  32. if not proxy_url or not proxy_url.strip():
  33. return None
  34. try:
  35. parsed = urlparse(proxy_url.strip())
  36. # Only accept HTTP proxies
  37. if parsed.scheme.lower() != "http":
  38. logger.warning(f"Unsupported proxy scheme '{parsed.scheme}': {proxy_url}")
  39. return None
  40. if not parsed.hostname or not parsed.port:
  41. logger.warning(f"Invalid proxy URL format: {proxy_url}")
  42. return None
  43. proxy_dict = {
  44. "proxy_type": "http",
  45. "addr": parsed.hostname,
  46. "port": parsed.port,
  47. }
  48. # Add authentication if present
  49. if parsed.username:
  50. proxy_dict["username"] = parsed.username
  51. if parsed.password:
  52. proxy_dict["password"] = parsed.password
  53. logger.debug(f"Parsed proxy: {proxy_dict}")
  54. return proxy_dict
  55. except Exception as e:
  56. logger.error(f"Failed to parse proxy URL '{proxy_url}': {e}")
  57. return None
  58. class NotificationPriority(Enum):
  59. LOW = "🔵"
  60. NORMAL = "ℹ️"
  61. HIGH = "⚠️"
  62. CRITICAL = "🚨"
  63. class TelegramNotificationError(Exception):
  64. """Base exception for Telegram notification errors"""
  65. pass
  66. class TelegramConnectionError(TelegramNotificationError):
  67. """Raised when connection to Telegram fails"""
  68. pass
  69. class TelegramSendError(TelegramNotificationError):
  70. """Raised when sending message fails"""
  71. pass
  72. def async_retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0):
  73. def decorator(func):
  74. @wraps(func)
  75. async def wrapper(*args, **kwargs):
  76. current_delay = delay
  77. last_exception = None
  78. for attempt in range(max_attempts):
  79. try:
  80. return await func(*args, **kwargs)
  81. except (errors.FloodWaitError, errors.SlowModeWaitError) as e:
  82. wait_time = e.seconds if hasattr(e, "seconds") else current_delay
  83. logger.warning(
  84. f"Rate limited, waiting {wait_time}s (attempt {attempt + 1}/{max_attempts})"
  85. )
  86. await asyncio.sleep(wait_time)
  87. last_exception = e
  88. except Exception as e:
  89. logger.warning(
  90. f"Error on attempt {attempt + 1}/{max_attempts}: {e}"
  91. )
  92. if attempt < max_attempts - 1:
  93. await asyncio.sleep(current_delay)
  94. current_delay *= backoff
  95. last_exception = e
  96. break
  97. raise TelegramSendError(
  98. f"Failed after {max_attempts} attempts"
  99. ) from last_exception
  100. return wrapper
  101. return decorator
  102. class TelegramService:
  103. _instance: Optional["TelegramService"] = None
  104. _lock = asyncio.Lock()
  105. def __new__(cls, *args, **kwargs):
  106. if cls._instance is None:
  107. cls._instance = super().__new__(cls)
  108. cls._instance._initialized = False
  109. return cls._instance
  110. def __init__(
  111. self,
  112. api_id: int,
  113. api_hash: str,
  114. bot_token: str | None = None,
  115. session_name: str = "squidstats_bot",
  116. phone: str | None = None,
  117. enabled: bool = True,
  118. proxy: dict[str, Any] | None = None,
  119. ):
  120. if self._initialized:
  121. return
  122. self.api_id = api_id
  123. self.api_hash = api_hash
  124. self.bot_token = bot_token
  125. self.session_name = session_name
  126. self.phone = phone
  127. self.enabled = enabled
  128. self.proxy = proxy
  129. self._client: TelegramClient | None = None
  130. self._connected = False
  131. self._event_loop: asyncio.AbstractEventLoop | None = None
  132. self._recipients: dict[str, InputPeerUser] = {}
  133. self._initialized = True
  134. logger.info("TelegramService initialized")
  135. async def _ensure_connected(self) -> None:
  136. """Ensure client is connected, connect if necessary"""
  137. if not self.enabled:
  138. raise TelegramNotificationError("Telegram notifications are disabled")
  139. if self._client and self._connected:
  140. try:
  141. await self._client.get_me()
  142. return
  143. except Exception as e:
  144. logger.warning(f"Connection check failed: {e}")
  145. self._connected = False
  146. await self.connect()
  147. async def connect(self) -> None:
  148. """Establish connection to Telegram"""
  149. if not self.enabled:
  150. logger.info("Telegram notifications disabled, skipping connection")
  151. return
  152. async with self._lock:
  153. try:
  154. if self._client:
  155. try:
  156. await self._client.disconnect()
  157. except Exception:
  158. pass
  159. self._client = TelegramClient(
  160. self.session_name, self.api_id, self.api_hash, proxy=self.proxy
  161. )
  162. await self._client.connect()
  163. if self.bot_token:
  164. # Bot mode
  165. await self._client.sign_in(bot_token=self.bot_token)
  166. logger.info("Connected to Telegram as bot")
  167. elif self.phone:
  168. # User mode
  169. if not await self._client.is_user_authorized():
  170. await self._client.send_code_request(self.phone)
  171. logger.warning(
  172. "Authorization required. Check your Telegram for code."
  173. )
  174. else:
  175. logger.info("Connected to Telegram as user")
  176. else:
  177. # Try to use existing session
  178. if not await self._client.is_user_authorized():
  179. raise TelegramConnectionError(
  180. "No bot_token or phone provided and no valid session exists"
  181. )
  182. logger.info("Connected using existing session")
  183. self._connected = True
  184. except errors.ApiIdInvalidError:
  185. raise TelegramConnectionError("Invalid API ID or Hash")
  186. except errors.PhoneNumberInvalidError:
  187. raise TelegramConnectionError("Invalid phone number")
  188. except Exception as e:
  189. self._connected = False
  190. raise TelegramConnectionError(f"Failed to connect: {e}") from e
  191. async def disconnect(self) -> None:
  192. """Disconnect from Telegram"""
  193. if self._client:
  194. try:
  195. await self._client.disconnect()
  196. self._connected = False
  197. logger.info("Disconnected from Telegram")
  198. except Exception as e:
  199. logger.error(f"Error disconnecting: {e}")
  200. @asynccontextmanager
  201. async def session(self):
  202. """Context manager for Telegram session"""
  203. await self._ensure_connected()
  204. try:
  205. yield self._client
  206. except Exception as e:
  207. logger.error(f"Error in Telegram session: {e}")
  208. raise
  209. def _format_message(
  210. self,
  211. message: str,
  212. priority: NotificationPriority = NotificationPriority.NORMAL,
  213. source: str = "SquidStats",
  214. timestamp: bool = True,
  215. extra_data: dict[str, Any] | None = None,
  216. ) -> str:
  217. parts = [f"{priority.value} **{source}**\n"]
  218. if timestamp:
  219. time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  220. parts.append(f"🕐 {time_str}\n")
  221. parts.append(f"\n{message}")
  222. if extra_data:
  223. parts.append("\n\n📊 **Detalles:**")
  224. for key, value in extra_data.items():
  225. parts.append(f"\n• {key}: `{value}`")
  226. return "".join(parts)
  227. async def _resolve_recipient(self, recipient: str | int) -> InputPeerUser | int:
  228. if isinstance(recipient, int):
  229. return recipient
  230. # Check cache
  231. if recipient in self._recipients:
  232. return self._recipients[recipient]
  233. # Resolve entity
  234. try:
  235. async with self.session() as client:
  236. # Convert channel IDs to int for better resolution
  237. resolve_target = recipient
  238. if isinstance(recipient, str) and recipient.startswith("-100"):
  239. resolve_target = int(recipient)
  240. entity = await client.get_entity(resolve_target)
  241. if isinstance(entity, User):
  242. self._recipients[recipient] = entity
  243. return entity
  244. except Exception as e:
  245. logger.error(f"Failed to resolve recipient {recipient}: {e}")
  246. raise TelegramSendError(f"Invalid recipient: {recipient}") from e
  247. @async_retry(max_attempts=3, delay=1.0, backoff=2.0)
  248. async def send_notification(
  249. self,
  250. recipient: str | int,
  251. message: str,
  252. priority: NotificationPriority = NotificationPriority.NORMAL,
  253. source: str = "SquidStats",
  254. parse_mode: str = "md",
  255. **kwargs,
  256. ) -> bool:
  257. if not self.enabled:
  258. logger.debug("Telegram notifications disabled")
  259. return False
  260. try:
  261. formatted_message = self._format_message(
  262. message, priority=priority, source=source, **kwargs
  263. )
  264. entity = await self._resolve_recipient(recipient)
  265. async with self.session() as client:
  266. await client.send_message(
  267. entity, formatted_message, parse_mode=parse_mode
  268. )
  269. logger.info(f"Notification sent to {recipient}")
  270. return True
  271. except TelegramSendError:
  272. raise
  273. except Exception as e:
  274. logger.error(f"Failed to send notification: {e}")
  275. raise TelegramSendError(f"Send failed: {e}") from e
  276. async def send_bulk_notifications(
  277. self,
  278. recipients: list[str | int],
  279. message: str,
  280. priority: NotificationPriority = NotificationPriority.NORMAL,
  281. **kwargs,
  282. ) -> dict[str, bool]:
  283. results = {}
  284. for recipient in recipients:
  285. try:
  286. success = await self.send_notification(
  287. recipient, message, priority=priority, **kwargs
  288. )
  289. results[str(recipient)] = success
  290. except Exception as e:
  291. logger.error(f"Failed to send to {recipient}: {e}")
  292. results[str(recipient)] = False
  293. return results
  294. async def send_security_alert(
  295. self, recipient: str | int, alert_type: str, details: dict[str, Any]
  296. ) -> bool:
  297. message = f"🔐 **Alerta de Seguridad: {alert_type}**"
  298. return await self.send_notification(
  299. recipient,
  300. message,
  301. priority=NotificationPriority.CRITICAL,
  302. source="Security Monitor",
  303. extra_data=details,
  304. )
  305. async def send_system_alert(
  306. self,
  307. recipient: str | int,
  308. alert_message: str,
  309. metrics: dict[str, Any] | None = None,
  310. ) -> bool:
  311. return await self.send_notification(
  312. recipient,
  313. alert_message,
  314. priority=NotificationPriority.HIGH,
  315. source="System Monitor",
  316. extra_data=metrics,
  317. )
  318. async def send_user_activity_alert(
  319. self, recipient: str | int, username: str, activity_data: dict[str, Any]
  320. ) -> bool:
  321. message = f"👤 **Alta actividad detectada: {username}**"
  322. return await self.send_notification(
  323. recipient,
  324. message,
  325. priority=NotificationPriority.HIGH,
  326. source="User Monitor",
  327. extra_data=activity_data,
  328. )
  329. async def health_check(self) -> dict[str, Any]:
  330. status = {
  331. "enabled": self.enabled,
  332. "connected": False,
  333. "bot_mode": bool(self.bot_token),
  334. "session": self.session_name,
  335. "error": None,
  336. }
  337. if not self.enabled:
  338. return status
  339. try:
  340. await self._ensure_connected()
  341. async with self.session() as client:
  342. me = await client.get_me()
  343. status["connected"] = True
  344. status["user_id"] = me.id
  345. status["username"] = getattr(me, "username", None)
  346. except Exception:
  347. logger.exception("Health check failed")
  348. status["error"] = "Health check failed"
  349. return status
  350. def __del__(self):
  351. """Cleanup on deletion"""
  352. if self._client and self._connected:
  353. try:
  354. # Try to disconnect gracefully
  355. if self._event_loop and self._event_loop.is_running():
  356. asyncio.create_task(self.disconnect())
  357. except Exception:
  358. pass
  359. # Singleton instance
  360. _telegram_service: TelegramService | None = None
  361. def get_telegram_service(
  362. api_id: int | None = None,
  363. api_hash: str | None = None,
  364. proxy: dict[str, Any] | None = None,
  365. **kwargs,
  366. ) -> TelegramService:
  367. """
  368. Get or create TelegramService singleton instance
  369. Args:
  370. api_id: Telegram API ID (required on first call)
  371. api_hash: Telegram API Hash (required on first call)
  372. proxy: Proxy configuration dict for Telethon
  373. **kwargs: Additional parameters for TelegramService
  374. Returns:
  375. TelegramService instance
  376. """
  377. global _telegram_service
  378. if _telegram_service is None:
  379. if api_id is None or api_hash is None:
  380. raise ValueError("api_id and api_hash required for first initialization")
  381. _telegram_service = TelegramService(
  382. api_id=api_id, api_hash=api_hash, proxy=proxy, **kwargs
  383. )
  384. return _telegram_service
  385. async def cleanup_telegram_service():
  386. """Cleanup Telegram service on shutdown"""
  387. global _telegram_service
  388. if _telegram_service:
  389. await _telegram_service.disconnect()
  390. _telegram_service = None
  391. logger.info("Telegram service cleaned up")