telegram_integration.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. """
  2. Telegram Integration Wrapper
  3. Integrates Telegram notifications with the existing notification system
  4. """
  5. import asyncio
  6. from collections.abc import Callable
  7. from concurrent.futures import ThreadPoolExecutor
  8. from functools import wraps
  9. from typing import Any
  10. from loguru import logger
  11. from config import Config
  12. from services.notifications.telegram_service import (
  13. NotificationPriority,
  14. TelegramService,
  15. get_telegram_service,
  16. parse_http_proxy_url,
  17. )
  18. # Thread pool for async execution
  19. _executor = ThreadPoolExecutor(max_workers=2)
  20. _telegram_service: TelegramService | None = None
  21. def run_async(coro):
  22. """
  23. Run an async coroutine in a new event loop
  24. Helper for calling async functions from sync code
  25. Always creates a new event loop in the current thread
  26. """
  27. # Always create a new event loop for the thread
  28. loop = asyncio.new_event_loop()
  29. asyncio.set_event_loop(loop)
  30. try:
  31. return loop.run_until_complete(coro)
  32. finally:
  33. try:
  34. # Cancel all remaining tasks
  35. pending = asyncio.all_tasks(loop)
  36. for task in pending:
  37. task.cancel()
  38. # Run loop until all tasks are cancelled
  39. loop.run_until_complete(asyncio.gather(*pending, return_exceptions=True))
  40. except Exception as e:
  41. logger.debug("Error while cancelling pending async tasks: %s", e)
  42. finally:
  43. loop.close()
  44. def async_to_sync(async_func: Callable) -> Callable:
  45. """
  46. Decorator to convert async function to sync
  47. Runs async function in thread pool to avoid blocking
  48. """
  49. @wraps(async_func)
  50. def wrapper(*args, **kwargs):
  51. # Execute in thread pool with a new event loop
  52. future = _executor.submit(run_async, async_func(*args, **kwargs))
  53. return future.result(timeout=60)
  54. return wrapper
  55. def initialize_telegram_service() -> bool:
  56. """
  57. Initialize Telegram service with config
  58. Returns:
  59. True if initialized successfully
  60. """
  61. global _telegram_service
  62. if not Config.TELEGRAM_ENABLED:
  63. logger.info("Telegram notifications disabled in config")
  64. return False
  65. if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
  66. logger.warning(
  67. "Telegram API credentials not configured. "
  68. "Set TELEGRAM_API_ID and TELEGRAM_API_HASH in environment."
  69. )
  70. return False
  71. try:
  72. api_id = int(Config.TELEGRAM_API_ID)
  73. # Configure proxy if available
  74. proxy_config = None
  75. if Config.HTTP_PROXY:
  76. proxy_config = parse_http_proxy_url(Config.HTTP_PROXY)
  77. if proxy_config:
  78. logger.info(f"Using HTTP proxy: {Config.HTTP_PROXY}")
  79. else:
  80. logger.warning(f"Invalid proxy URL: {Config.HTTP_PROXY}")
  81. _telegram_service = get_telegram_service(
  82. api_id=api_id,
  83. api_hash=Config.TELEGRAM_API_HASH,
  84. bot_token=Config.TELEGRAM_BOT_TOKEN,
  85. session_name=Config.TELEGRAM_SESSION_NAME,
  86. phone=Config.TELEGRAM_PHONE,
  87. enabled=Config.TELEGRAM_ENABLED,
  88. proxy=proxy_config,
  89. )
  90. logger.info("Telegram service initialized successfully")
  91. return True
  92. except ValueError as e:
  93. logger.error(f"Invalid Telegram API ID: {e}")
  94. return False
  95. except Exception as e:
  96. logger.error(f"Failed to initialize Telegram service: {e}")
  97. return False
  98. def map_notification_type_to_priority(notification_type: str) -> NotificationPriority:
  99. """
  100. Map notification type to Telegram priority
  101. Args:
  102. notification_type: Notification type from the system
  103. Returns:
  104. NotificationPriority enum value
  105. """
  106. mapping = {
  107. "error": NotificationPriority.CRITICAL,
  108. "warning": NotificationPriority.HIGH,
  109. "success": NotificationPriority.NORMAL,
  110. "info": NotificationPriority.LOW,
  111. }
  112. return mapping.get(notification_type.lower(), NotificationPriority.NORMAL)
  113. def map_source_to_emoji(source: str) -> str:
  114. """
  115. Map notification source to emoji
  116. Args:
  117. source: Notification source
  118. Returns:
  119. Emoji string
  120. """
  121. mapping = {
  122. "security": "🔒",
  123. "system": "💻",
  124. "squid": "🦑",
  125. "users": "👥",
  126. "git": "📦",
  127. "database": "🗄️",
  128. "network": "🌐",
  129. }
  130. return mapping.get(source.lower(), "📢")
  131. @async_to_sync
  132. async def send_telegram_notification(
  133. notification_type: str,
  134. message: str,
  135. source: str = "system",
  136. extra_data: dict[str, Any] | None = None,
  137. ) -> bool:
  138. """
  139. Send notification to all configured Telegram recipients
  140. Args:
  141. notification_type: Type of notification ('info', 'warning', 'error', 'success')
  142. message: Notification message
  143. source: Source of the notification
  144. extra_data: Additional data to include
  145. Returns:
  146. True if sent to at least one recipient
  147. """
  148. if not _telegram_service or not Config.TELEGRAM_ENABLED:
  149. return False
  150. if not Config.TELEGRAM_RECIPIENTS:
  151. logger.debug("No Telegram recipients configured")
  152. return False
  153. # Filter empty recipients
  154. recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
  155. if not recipients:
  156. return False
  157. priority = map_notification_type_to_priority(notification_type)
  158. emoji = map_source_to_emoji(source)
  159. source_display = f"{emoji} {source.title()}"
  160. try:
  161. results = await _telegram_service.send_bulk_notifications(
  162. recipients=recipients,
  163. message=message,
  164. priority=priority,
  165. source=source_display,
  166. extra_data=extra_data,
  167. )
  168. success_count = sum(1 for success in results.values() if success)
  169. if success_count > 0:
  170. logger.info(
  171. f"Telegram notification sent to {success_count}/{len(recipients)} recipients"
  172. )
  173. return True
  174. else:
  175. logger.warning("Failed to send Telegram notification to any recipient")
  176. return False
  177. except Exception as e:
  178. logger.error(f"Error sending Telegram notification: {e}")
  179. return False
  180. @async_to_sync
  181. async def send_security_alert_telegram(
  182. alert_type: str, details: dict[str, Any]
  183. ) -> bool:
  184. """
  185. Send security alert to Telegram
  186. Args:
  187. alert_type: Type of security alert
  188. details: Alert details
  189. Returns:
  190. True if sent successfully
  191. """
  192. if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
  193. return False
  194. recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
  195. success_count = 0
  196. for recipient in recipients:
  197. try:
  198. success = await _telegram_service.send_security_alert(
  199. recipient, alert_type, details
  200. )
  201. if success:
  202. success_count += 1
  203. except Exception as e:
  204. logger.error(f"Failed to send security alert to {recipient}: {e}")
  205. return success_count > 0
  206. @async_to_sync
  207. async def send_system_alert_telegram(
  208. alert_message: str, metrics: dict[str, Any] | None = None
  209. ) -> bool:
  210. """
  211. Send system alert to Telegram
  212. Args:
  213. alert_message: Alert message
  214. metrics: System metrics
  215. Returns:
  216. True if sent successfully
  217. """
  218. if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
  219. return False
  220. recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
  221. success_count = 0
  222. for recipient in recipients:
  223. try:
  224. success = await _telegram_service.send_system_alert(
  225. recipient, alert_message, metrics
  226. )
  227. if success:
  228. success_count += 1
  229. except Exception as e:
  230. logger.error(f"Failed to send system alert to {recipient}: {e}")
  231. return success_count > 0
  232. @async_to_sync
  233. async def send_user_activity_alert_telegram(
  234. username: str, activity_data: dict[str, Any]
  235. ) -> bool:
  236. """
  237. Send user activity alert to Telegram
  238. Args:
  239. username: Username with high activity
  240. activity_data: Activity details
  241. Returns:
  242. True if sent successfully
  243. """
  244. if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
  245. return False
  246. recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
  247. success_count = 0
  248. for recipient in recipients:
  249. try:
  250. success = await _telegram_service.send_user_activity_alert(
  251. recipient, username, activity_data
  252. )
  253. if success:
  254. success_count += 1
  255. except Exception as e:
  256. logger.error(f"Failed to send user activity alert to {recipient}: {e}")
  257. return success_count > 0
  258. @async_to_sync
  259. async def telegram_health_check() -> dict[str, Any]:
  260. """
  261. Check Telegram service health
  262. Returns:
  263. Health status dictionary
  264. """
  265. if not _telegram_service:
  266. return {
  267. "enabled": Config.TELEGRAM_ENABLED,
  268. "initialized": False,
  269. "connected": False,
  270. }
  271. try:
  272. health = await _telegram_service.health_check()
  273. return health
  274. except Exception as e:
  275. logger.exception("Telegram health check failed")
  276. err = str(e) if getattr(Config, "DEBUG", False) else "Internal error"
  277. return {
  278. "enabled": Config.TELEGRAM_ENABLED,
  279. "initialized": True,
  280. "connected": False,
  281. "error": err,
  282. }
  283. def cleanup_telegram() -> None:
  284. """Cleanup Telegram service on shutdown"""
  285. global _telegram_service
  286. if _telegram_service:
  287. try:
  288. run_async(_telegram_service.disconnect())
  289. logger.info("Telegram service disconnected")
  290. except Exception as e:
  291. logger.error(f"Error during Telegram cleanup: {e}")
  292. finally:
  293. _telegram_service = None
  294. _executor.shutdown(wait=True)