test_telegram_integration.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. #!/usr/bin/env python3
  2. """
  3. Script de prueba para la integración de Telegram
  4. Ejecutar: python test_telegram_integration.py
  5. """
  6. import asyncio
  7. import sys
  8. from pathlib import Path
  9. # Agregar el directorio raíz al path
  10. sys.path.insert(0, str(Path(__file__).parent.parent))
  11. # Import dotenv and load before other project imports
  12. from dotenv import load_dotenv
  13. load_dotenv()
  14. # Now import project modules (they may depend on env vars)
  15. from config import Config # noqa: E402
  16. from services.telegram_integration import ( # noqa: E402
  17. initialize_telegram_service,
  18. send_security_alert_telegram,
  19. send_system_alert_telegram,
  20. send_telegram_notification,
  21. send_user_activity_alert_telegram,
  22. telegram_health_check,
  23. )
  24. from services.telegram_service import ( # noqa: E402
  25. NotificationPriority,
  26. get_telegram_service,
  27. parse_http_proxy_url,
  28. )
  29. def print_separator(title=""):
  30. """Imprimir separador visual"""
  31. print("\n" + "=" * 60)
  32. if title:
  33. print(f" {title}")
  34. print("=" * 60)
  35. print()
  36. def check_configuration():
  37. """Verificar configuración de Telegram"""
  38. print_separator("Verificación de Configuración")
  39. print(f"TELEGRAM_ENABLED: {Config.TELEGRAM_ENABLED}")
  40. print(
  41. f"TELEGRAM_API_ID: {'✓ Configurado' if Config.TELEGRAM_API_ID else '✗ No configurado'}"
  42. )
  43. print(
  44. f"TELEGRAM_API_HASH: {'✓ Configurado' if Config.TELEGRAM_API_HASH else '✗ No configurado'}"
  45. )
  46. print(
  47. f"TELEGRAM_BOT_TOKEN: {'✓ Configurado' if Config.TELEGRAM_BOT_TOKEN else '✗ No configurado'}"
  48. )
  49. print(
  50. f"TELEGRAM_PHONE: {'✓ Configurado' if Config.TELEGRAM_PHONE else '✗ No configurado'}"
  51. )
  52. print(f"TELEGRAM_SESSION_NAME: {Config.TELEGRAM_SESSION_NAME}")
  53. print(
  54. f"TELEGRAM_RECIPIENTS: {Config.TELEGRAM_RECIPIENTS if Config.TELEGRAM_RECIPIENTS else '✗ No configurado'}"
  55. )
  56. if not Config.TELEGRAM_ENABLED:
  57. print("\n⚠️ TELEGRAM_ENABLED=false - Habilita en el archivo .env")
  58. return False
  59. if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
  60. print("\n❌ Faltan credenciales de API")
  61. print(" Obtén tus credenciales en: https://my.telegram.org/apps")
  62. return False
  63. if not Config.TELEGRAM_BOT_TOKEN and not Config.TELEGRAM_PHONE:
  64. print("\n❌ Falta BOT_TOKEN o PHONE")
  65. print(" Configura TELEGRAM_BOT_TOKEN o TELEGRAM_PHONE")
  66. return False
  67. if not Config.TELEGRAM_RECIPIENTS or not any(
  68. r.strip() for r in Config.TELEGRAM_RECIPIENTS
  69. ):
  70. print("\n❌ Faltan destinatarios")
  71. print(" Configura TELEGRAM_RECIPIENTS en el archivo .env")
  72. return False
  73. print("\n✅ Configuración completa")
  74. return True
  75. async def test_connection():
  76. """Probar conexión a Telegram"""
  77. print_separator("Test de Conexión")
  78. try:
  79. service = get_telegram_service(
  80. api_id=int(Config.TELEGRAM_API_ID),
  81. api_hash=Config.TELEGRAM_API_HASH,
  82. bot_token=Config.TELEGRAM_BOT_TOKEN,
  83. phone=Config.TELEGRAM_PHONE,
  84. session_name=Config.TELEGRAM_SESSION_NAME,
  85. enabled=Config.TELEGRAM_ENABLED,
  86. )
  87. print("Conectando a Telegram...")
  88. await service.connect()
  89. print("✅ Conexión establecida")
  90. print("\nObteniendo información de la cuenta...")
  91. health = await service.health_check()
  92. print("\n📊 Estado del servicio:")
  93. print(f" Habilitado: {health['enabled']}")
  94. print(f" Conectado: {health['connected']}")
  95. print(f" Modo Bot: {health['bot_mode']}")
  96. print(f" Sesión: {health['session']}")
  97. if health["connected"]:
  98. print(f" User ID: {health.get('user_id', 'N/A')}")
  99. print(f" Username: {health.get('username', 'N/A')}")
  100. print("\n✅ Test de conexión exitoso")
  101. else:
  102. error = health.get("error", "Unknown error")
  103. print(f"\n❌ No se pudo conectar: {error}")
  104. return False
  105. await service.disconnect()
  106. return True
  107. except Exception as e:
  108. print(f"\n❌ Error en test de conexión: {e}")
  109. import traceback
  110. traceback.print_exc()
  111. return False
  112. async def test_send_basic_notification():
  113. """Probar envío de notificación básica"""
  114. print_separator("Test de Notificación Básica")
  115. try:
  116. service = get_telegram_service()
  117. await service.connect()
  118. recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
  119. recipient = recipients[0]
  120. print(f"Enviando notificación de prueba a: {recipient}")
  121. success = await service.send_notification(
  122. recipient=recipient,
  123. message="🧪 Test de notificación desde SquidStats\n\nSi recibes este mensaje, la integración funciona correctamente.",
  124. priority=NotificationPriority.NORMAL,
  125. source="Test Suite",
  126. )
  127. if success:
  128. print("✅ Notificación enviada exitosamente")
  129. else:
  130. print("❌ No se pudo enviar la notificación")
  131. await service.disconnect()
  132. return success
  133. except Exception as e:
  134. print(f"❌ Error enviando notificación: {e}")
  135. import traceback
  136. traceback.print_exc()
  137. return False
  138. async def test_priority_notifications():
  139. """Probar notificaciones con diferentes prioridades"""
  140. print_separator("Test de Prioridades")
  141. try:
  142. service = get_telegram_service()
  143. await service.connect()
  144. recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
  145. recipient = recipients[0]
  146. priorities = [
  147. (NotificationPriority.LOW, "Información de baja prioridad"),
  148. (NotificationPriority.NORMAL, "Notificación estándar"),
  149. (NotificationPriority.HIGH, "Advertencia importante"),
  150. (NotificationPriority.CRITICAL, "¡Alerta crítica!"),
  151. ]
  152. for priority, message in priorities:
  153. print(f"Enviando {priority.name}...")
  154. await service.send_notification(
  155. recipient=recipient,
  156. message=message,
  157. priority=priority,
  158. source="Priority Test",
  159. )
  160. await asyncio.sleep(1) # Evitar rate limiting
  161. print("✅ Todas las prioridades enviadas")
  162. await service.disconnect()
  163. return True
  164. except Exception as e:
  165. print(f"❌ Error en test de prioridades: {e}")
  166. return False
  167. async def test_formatted_notifications():
  168. """Probar notificaciones con datos extra"""
  169. print_separator("Test de Mensajes Formateados")
  170. try:
  171. service = get_telegram_service()
  172. await service.connect()
  173. recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
  174. recipient = recipients[0]
  175. print("Enviando notificación con metadata...")
  176. await service.send_notification(
  177. recipient=recipient,
  178. message="Alerta del sistema detectada",
  179. priority=NotificationPriority.HIGH,
  180. source="System Monitor",
  181. extra_data={
  182. "CPU": "85%",
  183. "RAM": "7.2 GB / 16 GB",
  184. "Disco": "45.3 GB disponibles",
  185. "Uptime": "5 días, 3 horas",
  186. },
  187. )
  188. print("✅ Notificación formateada enviada")
  189. await service.disconnect()
  190. return True
  191. except Exception as e:
  192. print(f"❌ Error en test de formato: {e}")
  193. return False
  194. def test_integration_wrapper():
  195. """Probar wrapper de integración (funciones síncronas)"""
  196. print_separator("Test de Wrapper de Integración")
  197. try:
  198. # Inicializar servicio
  199. print("Inicializando servicio de Telegram...")
  200. if not initialize_telegram_service():
  201. print("❌ No se pudo inicializar el servicio")
  202. return False
  203. print("✅ Servicio inicializado")
  204. # Health check
  205. print("\nVerificando estado...")
  206. health = telegram_health_check()
  207. print(f"Estado: {health}")
  208. if not health.get("connected"):
  209. print("⚠️ No conectado - algunas funciones no estarán disponibles")
  210. # Enviar notificación genérica
  211. print("\nEnviando notificación genérica...")
  212. success1 = send_telegram_notification(
  213. notification_type="info",
  214. message="Test de integración wrapper",
  215. source="Integration Test",
  216. )
  217. print(f"Resultado: {'✅ Enviado' if success1 else '❌ Fallo'}")
  218. # Enviar alerta de seguridad
  219. print("\nEnviando alerta de seguridad...")
  220. success2 = send_security_alert_telegram(
  221. alert_type="Acceso sospechoso detectado",
  222. details={
  223. "IP": "192.168.1.100",
  224. "Usuario": "test_user",
  225. "Timestamp": "2026-01-17 15:00:00",
  226. },
  227. )
  228. print(f"Resultado: {'✅ Enviado' if success2 else '❌ Fallo'}")
  229. # Enviar alerta del sistema
  230. print("\nEnviando alerta del sistema...")
  231. success3 = send_system_alert_telegram(
  232. alert_message="Uso elevado de recursos detectado",
  233. metrics={"CPU": "92%", "Memoria": "14.8 GB / 16 GB", "Temperatura": "78°C"},
  234. )
  235. print(f"Resultado: {'✅ Enviado' if success3 else '❌ Fallo'}")
  236. # Enviar alerta de actividad de usuario
  237. print("\nEnviando alerta de actividad de usuario...")
  238. success4 = send_user_activity_alert_telegram(
  239. username="john_doe",
  240. activity_data={
  241. "Requests": "1,234",
  242. "Datos descargados": "45.3 GB",
  243. "Sitios únicos": "87",
  244. },
  245. )
  246. print(f"Resultado: {'✅ Enviado' if success4 else '❌ Fallo'}")
  247. all_success = all([success1, success2, success3, success4])
  248. if all_success:
  249. print("\n✅ Todos los tests del wrapper exitosos")
  250. else:
  251. print("\n⚠️ Algunos tests fallaron")
  252. return all_success
  253. except Exception as e:
  254. print(f"\n❌ Error en test de wrapper: {e}")
  255. import traceback
  256. traceback.print_exc()
  257. return False
  258. async def run_async_tests():
  259. """Ejecutar tests asíncronos"""
  260. results = []
  261. # Test de conexión
  262. results.append(await test_connection())
  263. await asyncio.sleep(2)
  264. # Test de notificación básica
  265. results.append(await test_send_basic_notification())
  266. await asyncio.sleep(2)
  267. # Test de prioridades
  268. results.append(await test_priority_notifications())
  269. await asyncio.sleep(2)
  270. # Test de formato
  271. results.append(await test_formatted_notifications())
  272. return results
  273. def test_proxy_parsing():
  274. """Test parsing de URLs de proxy HTTP"""
  275. print_separator("🧪 Test de Parsing de Proxy")
  276. test_cases = [
  277. # (input, expected_output_keys)
  278. ("", None),
  279. ("http://proxy.example.com:8080", ["proxy_type", "addr", "port"]),
  280. (
  281. "http://user:pass@proxy.example.com:8080",
  282. ["proxy_type", "addr", "port", "username", "password"],
  283. ),
  284. ("https://proxy.example.com:8080", None), # Solo HTTP soportado
  285. ("invalid-url", None),
  286. ]
  287. all_passed = True
  288. for i, (proxy_url, expected_keys) in enumerate(test_cases, 1):
  289. try:
  290. result = parse_http_proxy_url(proxy_url)
  291. if expected_keys is None:
  292. if result is None:
  293. print(f"✅ Test {i}: '{proxy_url}' → None (correcto)")
  294. else:
  295. print(f"❌ Test {i}: '{proxy_url}' → {result} (esperaba None)")
  296. all_passed = False
  297. else:
  298. if result and all(key in result for key in expected_keys):
  299. print(f"✅ Test {i}: '{proxy_url}' → {result}")
  300. else:
  301. print(
  302. f"❌ Test {i}: '{proxy_url}' → {result} (faltan keys: {expected_keys})"
  303. )
  304. all_passed = False
  305. except Exception as e:
  306. print(f"❌ Test {i}: Error parsing '{proxy_url}': {e}")
  307. all_passed = False
  308. if all_passed:
  309. print("\n✅ Todos los tests de proxy pasaron")
  310. else:
  311. print("\n❌ Algunos tests de proxy fallaron")
  312. return all_passed
  313. def main():
  314. """Función principal"""
  315. print_separator("🧪 Test de Integración de Telegram")
  316. # Verificar configuración
  317. if not check_configuration():
  318. print("\n❌ Configuración incompleta. Corrige los errores y vuelve a intentar.")
  319. sys.exit(1)
  320. # Test de parsing de proxy
  321. proxy_test_passed = test_proxy_parsing()
  322. # Ejecutar tests asíncronos
  323. print("\n🚀 Iniciando tests asíncronos...")
  324. async_results = asyncio.run(run_async_tests())
  325. # Ejecutar tests síncronos (wrapper)
  326. print("\n🚀 Iniciando tests de wrapper...")
  327. sync_result = test_integration_wrapper()
  328. # Resumen
  329. print_separator("📊 Resumen de Tests")
  330. tests = [
  331. ("Parsing de Proxy", proxy_test_passed),
  332. ("Conexión", async_results[0] if len(async_results) > 0 else False),
  333. ("Notificación básica", async_results[1] if len(async_results) > 1 else False),
  334. ("Prioridades", async_results[2] if len(async_results) > 2 else False),
  335. ("Formato", async_results[3] if len(async_results) > 3 else False),
  336. ("Wrapper de integración", sync_result),
  337. ]
  338. for test_name, result in tests:
  339. status = "✅ PASS" if result else "❌ FAIL"
  340. print(f"{status} - {test_name}")
  341. total = len(tests)
  342. passed = sum(1 for _, result in tests if result)
  343. print(f"\n📈 Resultados: {passed}/{total} tests exitosos")
  344. if passed == total:
  345. print(
  346. "\n🎉 ¡Todos los tests pasaron! La integración de Telegram está funcionando correctamente."
  347. )
  348. return 0
  349. else:
  350. print("\n⚠️ Algunos tests fallaron. Revisa los logs para más detalles.")
  351. return 1
  352. if __name__ == "__main__":
  353. try:
  354. exit_code = main()
  355. sys.exit(exit_code)
  356. except KeyboardInterrupt:
  357. print("\n\n⚠️ Test interrumpido por el usuario")
  358. sys.exit(130)
  359. except Exception as e:
  360. print(f"\n\n❌ Error fatal: {e}")
  361. import traceback
  362. traceback.print_exc()
  363. sys.exit(1)