telegram_service.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. _session_lock = asyncio.Lock()
  106. def __new__(cls, *args, **kwargs):
  107. if cls._instance is None:
  108. cls._instance = super().__new__(cls)
  109. cls._instance._initialized = False
  110. return cls._instance
  111. def __init__(
  112. self,
  113. api_id: int,
  114. api_hash: str,
  115. bot_token: str | None = None,
  116. session_name: str = "squidstats_bot",
  117. phone: str | None = None,
  118. enabled: bool = True,
  119. proxy: dict[str, Any] | None = None,
  120. ):
  121. if self._initialized:
  122. return
  123. self.api_id = api_id
  124. self.api_hash = api_hash
  125. self.bot_token = bot_token
  126. self.session_name = session_name
  127. self.phone = phone
  128. self.enabled = enabled
  129. self.proxy = proxy
  130. self._client: TelegramClient | None = None
  131. self._connected = False
  132. self._event_loop: asyncio.AbstractEventLoop | None = None
  133. self._recipients: dict[str, InputPeerUser] = {}
  134. self._initialized = True
  135. logger.info("TelegramService initialized")
  136. async def _ensure_connected(self) -> None:
  137. """Ensure client is connected, connect if necessary"""
  138. if not self.enabled:
  139. raise TelegramNotificationError("Telegram notifications are disabled")
  140. if self._client and self._connected:
  141. try:
  142. await self._client.get_me()
  143. return
  144. except Exception as e:
  145. logger.warning(f"Connection check failed: {e}")
  146. self._connected = False
  147. await self.connect()
  148. async def connect(self) -> None:
  149. """Establish connection to Telegram"""
  150. if not self.enabled:
  151. logger.info("Telegram notifications disabled, skipping connection")
  152. return
  153. async with self._lock:
  154. try:
  155. if self._client:
  156. try:
  157. await self._client.disconnect()
  158. except Exception as e:
  159. logger.debug(
  160. "Error disconnecting previous Telegram client: %s", e
  161. )
  162. self._client = TelegramClient(
  163. self.session_name, self.api_id, self.api_hash, proxy=self.proxy
  164. )
  165. await self._client.connect()
  166. if self.bot_token:
  167. # Bot mode
  168. await self._client.sign_in(bot_token=self.bot_token)
  169. logger.info("Connected to Telegram as bot")
  170. elif self.phone:
  171. # User mode
  172. if not await self._client.is_user_authorized():
  173. await self._client.send_code_request(self.phone)
  174. logger.warning(
  175. "Authorization required. Check your Telegram for code."
  176. )
  177. else:
  178. logger.info("Connected to Telegram as user")
  179. else:
  180. # Try to use existing session
  181. if not await self._client.is_user_authorized():
  182. raise TelegramConnectionError(
  183. "No bot_token or phone provided and no valid session exists"
  184. )
  185. logger.info("Connected using existing session")
  186. self._connected = True
  187. except errors.ApiIdInvalidError:
  188. raise TelegramConnectionError("Invalid API ID or Hash")
  189. except errors.PhoneNumberInvalidError:
  190. raise TelegramConnectionError("Invalid phone number")
  191. except Exception as e:
  192. self._connected = False
  193. raise TelegramConnectionError(f"Failed to connect: {e}") from e
  194. async def disconnect(self) -> None:
  195. """Disconnect from Telegram"""
  196. if self._client:
  197. try:
  198. await self._client.disconnect()
  199. self._connected = False
  200. logger.info("Disconnected from Telegram")
  201. except Exception as e:
  202. logger.error(f"Error disconnecting: {e}")
  203. @asynccontextmanager
  204. async def session(self):
  205. """Context manager for Telegram session"""
  206. await self._ensure_connected()
  207. async with self._session_lock:
  208. try:
  209. yield self._client
  210. except Exception as e:
  211. logger.error(f"Error in Telegram session: {e}")
  212. raise
  213. def _format_message(
  214. self,
  215. message: str,
  216. priority: NotificationPriority = NotificationPriority.NORMAL,
  217. source: str = "SquidStats",
  218. timestamp: bool = True,
  219. extra_data: dict[str, Any] | None = None,
  220. ) -> str:
  221. parts = [f"{priority.value} **{source}**\n"]
  222. if timestamp:
  223. time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
  224. parts.append(f"🕐 {time_str}\n")
  225. parts.append(f"\n{message}")
  226. if extra_data:
  227. parts.append("\n\n📊 **Detalles:**")
  228. for key, value in extra_data.items():
  229. parts.append(f"\n• {key}: `{value}`")
  230. return "".join(parts)
  231. async def _resolve_recipient(self, recipient: str | int) -> InputPeerUser | int:
  232. if isinstance(recipient, int):
  233. return recipient
  234. # In bot mode, Telegram does not allow resolving phone numbers.
  235. # Only integer user/chat IDs or @username strings are valid.
  236. if self.bot_token and recipient.startswith("+"):
  237. raise TelegramSendError(
  238. f"Bot mode does not support phone-number recipients. "
  239. f"Use the integer chat/user ID instead of '{recipient}'."
  240. )
  241. # Check cache
  242. if recipient in self._recipients:
  243. return self._recipients[recipient]
  244. # Resolve entity
  245. try:
  246. async with self.session() as client:
  247. # Convert channel IDs to int for better resolution
  248. resolve_target = recipient
  249. if isinstance(recipient, str) and recipient.startswith("-100"):
  250. resolve_target = int(recipient)
  251. entity = await client.get_entity(resolve_target)
  252. if isinstance(entity, User):
  253. self._recipients[recipient] = entity
  254. return entity
  255. except Exception as e:
  256. logger.error(f"Failed to resolve recipient {recipient}: {e}")
  257. raise TelegramSendError(f"Invalid recipient: {recipient}") from e
  258. @async_retry(max_attempts=3, delay=1.0, backoff=2.0)
  259. async def send_notification(
  260. self,
  261. recipient: str | int,
  262. message: str,
  263. priority: NotificationPriority = NotificationPriority.NORMAL,
  264. source: str = "SquidStats",
  265. parse_mode: str = "md",
  266. **kwargs,
  267. ) -> bool:
  268. if not self.enabled:
  269. logger.debug("Telegram notifications disabled")
  270. return False
  271. try:
  272. formatted_message = self._format_message(
  273. message, priority=priority, source=source, **kwargs
  274. )
  275. entity = await self._resolve_recipient(recipient)
  276. async with self.session() as client:
  277. await client.send_message(
  278. entity, formatted_message, parse_mode=parse_mode
  279. )
  280. logger.info(f"Notification sent to {recipient}")
  281. return True
  282. except TelegramSendError:
  283. raise
  284. except Exception as e:
  285. logger.error(f"Failed to send notification: {e}")
  286. raise TelegramSendError(f"Send failed: {e}") from e
  287. async def send_bulk_notifications(
  288. self,
  289. recipients: list[str | int],
  290. message: str,
  291. priority: NotificationPriority = NotificationPriority.NORMAL,
  292. **kwargs,
  293. ) -> dict[str, bool]:
  294. results = {}
  295. for recipient in recipients:
  296. try:
  297. success = await self.send_notification(
  298. recipient, message, priority=priority, **kwargs
  299. )
  300. results[str(recipient)] = success
  301. except Exception as e:
  302. logger.error(f"Failed to send to {recipient}: {e}")
  303. results[str(recipient)] = False
  304. return results
  305. async def send_security_alert(
  306. self, recipient: str | int, alert_type: str, details: dict[str, Any]
  307. ) -> bool:
  308. message = f"🔐 **Alerta de Seguridad: {alert_type}**"
  309. return await self.send_notification(
  310. recipient,
  311. message,
  312. priority=NotificationPriority.CRITICAL,
  313. source="Security Monitor",
  314. extra_data=details,
  315. )
  316. async def send_system_alert(
  317. self,
  318. recipient: str | int,
  319. alert_message: str,
  320. metrics: dict[str, Any] | None = None,
  321. ) -> bool:
  322. return await self.send_notification(
  323. recipient,
  324. alert_message,
  325. priority=NotificationPriority.HIGH,
  326. source="System Monitor",
  327. extra_data=metrics,
  328. )
  329. async def send_user_activity_alert(
  330. self, recipient: str | int, username: str, activity_data: dict[str, Any]
  331. ) -> bool:
  332. message = f"👤 **Alta actividad detectada: {username}**"
  333. return await self.send_notification(
  334. recipient,
  335. message,
  336. priority=NotificationPriority.HIGH,
  337. source="User Monitor",
  338. extra_data=activity_data,
  339. )
  340. async def health_check(self) -> dict[str, Any]:
  341. status = {
  342. "enabled": self.enabled,
  343. "connected": False,
  344. "bot_mode": bool(self.bot_token),
  345. "session": self.session_name,
  346. "error": None,
  347. }
  348. if not self.enabled:
  349. return status
  350. try:
  351. await self._ensure_connected()
  352. async with self.session() as client:
  353. me = await client.get_me()
  354. status["connected"] = True
  355. status["user_id"] = me.id
  356. status["username"] = getattr(me, "username", None)
  357. except Exception:
  358. logger.exception("Health check failed")
  359. status["error"] = "Health check failed"
  360. return status
  361. def __del__(self):
  362. """Cleanup on deletion"""
  363. if self._client and self._connected:
  364. try:
  365. # Try to disconnect gracefully
  366. if self._event_loop and self._event_loop.is_running():
  367. asyncio.create_task(self.disconnect())
  368. except Exception as e:
  369. logger.debug("Error scheduling disconnect in __del__: %s", e)
  370. # Singleton instance
  371. _telegram_service: TelegramService | None = None
  372. def get_telegram_service(
  373. api_id: int | None = None,
  374. api_hash: str | None = None,
  375. proxy: dict[str, Any] | None = None,
  376. **kwargs,
  377. ) -> TelegramService:
  378. """
  379. Get or create TelegramService singleton instance
  380. Args:
  381. api_id: Telegram API ID (required on first call)
  382. api_hash: Telegram API Hash (required on first call)
  383. proxy: Proxy configuration dict for Telethon
  384. **kwargs: Additional parameters for TelegramService
  385. Returns:
  386. TelegramService instance
  387. """
  388. global _telegram_service
  389. if _telegram_service is None:
  390. if api_id is None or api_hash is None:
  391. raise ValueError("api_id and api_hash required for first initialization")
  392. _telegram_service = TelegramService(
  393. api_id=api_id, api_hash=api_hash, proxy=proxy, **kwargs
  394. )
  395. return _telegram_service
  396. async def cleanup_telegram_service():
  397. """Cleanup Telegram service on shutdown"""
  398. global _telegram_service
  399. if _telegram_service:
  400. await _telegram_service.disconnect()
  401. _telegram_service = None
  402. logger.info("Telegram service cleaned up")