Przeglądaj źródła

Refactor Telegram integration and improve notification handling

- Reintroduced the initialization of the Telegram service in app.py.
- Reformatted the TELEGRAM_RECIPIENTS configuration in config.py for better readability.
- Enhanced the notifications.py service to ensure Telegram notifications are sent correctly.
- Updated telegram_integration.py to streamline notification functions and improve error handling.
- Refined telegram_service.py to ensure proper connection management and proxy parsing.
- Improved test_telegram_integration.py by organizing imports and enhancing configuration checks.
- Added detailed logging and error handling across the Telegram integration workflow.
Manuel 10 miesięcy temu
rodzic
commit
0878b2ba3e

+ 2 - 1
app.py

@@ -29,9 +29,10 @@ from services.notifications import (
 # Import Telegram integration (optional)
 # Import Telegram integration (optional)
 try:
 try:
     from services.telegram_integration import (
     from services.telegram_integration import (
-        initialize_telegram_service,
         cleanup_telegram,
         cleanup_telegram,
+        initialize_telegram_service,
     )
     )
+
     TELEGRAM_AVAILABLE = True
     TELEGRAM_AVAILABLE = True
 except Exception:
 except Exception:
     TELEGRAM_AVAILABLE = False
     TELEGRAM_AVAILABLE = False

+ 3 - 1
config.py

@@ -62,7 +62,9 @@ class Config:
     TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
     TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
     TELEGRAM_SESSION_NAME = os.getenv("TELEGRAM_SESSION_NAME", "squidstats_bot")
     TELEGRAM_SESSION_NAME = os.getenv("TELEGRAM_SESSION_NAME", "squidstats_bot")
     TELEGRAM_PHONE = os.getenv("TELEGRAM_PHONE")
     TELEGRAM_PHONE = os.getenv("TELEGRAM_PHONE")
-    TELEGRAM_RECIPIENTS = os.getenv("TELEGRAM_RECIPIENTS", "").split(",")  # Comma-separated list
+    TELEGRAM_RECIPIENTS = os.getenv("TELEGRAM_RECIPIENTS", "").split(
+        ","
+    )  # Comma-separated list
 
 
     # Proxy settings
     # Proxy settings
     HTTP_PROXY = os.getenv("HTTP_PROXY", "").strip()
     HTTP_PROXY = os.getenv("HTTP_PROXY", "").strip()

+ 3 - 5
services/notifications.py

@@ -18,6 +18,7 @@ logger = logging.getLogger(__name__)
 # Import Telegram integration (optional - fails gracefully if not configured)
 # Import Telegram integration (optional - fails gracefully if not configured)
 try:
 try:
     from services.telegram_integration import send_telegram_notification
     from services.telegram_integration import send_telegram_notification
+
     TELEGRAM_AVAILABLE = True
     TELEGRAM_AVAILABLE = True
 except Exception as e:
 except Exception as e:
     logger.debug(f"Telegram integration not available: {e}")
     logger.debug(f"Telegram integration not available: {e}")
@@ -219,14 +220,12 @@ def add_notification(
                     "unread_count": unread_count,
                     "unread_count": unread_count,
                 },
                 },
             )
             )
-        
+
         # Send to Telegram if enabled and requested
         # Send to Telegram if enabled and requested
         if send_telegram and TELEGRAM_AVAILABLE and send_telegram_notification:
         if send_telegram and TELEGRAM_AVAILABLE and send_telegram_notification:
             try:
             try:
                 send_telegram_notification(
                 send_telegram_notification(
-                    notification_type=notification_type,
-                    message=message,
-                    source=source
+                    notification_type=notification_type, message=message, source=source
                 )
                 )
             except Exception as e:
             except Exception as e:
                 logger.error(f"Failed to send Telegram notification: {e}")
                 logger.error(f"Failed to send Telegram notification: {e}")
@@ -468,7 +467,6 @@ def check_system_health():
 def has_remote_commits_with_messages(
 def has_remote_commits_with_messages(
     repo_path: str, branch: str = "main"
     repo_path: str, branch: str = "main"
 ) -> tuple[bool, list[str]]:
 ) -> tuple[bool, list[str]]:
-    
     git_dir = os.path.join(repo_path, ".git")
     git_dir = os.path.join(repo_path, ".git")
     if not os.path.isdir(git_dir):
     if not os.path.isdir(git_dir):
         logger.warning(f"Not a valid Git repository: {repo_path}")
         logger.warning(f"Not a valid Git repository: {repo_path}")

+ 72 - 82
services/telegram_integration.py

@@ -5,9 +5,10 @@ Integrates Telegram notifications with the existing notification system
 
 
 import asyncio
 import asyncio
 import logging
 import logging
+from collections.abc import Callable
 from concurrent.futures import ThreadPoolExecutor
 from concurrent.futures import ThreadPoolExecutor
 from functools import wraps
 from functools import wraps
-from typing import Any, Callable, Optional
+from typing import Any
 
 
 from config import Config
 from config import Config
 from services.telegram_service import (
 from services.telegram_service import (
@@ -21,7 +22,7 @@ logger = logging.getLogger(__name__)
 
 
 # Thread pool for async execution
 # Thread pool for async execution
 _executor = ThreadPoolExecutor(max_workers=2)
 _executor = ThreadPoolExecutor(max_workers=2)
-_telegram_service: Optional[TelegramService] = None
+_telegram_service: TelegramService | None = None
 
 
 
 
 def run_async(coro):
 def run_async(coro):
@@ -54,41 +55,39 @@ def async_to_sync(async_func: Callable) -> Callable:
     Decorator to convert async function to sync
     Decorator to convert async function to sync
     Runs async function in thread pool to avoid blocking
     Runs async function in thread pool to avoid blocking
     """
     """
+
     @wraps(async_func)
     @wraps(async_func)
     def wrapper(*args, **kwargs):
     def wrapper(*args, **kwargs):
         # Execute in thread pool with a new event loop
         # Execute in thread pool with a new event loop
-        future = _executor.submit(
-            run_async,
-            async_func(*args, **kwargs)
-        )
+        future = _executor.submit(run_async, async_func(*args, **kwargs))
         return future.result(timeout=60)
         return future.result(timeout=60)
-    
+
     return wrapper
     return wrapper
 
 
 
 
 def initialize_telegram_service() -> bool:
 def initialize_telegram_service() -> bool:
     """
     """
     Initialize Telegram service with config
     Initialize Telegram service with config
-    
+
     Returns:
     Returns:
         True if initialized successfully
         True if initialized successfully
     """
     """
     global _telegram_service
     global _telegram_service
-    
+
     if not Config.TELEGRAM_ENABLED:
     if not Config.TELEGRAM_ENABLED:
         logger.info("Telegram notifications disabled in config")
         logger.info("Telegram notifications disabled in config")
         return False
         return False
-    
+
     if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
     if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
         logger.warning(
         logger.warning(
             "Telegram API credentials not configured. "
             "Telegram API credentials not configured. "
             "Set TELEGRAM_API_ID and TELEGRAM_API_HASH in environment."
             "Set TELEGRAM_API_ID and TELEGRAM_API_HASH in environment."
         )
         )
         return False
         return False
-    
+
     try:
     try:
         api_id = int(Config.TELEGRAM_API_ID)
         api_id = int(Config.TELEGRAM_API_ID)
-        
+
         # Configure proxy if available
         # Configure proxy if available
         proxy_config = None
         proxy_config = None
         if Config.HTTP_PROXY:
         if Config.HTTP_PROXY:
@@ -97,7 +96,7 @@ def initialize_telegram_service() -> bool:
                 logger.info(f"Using HTTP proxy: {Config.HTTP_PROXY}")
                 logger.info(f"Using HTTP proxy: {Config.HTTP_PROXY}")
             else:
             else:
                 logger.warning(f"Invalid proxy URL: {Config.HTTP_PROXY}")
                 logger.warning(f"Invalid proxy URL: {Config.HTTP_PROXY}")
-        
+
         _telegram_service = get_telegram_service(
         _telegram_service = get_telegram_service(
             api_id=api_id,
             api_id=api_id,
             api_hash=Config.TELEGRAM_API_HASH,
             api_hash=Config.TELEGRAM_API_HASH,
@@ -105,12 +104,12 @@ def initialize_telegram_service() -> bool:
             session_name=Config.TELEGRAM_SESSION_NAME,
             session_name=Config.TELEGRAM_SESSION_NAME,
             phone=Config.TELEGRAM_PHONE,
             phone=Config.TELEGRAM_PHONE,
             enabled=Config.TELEGRAM_ENABLED,
             enabled=Config.TELEGRAM_ENABLED,
-            proxy=proxy_config
+            proxy=proxy_config,
         )
         )
-        
+
         logger.info("Telegram service initialized successfully")
         logger.info("Telegram service initialized successfully")
         return True
         return True
-        
+
     except ValueError as e:
     except ValueError as e:
         logger.error(f"Invalid Telegram API ID: {e}")
         logger.error(f"Invalid Telegram API ID: {e}")
         return False
         return False
@@ -122,44 +121,44 @@ def initialize_telegram_service() -> bool:
 def map_notification_type_to_priority(notification_type: str) -> NotificationPriority:
 def map_notification_type_to_priority(notification_type: str) -> NotificationPriority:
     """
     """
     Map notification type to Telegram priority
     Map notification type to Telegram priority
-    
+
     Args:
     Args:
         notification_type: Notification type from the system
         notification_type: Notification type from the system
-    
+
     Returns:
     Returns:
         NotificationPriority enum value
         NotificationPriority enum value
     """
     """
     mapping = {
     mapping = {
-        'error': NotificationPriority.CRITICAL,
-        'warning': NotificationPriority.HIGH,
-        'success': NotificationPriority.NORMAL,
-        'info': NotificationPriority.LOW,
+        "error": NotificationPriority.CRITICAL,
+        "warning": NotificationPriority.HIGH,
+        "success": NotificationPriority.NORMAL,
+        "info": NotificationPriority.LOW,
     }
     }
-    
+
     return mapping.get(notification_type.lower(), NotificationPriority.NORMAL)
     return mapping.get(notification_type.lower(), NotificationPriority.NORMAL)
 
 
 
 
 def map_source_to_emoji(source: str) -> str:
 def map_source_to_emoji(source: str) -> str:
     """
     """
     Map notification source to emoji
     Map notification source to emoji
-    
+
     Args:
     Args:
         source: Notification source
         source: Notification source
-    
+
     Returns:
     Returns:
         Emoji string
         Emoji string
     """
     """
     mapping = {
     mapping = {
-        'security': '🔒',
-        'system': '💻',
-        'squid': '🦑',
-        'users': '👥',
-        'git': '📦',
-        'database': '🗄️',
-        'network': '🌐',
+        "security": "🔒",
+        "system": "💻",
+        "squid": "🦑",
+        "users": "👥",
+        "git": "📦",
+        "database": "🗄️",
+        "network": "🌐",
     }
     }
-    
-    return mapping.get(source.lower(), '📢')
+
+    return mapping.get(source.lower(), "📢")
 
 
 
 
 @async_to_sync
 @async_to_sync
@@ -167,48 +166,48 @@ async def send_telegram_notification(
     notification_type: str,
     notification_type: str,
     message: str,
     message: str,
     source: str = "system",
     source: str = "system",
-    extra_data: Optional[dict[str, Any]] = None
+    extra_data: dict[str, Any] | None = None,
 ) -> bool:
 ) -> bool:
     """
     """
     Send notification to all configured Telegram recipients
     Send notification to all configured Telegram recipients
-    
+
     Args:
     Args:
         notification_type: Type of notification ('info', 'warning', 'error', 'success')
         notification_type: Type of notification ('info', 'warning', 'error', 'success')
         message: Notification message
         message: Notification message
         source: Source of the notification
         source: Source of the notification
         extra_data: Additional data to include
         extra_data: Additional data to include
-    
+
     Returns:
     Returns:
         True if sent to at least one recipient
         True if sent to at least one recipient
     """
     """
     if not _telegram_service or not Config.TELEGRAM_ENABLED:
     if not _telegram_service or not Config.TELEGRAM_ENABLED:
         return False
         return False
-    
+
     if not Config.TELEGRAM_RECIPIENTS:
     if not Config.TELEGRAM_RECIPIENTS:
         logger.debug("No Telegram recipients configured")
         logger.debug("No Telegram recipients configured")
         return False
         return False
-    
+
     # Filter empty recipients
     # Filter empty recipients
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
-    
+
     if not recipients:
     if not recipients:
         return False
         return False
-    
+
     priority = map_notification_type_to_priority(notification_type)
     priority = map_notification_type_to_priority(notification_type)
     emoji = map_source_to_emoji(source)
     emoji = map_source_to_emoji(source)
     source_display = f"{emoji} {source.title()}"
     source_display = f"{emoji} {source.title()}"
-    
+
     try:
     try:
         results = await _telegram_service.send_bulk_notifications(
         results = await _telegram_service.send_bulk_notifications(
             recipients=recipients,
             recipients=recipients,
             message=message,
             message=message,
             priority=priority,
             priority=priority,
             source=source_display,
             source=source_display,
-            extra_data=extra_data
+            extra_data=extra_data,
         )
         )
-        
+
         success_count = sum(1 for success in results.values() if success)
         success_count = sum(1 for success in results.values() if success)
-        
+
         if success_count > 0:
         if success_count > 0:
             logger.info(
             logger.info(
                 f"Telegram notification sent to {success_count}/{len(recipients)} recipients"
                 f"Telegram notification sent to {success_count}/{len(recipients)} recipients"
@@ -217,7 +216,7 @@ async def send_telegram_notification(
         else:
         else:
             logger.warning("Failed to send Telegram notification to any recipient")
             logger.warning("Failed to send Telegram notification to any recipient")
             return False
             return False
-            
+
     except Exception as e:
     except Exception as e:
         logger.error(f"Error sending Telegram notification: {e}")
         logger.error(f"Error sending Telegram notification: {e}")
         return False
         return False
@@ -225,109 +224,100 @@ async def send_telegram_notification(
 
 
 @async_to_sync
 @async_to_sync
 async def send_security_alert_telegram(
 async def send_security_alert_telegram(
-    alert_type: str,
-    details: dict[str, Any]
+    alert_type: str, details: dict[str, Any]
 ) -> bool:
 ) -> bool:
     """
     """
     Send security alert to Telegram
     Send security alert to Telegram
-    
+
     Args:
     Args:
         alert_type: Type of security alert
         alert_type: Type of security alert
         details: Alert details
         details: Alert details
-    
+
     Returns:
     Returns:
         True if sent successfully
         True if sent successfully
     """
     """
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
         return False
         return False
-    
+
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     success_count = 0
     success_count = 0
-    
+
     for recipient in recipients:
     for recipient in recipients:
         try:
         try:
             success = await _telegram_service.send_security_alert(
             success = await _telegram_service.send_security_alert(
-                recipient,
-                alert_type,
-                details
+                recipient, alert_type, details
             )
             )
             if success:
             if success:
                 success_count += 1
                 success_count += 1
         except Exception as e:
         except Exception as e:
             logger.error(f"Failed to send security alert to {recipient}: {e}")
             logger.error(f"Failed to send security alert to {recipient}: {e}")
-    
+
     return success_count > 0
     return success_count > 0
 
 
 
 
 @async_to_sync
 @async_to_sync
 async def send_system_alert_telegram(
 async def send_system_alert_telegram(
-    alert_message: str,
-    metrics: Optional[dict[str, Any]] = None
+    alert_message: str, metrics: dict[str, Any] | None = None
 ) -> bool:
 ) -> bool:
     """
     """
     Send system alert to Telegram
     Send system alert to Telegram
-    
+
     Args:
     Args:
         alert_message: Alert message
         alert_message: Alert message
         metrics: System metrics
         metrics: System metrics
-    
+
     Returns:
     Returns:
         True if sent successfully
         True if sent successfully
     """
     """
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
         return False
         return False
-    
+
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     success_count = 0
     success_count = 0
-    
+
     for recipient in recipients:
     for recipient in recipients:
         try:
         try:
             success = await _telegram_service.send_system_alert(
             success = await _telegram_service.send_system_alert(
-                recipient,
-                alert_message,
-                metrics
+                recipient, alert_message, metrics
             )
             )
             if success:
             if success:
                 success_count += 1
                 success_count += 1
         except Exception as e:
         except Exception as e:
             logger.error(f"Failed to send system alert to {recipient}: {e}")
             logger.error(f"Failed to send system alert to {recipient}: {e}")
-    
+
     return success_count > 0
     return success_count > 0
 
 
 
 
 @async_to_sync
 @async_to_sync
 async def send_user_activity_alert_telegram(
 async def send_user_activity_alert_telegram(
-    username: str,
-    activity_data: dict[str, Any]
+    username: str, activity_data: dict[str, Any]
 ) -> bool:
 ) -> bool:
     """
     """
     Send user activity alert to Telegram
     Send user activity alert to Telegram
-    
+
     Args:
     Args:
         username: Username with high activity
         username: Username with high activity
         activity_data: Activity details
         activity_data: Activity details
-    
+
     Returns:
     Returns:
         True if sent successfully
         True if sent successfully
     """
     """
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
         return False
         return False
-    
+
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     success_count = 0
     success_count = 0
-    
+
     for recipient in recipients:
     for recipient in recipients:
         try:
         try:
             success = await _telegram_service.send_user_activity_alert(
             success = await _telegram_service.send_user_activity_alert(
-                recipient,
-                username,
-                activity_data
+                recipient, username, activity_data
             )
             )
             if success:
             if success:
                 success_count += 1
                 success_count += 1
         except Exception as e:
         except Exception as e:
             logger.error(f"Failed to send user activity alert to {recipient}: {e}")
             logger.error(f"Failed to send user activity alert to {recipient}: {e}")
-    
+
     return success_count > 0
     return success_count > 0
 
 
 
 
@@ -335,7 +325,7 @@ async def send_user_activity_alert_telegram(
 async def telegram_health_check() -> dict[str, Any]:
 async def telegram_health_check() -> dict[str, Any]:
     """
     """
     Check Telegram service health
     Check Telegram service health
-    
+
     Returns:
     Returns:
         Health status dictionary
         Health status dictionary
     """
     """
@@ -343,9 +333,9 @@ async def telegram_health_check() -> dict[str, Any]:
         return {
         return {
             "enabled": Config.TELEGRAM_ENABLED,
             "enabled": Config.TELEGRAM_ENABLED,
             "initialized": False,
             "initialized": False,
-            "connected": False
+            "connected": False,
         }
         }
-    
+
     try:
     try:
         health = await _telegram_service.health_check()
         health = await _telegram_service.health_check()
         return health
         return health
@@ -355,14 +345,14 @@ async def telegram_health_check() -> dict[str, Any]:
             "enabled": Config.TELEGRAM_ENABLED,
             "enabled": Config.TELEGRAM_ENABLED,
             "initialized": True,
             "initialized": True,
             "connected": False,
             "connected": False,
-            "error": str(e)
+            "error": str(e),
         }
         }
 
 
 
 
 def cleanup_telegram() -> None:
 def cleanup_telegram() -> None:
     """Cleanup Telegram service on shutdown"""
     """Cleanup Telegram service on shutdown"""
     global _telegram_service
     global _telegram_service
-    
+
     if _telegram_service:
     if _telegram_service:
         try:
         try:
             run_async(_telegram_service.disconnect())
             run_async(_telegram_service.disconnect())
@@ -371,5 +361,5 @@ def cleanup_telegram() -> None:
             logger.error(f"Error during Telegram cleanup: {e}")
             logger.error(f"Error during Telegram cleanup: {e}")
         finally:
         finally:
             _telegram_service = None
             _telegram_service = None
-    
+
     _executor.shutdown(wait=True)
     _executor.shutdown(wait=True)

+ 106 - 146
services/telegram_service.py

@@ -13,26 +13,26 @@ from telethon.tl.types import InputPeerUser, User
 logger = logging.getLogger(__name__)
 logger = logging.getLogger(__name__)
 
 
 
 
-def parse_http_proxy_url(proxy_url: str) -> Optional[dict[str, Any]]:
+def parse_http_proxy_url(proxy_url: str) -> dict[str, Any] | None:
     """
     """
     Convert HTTP proxy URL to Telethon proxy dict
     Convert HTTP proxy URL to Telethon proxy dict
-    
+
     Args:
     Args:
         proxy_url: HTTP proxy URL (http://user:pass@host:port or http://host:port)
         proxy_url: HTTP proxy URL (http://user:pass@host:port or http://host:port)
-    
+
     Returns:
     Returns:
         Dict compatible with Telethon proxy format, or None if invalid
         Dict compatible with Telethon proxy format, or None if invalid
-    
+
     Example:
     Example:
         "http://proxy.example.com:8080" -> {
         "http://proxy.example.com:8080" -> {
             "proxy_type": "http",
             "proxy_type": "http",
             "addr": "proxy.example.com",
             "addr": "proxy.example.com",
             "port": 8080
             "port": 8080
         }
         }
-        
+
         "http://user:pass@proxy.example.com:8080" -> {
         "http://user:pass@proxy.example.com:8080" -> {
             "proxy_type": "http",
             "proxy_type": "http",
-            "addr": "proxy.example.com", 
+            "addr": "proxy.example.com",
             "port": 8080,
             "port": 8080,
             "username": "user",
             "username": "user",
             "password": "pass"
             "password": "pass"
@@ -40,34 +40,34 @@ def parse_http_proxy_url(proxy_url: str) -> Optional[dict[str, Any]]:
     """
     """
     if not proxy_url or not proxy_url.strip():
     if not proxy_url or not proxy_url.strip():
         return None
         return None
-    
+
     try:
     try:
         parsed = urlparse(proxy_url.strip())
         parsed = urlparse(proxy_url.strip())
-        
+
         # Only accept HTTP proxies
         # Only accept HTTP proxies
-        if parsed.scheme.lower() != 'http':
+        if parsed.scheme.lower() != "http":
             logger.warning(f"Unsupported proxy scheme '{parsed.scheme}': {proxy_url}")
             logger.warning(f"Unsupported proxy scheme '{parsed.scheme}': {proxy_url}")
             return None
             return None
-        
+
         if not parsed.hostname or not parsed.port:
         if not parsed.hostname or not parsed.port:
             logger.warning(f"Invalid proxy URL format: {proxy_url}")
             logger.warning(f"Invalid proxy URL format: {proxy_url}")
             return None
             return None
-        
+
         proxy_dict = {
         proxy_dict = {
             "proxy_type": "http",
             "proxy_type": "http",
             "addr": parsed.hostname,
             "addr": parsed.hostname,
-            "port": parsed.port
+            "port": parsed.port,
         }
         }
-        
+
         # Add authentication if present
         # Add authentication if present
         if parsed.username:
         if parsed.username:
             proxy_dict["username"] = parsed.username
             proxy_dict["username"] = parsed.username
         if parsed.password:
         if parsed.password:
             proxy_dict["password"] = parsed.password
             proxy_dict["password"] = parsed.password
-        
+
         logger.debug(f"Parsed proxy: {proxy_dict}")
         logger.debug(f"Parsed proxy: {proxy_dict}")
         return proxy_dict
         return proxy_dict
-        
+
     except Exception as e:
     except Exception as e:
         logger.error(f"Failed to parse proxy URL '{proxy_url}': {e}")
         logger.error(f"Failed to parse proxy URL '{proxy_url}': {e}")
         return None
         return None
@@ -82,16 +82,19 @@ class NotificationPriority(Enum):
 
 
 class TelegramNotificationError(Exception):
 class TelegramNotificationError(Exception):
     """Base exception for Telegram notification errors"""
     """Base exception for Telegram notification errors"""
+
     pass
     pass
 
 
 
 
 class TelegramConnectionError(TelegramNotificationError):
 class TelegramConnectionError(TelegramNotificationError):
     """Raised when connection to Telegram fails"""
     """Raised when connection to Telegram fails"""
+
     pass
     pass
 
 
 
 
 class TelegramSendError(TelegramNotificationError):
 class TelegramSendError(TelegramNotificationError):
     """Raised when sending message fails"""
     """Raised when sending message fails"""
+
     pass
     pass
 
 
 
 
@@ -101,12 +104,12 @@ def async_retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0)
         async def wrapper(*args, **kwargs):
         async def wrapper(*args, **kwargs):
             current_delay = delay
             current_delay = delay
             last_exception = None
             last_exception = None
-            
+
             for attempt in range(max_attempts):
             for attempt in range(max_attempts):
                 try:
                 try:
                     return await func(*args, **kwargs)
                     return await func(*args, **kwargs)
                 except (errors.FloodWaitError, errors.SlowModeWaitError) as e:
                 except (errors.FloodWaitError, errors.SlowModeWaitError) as e:
-                    wait_time = e.seconds if hasattr(e, 'seconds') else current_delay
+                    wait_time = e.seconds if hasattr(e, "seconds") else current_delay
                     logger.warning(
                     logger.warning(
                         f"Rate limited, waiting {wait_time}s (attempt {attempt + 1}/{max_attempts})"
                         f"Rate limited, waiting {wait_time}s (attempt {attempt + 1}/{max_attempts})"
                     )
                     )
@@ -114,47 +117,46 @@ def async_retry(max_attempts: int = 3, delay: float = 1.0, backoff: float = 2.0)
                     last_exception = e
                     last_exception = e
                 except Exception as e:
                 except Exception as e:
                     logger.warning(
                     logger.warning(
-                        f"Network error on attempt {attempt + 1}/{max_attempts}: {e}"
+                        f"Error on attempt {attempt + 1}/{max_attempts}: {e}"
                     )
                     )
                     if attempt < max_attempts - 1:
                     if attempt < max_attempts - 1:
                         await asyncio.sleep(current_delay)
                         await asyncio.sleep(current_delay)
                         current_delay *= backoff
                         current_delay *= backoff
                     last_exception = e
                     last_exception = e
-                except Exception as e:
-                    logger.error(f"Unexpected error in {func.__name__}: {e}")
-                    last_exception = e
                     break
                     break
-            
-            raise TelegramSendError(f"Failed after {max_attempts} attempts") from last_exception
-        
+
+            raise TelegramSendError(
+                f"Failed after {max_attempts} attempts"
+            ) from last_exception
+
         return wrapper
         return wrapper
+
     return decorator
     return decorator
 
 
 
 
 class TelegramService:
 class TelegramService:
-   
-    _instance: Optional['TelegramService'] = None
+    _instance: Optional["TelegramService"] = None
     _lock = asyncio.Lock()
     _lock = asyncio.Lock()
-    
+
     def __new__(cls, *args, **kwargs):
     def __new__(cls, *args, **kwargs):
         if cls._instance is None:
         if cls._instance is None:
             cls._instance = super().__new__(cls)
             cls._instance = super().__new__(cls)
             cls._instance._initialized = False
             cls._instance._initialized = False
         return cls._instance
         return cls._instance
-    
+
     def __init__(
     def __init__(
         self,
         self,
         api_id: int,
         api_id: int,
         api_hash: str,
         api_hash: str,
-        bot_token: Optional[str] = None,
+        bot_token: str | None = None,
         session_name: str = "squidstats_bot",
         session_name: str = "squidstats_bot",
-        phone: Optional[str] = None,
+        phone: str | None = None,
         enabled: bool = True,
         enabled: bool = True,
-        proxy: Optional[dict[str, Any]] = None
+        proxy: dict[str, Any] | None = None,
     ):
     ):
         if self._initialized:
         if self._initialized:
             return
             return
-        
+
         self.api_id = api_id
         self.api_id = api_id
         self.api_hash = api_hash
         self.api_hash = api_hash
         self.bot_token = bot_token
         self.bot_token = bot_token
@@ -162,20 +164,20 @@ class TelegramService:
         self.phone = phone
         self.phone = phone
         self.enabled = enabled
         self.enabled = enabled
         self.proxy = proxy
         self.proxy = proxy
-        
-        self._client: Optional[TelegramClient] = None
+
+        self._client: TelegramClient | None = None
         self._connected = False
         self._connected = False
-        self._event_loop: Optional[asyncio.AbstractEventLoop] = None
+        self._event_loop: asyncio.AbstractEventLoop | None = None
         self._recipients: dict[str, InputPeerUser] = {}
         self._recipients: dict[str, InputPeerUser] = {}
-        
+
         self._initialized = True
         self._initialized = True
         logger.info("TelegramService initialized")
         logger.info("TelegramService initialized")
-    
+
     async def _ensure_connected(self) -> None:
     async def _ensure_connected(self) -> None:
         """Ensure client is connected, connect if necessary"""
         """Ensure client is connected, connect if necessary"""
         if not self.enabled:
         if not self.enabled:
             raise TelegramNotificationError("Telegram notifications are disabled")
             raise TelegramNotificationError("Telegram notifications are disabled")
-        
+
         if self._client and self._connected:
         if self._client and self._connected:
             try:
             try:
                 await self._client.get_me()
                 await self._client.get_me()
@@ -183,15 +185,15 @@ class TelegramService:
             except Exception as e:
             except Exception as e:
                 logger.warning(f"Connection check failed: {e}")
                 logger.warning(f"Connection check failed: {e}")
                 self._connected = False
                 self._connected = False
-        
+
         await self.connect()
         await self.connect()
-    
+
     async def connect(self) -> None:
     async def connect(self) -> None:
         """Establish connection to Telegram"""
         """Establish connection to Telegram"""
         if not self.enabled:
         if not self.enabled:
             logger.info("Telegram notifications disabled, skipping connection")
             logger.info("Telegram notifications disabled, skipping connection")
             return
             return
-        
+
         async with self._lock:
         async with self._lock:
             try:
             try:
                 if self._client:
                 if self._client:
@@ -199,16 +201,13 @@ class TelegramService:
                         await self._client.disconnect()
                         await self._client.disconnect()
                     except Exception:
                     except Exception:
                         pass
                         pass
-                
+
                 self._client = TelegramClient(
                 self._client = TelegramClient(
-                    self.session_name,
-                    self.api_id,
-                    self.api_hash,
-                    proxy=self.proxy
+                    self.session_name, self.api_id, self.api_hash, proxy=self.proxy
                 )
                 )
-                
+
                 await self._client.connect()
                 await self._client.connect()
-                
+
                 if self.bot_token:
                 if self.bot_token:
                     # Bot mode
                     # Bot mode
                     await self._client.sign_in(bot_token=self.bot_token)
                     await self._client.sign_in(bot_token=self.bot_token)
@@ -229,9 +228,9 @@ class TelegramService:
                             "No bot_token or phone provided and no valid session exists"
                             "No bot_token or phone provided and no valid session exists"
                         )
                         )
                     logger.info("Connected using existing session")
                     logger.info("Connected using existing session")
-                
+
                 self._connected = True
                 self._connected = True
-                
+
             except errors.ApiIdInvalidError:
             except errors.ApiIdInvalidError:
                 raise TelegramConnectionError("Invalid API ID or Hash")
                 raise TelegramConnectionError("Invalid API ID or Hash")
             except errors.PhoneNumberInvalidError:
             except errors.PhoneNumberInvalidError:
@@ -239,7 +238,7 @@ class TelegramService:
             except Exception as e:
             except Exception as e:
                 self._connected = False
                 self._connected = False
                 raise TelegramConnectionError(f"Failed to connect: {e}") from e
                 raise TelegramConnectionError(f"Failed to connect: {e}") from e
-    
+
     async def disconnect(self) -> None:
     async def disconnect(self) -> None:
         """Disconnect from Telegram"""
         """Disconnect from Telegram"""
         if self._client:
         if self._client:
@@ -249,29 +248,7 @@ class TelegramService:
                 logger.info("Disconnected from Telegram")
                 logger.info("Disconnected from Telegram")
             except Exception as e:
             except Exception as e:
                 logger.error(f"Error disconnecting: {e}")
                 logger.error(f"Error disconnecting: {e}")
-    
-    async def health_check(self) -> dict[str, Any]:
-        """Check service health"""
-        status = {
-            "enabled": self.enabled,
-            "connected": self._connected,
-            "bot_mode": bool(self.bot_token),
-            "session": self.session_name,
-        }
-        
-        if self._client and self._connected:
-            try:
-                # Quick check
-                me = await self._client.get_me()
-                status["user_id"] = me.id
-                status["username"] = me.username
-            except Exception as e:
-                status["connected"] = False
-                status["error"] = str(e)
-                logger.warning(f"Health check failed: {e}")
-        
-        return status
-    
+
     @asynccontextmanager
     @asynccontextmanager
     async def session(self):
     async def session(self):
         """Context manager for Telegram session"""
         """Context manager for Telegram session"""
@@ -281,46 +258,46 @@ class TelegramService:
         except Exception as e:
         except Exception as e:
             logger.error(f"Error in Telegram session: {e}")
             logger.error(f"Error in Telegram session: {e}")
             raise
             raise
-    
+
     def _format_message(
     def _format_message(
         self,
         self,
         message: str,
         message: str,
         priority: NotificationPriority = NotificationPriority.NORMAL,
         priority: NotificationPriority = NotificationPriority.NORMAL,
         source: str = "SquidStats",
         source: str = "SquidStats",
         timestamp: bool = True,
         timestamp: bool = True,
-        extra_data: Optional[dict[str, Any]] = None
+        extra_data: dict[str, Any] | None = None,
     ) -> str:
     ) -> str:
         parts = [f"{priority.value} **{source}**\n"]
         parts = [f"{priority.value} **{source}**\n"]
-        
+
         if timestamp:
         if timestamp:
             time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
             time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
             parts.append(f"🕐 {time_str}\n")
             parts.append(f"🕐 {time_str}\n")
-        
+
         parts.append(f"\n{message}")
         parts.append(f"\n{message}")
-        
+
         if extra_data:
         if extra_data:
             parts.append("\n\n📊 **Detalles:**")
             parts.append("\n\n📊 **Detalles:**")
             for key, value in extra_data.items():
             for key, value in extra_data.items():
                 parts.append(f"\n• {key}: `{value}`")
                 parts.append(f"\n• {key}: `{value}`")
-        
+
         return "".join(parts)
         return "".join(parts)
-    
+
     async def _resolve_recipient(self, recipient: str | int) -> InputPeerUser | int:
     async def _resolve_recipient(self, recipient: str | int) -> InputPeerUser | int:
         if isinstance(recipient, int):
         if isinstance(recipient, int):
             return recipient
             return recipient
-        
+
         # Check cache
         # Check cache
         if recipient in self._recipients:
         if recipient in self._recipients:
             return self._recipients[recipient]
             return self._recipients[recipient]
-        
+
         # Resolve entity
         # Resolve entity
         try:
         try:
             async with self.session() as client:
             async with self.session() as client:
                 # Convert channel IDs to int for better resolution
                 # Convert channel IDs to int for better resolution
                 resolve_target = recipient
                 resolve_target = recipient
-                if isinstance(recipient, str) and recipient.startswith('-100'):
+                if isinstance(recipient, str) and recipient.startswith("-100"):
                     resolve_target = int(recipient)
                     resolve_target = int(recipient)
-                
+
                 entity = await client.get_entity(resolve_target)
                 entity = await client.get_entity(resolve_target)
                 if isinstance(entity, User):
                 if isinstance(entity, User):
                     self._recipients[recipient] = entity
                     self._recipients[recipient] = entity
@@ -328,7 +305,7 @@ class TelegramService:
         except Exception as e:
         except Exception as e:
             logger.error(f"Failed to resolve recipient {recipient}: {e}")
             logger.error(f"Failed to resolve recipient {recipient}: {e}")
             raise TelegramSendError(f"Invalid recipient: {recipient}") from e
             raise TelegramSendError(f"Invalid recipient: {recipient}") from e
-    
+
     @async_retry(max_attempts=3, delay=1.0, backoff=2.0)
     @async_retry(max_attempts=3, delay=1.0, backoff=2.0)
     async def send_notification(
     async def send_notification(
         self,
         self,
@@ -337,133 +314,119 @@ class TelegramService:
         priority: NotificationPriority = NotificationPriority.NORMAL,
         priority: NotificationPriority = NotificationPriority.NORMAL,
         source: str = "SquidStats",
         source: str = "SquidStats",
         parse_mode: str = "md",
         parse_mode: str = "md",
-        **kwargs
+        **kwargs,
     ) -> bool:
     ) -> bool:
         if not self.enabled:
         if not self.enabled:
             logger.debug("Telegram notifications disabled")
             logger.debug("Telegram notifications disabled")
             return False
             return False
-        
+
         try:
         try:
             formatted_message = self._format_message(
             formatted_message = self._format_message(
-                message,
-                priority=priority,
-                source=source,
-                **kwargs
+                message, priority=priority, source=source, **kwargs
             )
             )
-            
+
             entity = await self._resolve_recipient(recipient)
             entity = await self._resolve_recipient(recipient)
-            
+
             async with self.session() as client:
             async with self.session() as client:
                 await client.send_message(
                 await client.send_message(
-                    entity,
-                    formatted_message,
-                    parse_mode=parse_mode
+                    entity, formatted_message, parse_mode=parse_mode
                 )
                 )
-            
+
             logger.info(f"Notification sent to {recipient}")
             logger.info(f"Notification sent to {recipient}")
             return True
             return True
-            
+
         except TelegramSendError:
         except TelegramSendError:
             raise
             raise
         except Exception as e:
         except Exception as e:
             logger.error(f"Failed to send notification: {e}")
             logger.error(f"Failed to send notification: {e}")
             raise TelegramSendError(f"Send failed: {e}") from e
             raise TelegramSendError(f"Send failed: {e}") from e
-    
+
     async def send_bulk_notifications(
     async def send_bulk_notifications(
         self,
         self,
         recipients: list[str | int],
         recipients: list[str | int],
         message: str,
         message: str,
         priority: NotificationPriority = NotificationPriority.NORMAL,
         priority: NotificationPriority = NotificationPriority.NORMAL,
-        **kwargs
+        **kwargs,
     ) -> dict[str, bool]:
     ) -> dict[str, bool]:
         results = {}
         results = {}
-        
+
         for recipient in recipients:
         for recipient in recipients:
             try:
             try:
                 success = await self.send_notification(
                 success = await self.send_notification(
-                    recipient,
-                    message,
-                    priority=priority,
-                    **kwargs
+                    recipient, message, priority=priority, **kwargs
                 )
                 )
                 results[str(recipient)] = success
                 results[str(recipient)] = success
             except Exception as e:
             except Exception as e:
                 logger.error(f"Failed to send to {recipient}: {e}")
                 logger.error(f"Failed to send to {recipient}: {e}")
                 results[str(recipient)] = False
                 results[str(recipient)] = False
-        
+
         return results
         return results
-    
+
     async def send_security_alert(
     async def send_security_alert(
-        self,
-        recipient: str | int,
-        alert_type: str,
-        details: dict[str, Any]
+        self, recipient: str | int, alert_type: str, details: dict[str, Any]
     ) -> bool:
     ) -> bool:
         message = f"🔐 **Alerta de Seguridad: {alert_type}**"
         message = f"🔐 **Alerta de Seguridad: {alert_type}**"
-        
+
         return await self.send_notification(
         return await self.send_notification(
             recipient,
             recipient,
             message,
             message,
             priority=NotificationPriority.CRITICAL,
             priority=NotificationPriority.CRITICAL,
             source="Security Monitor",
             source="Security Monitor",
-            extra_data=details
+            extra_data=details,
         )
         )
-    
+
     async def send_system_alert(
     async def send_system_alert(
         self,
         self,
         recipient: str | int,
         recipient: str | int,
         alert_message: str,
         alert_message: str,
-        metrics: Optional[dict[str, Any]] = None
+        metrics: dict[str, Any] | None = None,
     ) -> bool:
     ) -> bool:
         return await self.send_notification(
         return await self.send_notification(
             recipient,
             recipient,
             alert_message,
             alert_message,
             priority=NotificationPriority.HIGH,
             priority=NotificationPriority.HIGH,
             source="System Monitor",
             source="System Monitor",
-            extra_data=metrics
+            extra_data=metrics,
         )
         )
-    
+
     async def send_user_activity_alert(
     async def send_user_activity_alert(
-        self,
-        recipient: str | int,
-        username: str,
-        activity_data: dict[str, Any]
+        self, recipient: str | int, username: str, activity_data: dict[str, Any]
     ) -> bool:
     ) -> bool:
         message = f"👤 **Alta actividad detectada: {username}**"
         message = f"👤 **Alta actividad detectada: {username}**"
-        
+
         return await self.send_notification(
         return await self.send_notification(
             recipient,
             recipient,
             message,
             message,
             priority=NotificationPriority.HIGH,
             priority=NotificationPriority.HIGH,
             source="User Monitor",
             source="User Monitor",
-            extra_data=activity_data
+            extra_data=activity_data,
         )
         )
-    
+
     async def health_check(self) -> dict[str, Any]:
     async def health_check(self) -> dict[str, Any]:
         status = {
         status = {
             "enabled": self.enabled,
             "enabled": self.enabled,
             "connected": False,
             "connected": False,
             "bot_mode": bool(self.bot_token),
             "bot_mode": bool(self.bot_token),
             "session": self.session_name,
             "session": self.session_name,
-            "error": None
+            "error": None,
         }
         }
-        
+
         if not self.enabled:
         if not self.enabled:
             return status
             return status
-        
+
         try:
         try:
             await self._ensure_connected()
             await self._ensure_connected()
             async with self.session() as client:
             async with self.session() as client:
                 me = await client.get_me()
                 me = await client.get_me()
                 status["connected"] = True
                 status["connected"] = True
                 status["user_id"] = me.id
                 status["user_id"] = me.id
-                status["username"] = getattr(me, 'username', None)
+                status["username"] = getattr(me, "username", None)
         except Exception as e:
         except Exception as e:
             status["error"] = str(e)
             status["error"] = str(e)
             logger.error(f"Health check failed: {e}")
             logger.error(f"Health check failed: {e}")
-        
+
         return status
         return status
-    
+
     def __del__(self):
     def __del__(self):
         """Cleanup on deletion"""
         """Cleanup on deletion"""
         if self._client and self._connected:
         if self._client and self._connected:
@@ -476,47 +439,44 @@ class TelegramService:
 
 
 
 
 # Singleton instance
 # Singleton instance
-_telegram_service: Optional[TelegramService] = None
+_telegram_service: TelegramService | None = None
 
 
 
 
 def get_telegram_service(
 def get_telegram_service(
-    api_id: Optional[int] = None,
-    api_hash: Optional[str] = None,
-    proxy: Optional[dict[str, Any]] = None,
-    **kwargs
+    api_id: int | None = None,
+    api_hash: str | None = None,
+    proxy: dict[str, Any] | None = None,
+    **kwargs,
 ) -> TelegramService:
 ) -> TelegramService:
     """
     """
     Get or create TelegramService singleton instance
     Get or create TelegramService singleton instance
-    
+
     Args:
     Args:
         api_id: Telegram API ID (required on first call)
         api_id: Telegram API ID (required on first call)
         api_hash: Telegram API Hash (required on first call)
         api_hash: Telegram API Hash (required on first call)
         proxy: Proxy configuration dict for Telethon
         proxy: Proxy configuration dict for Telethon
         **kwargs: Additional parameters for TelegramService
         **kwargs: Additional parameters for TelegramService
-    
+
     Returns:
     Returns:
         TelegramService instance
         TelegramService instance
     """
     """
     global _telegram_service
     global _telegram_service
-    
+
     if _telegram_service is None:
     if _telegram_service is None:
         if api_id is None or api_hash is None:
         if api_id is None or api_hash is None:
             raise ValueError("api_id and api_hash required for first initialization")
             raise ValueError("api_id and api_hash required for first initialization")
-        
+
         _telegram_service = TelegramService(
         _telegram_service = TelegramService(
-            api_id=api_id,
-            api_hash=api_hash,
-            proxy=proxy,
-            **kwargs
+            api_id=api_id, api_hash=api_hash, proxy=proxy, **kwargs
         )
         )
-    
+
     return _telegram_service
     return _telegram_service
 
 
 
 
 async def cleanup_telegram_service():
 async def cleanup_telegram_service():
     """Cleanup Telegram service on shutdown"""
     """Cleanup Telegram service on shutdown"""
     global _telegram_service
     global _telegram_service
-    
+
     if _telegram_service:
     if _telegram_service:
         await _telegram_service.disconnect()
         await _telegram_service.disconnect()
         _telegram_service = None
         _telegram_service = None

+ 1 - 1
tests/__init__.py

@@ -1 +1 @@
-# Tests package
+# Tests package

+ 132 - 114
tests/test_telegram_integration.py

@@ -5,32 +5,31 @@ Ejecutar: python test_telegram_integration.py
 """
 """
 
 
 import asyncio
 import asyncio
-import os
 import sys
 import sys
 from pathlib import Path
 from pathlib import Path
 
 
 # Agregar el directorio raíz al path
 # Agregar el directorio raíz al path
 sys.path.insert(0, str(Path(__file__).parent.parent))
 sys.path.insert(0, str(Path(__file__).parent.parent))
 
 
+# Import dotenv and load before other project imports
 from dotenv import load_dotenv
 from dotenv import load_dotenv
 
 
-# Cargar variables de entorno
 load_dotenv()
 load_dotenv()
 
 
-from config import Config
-from services.telegram_service import (
-    NotificationPriority,
-    TelegramService,
-    get_telegram_service,
-    parse_http_proxy_url,
-)
-from services.telegram_integration import (
+# Now import project modules (they may depend on env vars)
+from config import Config  # noqa: E402
+from services.telegram_integration import (  # noqa: E402
     initialize_telegram_service,
     initialize_telegram_service,
-    telegram_health_check,
-    send_telegram_notification,
     send_security_alert_telegram,
     send_security_alert_telegram,
     send_system_alert_telegram,
     send_system_alert_telegram,
+    send_telegram_notification,
     send_user_activity_alert_telegram,
     send_user_activity_alert_telegram,
+    telegram_health_check,
+)
+from services.telegram_service import (  # noqa: E402
+    NotificationPriority,
+    get_telegram_service,
+    parse_http_proxy_url,
 )
 )
 
 
 
 
@@ -46,34 +45,46 @@ def print_separator(title=""):
 def check_configuration():
 def check_configuration():
     """Verificar configuración de Telegram"""
     """Verificar configuración de Telegram"""
     print_separator("Verificación de Configuración")
     print_separator("Verificación de Configuración")
-    
+
     print(f"TELEGRAM_ENABLED: {Config.TELEGRAM_ENABLED}")
     print(f"TELEGRAM_ENABLED: {Config.TELEGRAM_ENABLED}")
-    print(f"TELEGRAM_API_ID: {'✓ Configurado' if Config.TELEGRAM_API_ID else '✗ No configurado'}")
-    print(f"TELEGRAM_API_HASH: {'✓ Configurado' if Config.TELEGRAM_API_HASH else '✗ No configurado'}")
-    print(f"TELEGRAM_BOT_TOKEN: {'✓ Configurado' if Config.TELEGRAM_BOT_TOKEN else '✗ No configurado'}")
-    print(f"TELEGRAM_PHONE: {'✓ Configurado' if Config.TELEGRAM_PHONE else '✗ No configurado'}")
+    print(
+        f"TELEGRAM_API_ID: {'✓ Configurado' if Config.TELEGRAM_API_ID else '✗ No configurado'}"
+    )
+    print(
+        f"TELEGRAM_API_HASH: {'✓ Configurado' if Config.TELEGRAM_API_HASH else '✗ No configurado'}"
+    )
+    print(
+        f"TELEGRAM_BOT_TOKEN: {'✓ Configurado' if Config.TELEGRAM_BOT_TOKEN else '✗ No configurado'}"
+    )
+    print(
+        f"TELEGRAM_PHONE: {'✓ Configurado' if Config.TELEGRAM_PHONE else '✗ No configurado'}"
+    )
     print(f"TELEGRAM_SESSION_NAME: {Config.TELEGRAM_SESSION_NAME}")
     print(f"TELEGRAM_SESSION_NAME: {Config.TELEGRAM_SESSION_NAME}")
-    print(f"TELEGRAM_RECIPIENTS: {Config.TELEGRAM_RECIPIENTS if Config.TELEGRAM_RECIPIENTS else '✗ No configurado'}")
-    
+    print(
+        f"TELEGRAM_RECIPIENTS: {Config.TELEGRAM_RECIPIENTS if Config.TELEGRAM_RECIPIENTS else '✗ No configurado'}"
+    )
+
     if not Config.TELEGRAM_ENABLED:
     if not Config.TELEGRAM_ENABLED:
         print("\n⚠️ TELEGRAM_ENABLED=false - Habilita en el archivo .env")
         print("\n⚠️ TELEGRAM_ENABLED=false - Habilita en el archivo .env")
         return False
         return False
-    
+
     if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
     if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
         print("\n❌ Faltan credenciales de API")
         print("\n❌ Faltan credenciales de API")
         print("   Obtén tus credenciales en: https://my.telegram.org/apps")
         print("   Obtén tus credenciales en: https://my.telegram.org/apps")
         return False
         return False
-    
+
     if not Config.TELEGRAM_BOT_TOKEN and not Config.TELEGRAM_PHONE:
     if not Config.TELEGRAM_BOT_TOKEN and not Config.TELEGRAM_PHONE:
         print("\n❌ Falta BOT_TOKEN o PHONE")
         print("\n❌ Falta BOT_TOKEN o PHONE")
         print("   Configura TELEGRAM_BOT_TOKEN o TELEGRAM_PHONE")
         print("   Configura TELEGRAM_BOT_TOKEN o TELEGRAM_PHONE")
         return False
         return False
-    
-    if not Config.TELEGRAM_RECIPIENTS or not any(r.strip() for r in Config.TELEGRAM_RECIPIENTS):
+
+    if not Config.TELEGRAM_RECIPIENTS or not any(
+        r.strip() for r in Config.TELEGRAM_RECIPIENTS
+    ):
         print("\n❌ Faltan destinatarios")
         print("\n❌ Faltan destinatarios")
         print("   Configura TELEGRAM_RECIPIENTS en el archivo .env")
         print("   Configura TELEGRAM_RECIPIENTS en el archivo .env")
         return False
         return False
-    
+
     print("\n✅ Configuración completa")
     print("\n✅ Configuración completa")
     return True
     return True
 
 
@@ -81,7 +92,7 @@ def check_configuration():
 async def test_connection():
 async def test_connection():
     """Probar conexión a Telegram"""
     """Probar conexión a Telegram"""
     print_separator("Test de Conexión")
     print_separator("Test de Conexión")
-    
+
     try:
     try:
         service = get_telegram_service(
         service = get_telegram_service(
             api_id=int(Config.TELEGRAM_API_ID),
             api_id=int(Config.TELEGRAM_API_ID),
@@ -89,37 +100,38 @@ async def test_connection():
             bot_token=Config.TELEGRAM_BOT_TOKEN,
             bot_token=Config.TELEGRAM_BOT_TOKEN,
             phone=Config.TELEGRAM_PHONE,
             phone=Config.TELEGRAM_PHONE,
             session_name=Config.TELEGRAM_SESSION_NAME,
             session_name=Config.TELEGRAM_SESSION_NAME,
-            enabled=Config.TELEGRAM_ENABLED
+            enabled=Config.TELEGRAM_ENABLED,
         )
         )
-        
+
         print("Conectando a Telegram...")
         print("Conectando a Telegram...")
         await service.connect()
         await service.connect()
         print("✅ Conexión establecida")
         print("✅ Conexión establecida")
-        
+
         print("\nObteniendo información de la cuenta...")
         print("\nObteniendo información de la cuenta...")
         health = await service.health_check()
         health = await service.health_check()
-        
-        print(f"\n📊 Estado del servicio:")
+
+        print("\n📊 Estado del servicio:")
         print(f"   Habilitado: {health['enabled']}")
         print(f"   Habilitado: {health['enabled']}")
         print(f"   Conectado: {health['connected']}")
         print(f"   Conectado: {health['connected']}")
         print(f"   Modo Bot: {health['bot_mode']}")
         print(f"   Modo Bot: {health['bot_mode']}")
         print(f"   Sesión: {health['session']}")
         print(f"   Sesión: {health['session']}")
-        
-        if health['connected']:
+
+        if health["connected"]:
             print(f"   User ID: {health.get('user_id', 'N/A')}")
             print(f"   User ID: {health.get('user_id', 'N/A')}")
             print(f"   Username: {health.get('username', 'N/A')}")
             print(f"   Username: {health.get('username', 'N/A')}")
             print("\n✅ Test de conexión exitoso")
             print("\n✅ Test de conexión exitoso")
         else:
         else:
-            error = health.get('error', 'Unknown error')
+            error = health.get("error", "Unknown error")
             print(f"\n❌ No se pudo conectar: {error}")
             print(f"\n❌ No se pudo conectar: {error}")
             return False
             return False
-        
+
         await service.disconnect()
         await service.disconnect()
         return True
         return True
-        
+
     except Exception as e:
     except Exception as e:
         print(f"\n❌ Error en test de conexión: {e}")
         print(f"\n❌ Error en test de conexión: {e}")
         import traceback
         import traceback
+
         traceback.print_exc()
         traceback.print_exc()
         return False
         return False
 
 
@@ -127,34 +139,35 @@ async def test_connection():
 async def test_send_basic_notification():
 async def test_send_basic_notification():
     """Probar envío de notificación básica"""
     """Probar envío de notificación básica"""
     print_separator("Test de Notificación Básica")
     print_separator("Test de Notificación Básica")
-    
+
     try:
     try:
         service = get_telegram_service()
         service = get_telegram_service()
         await service.connect()
         await service.connect()
-        
+
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipient = recipients[0]
         recipient = recipients[0]
-        
+
         print(f"Enviando notificación de prueba a: {recipient}")
         print(f"Enviando notificación de prueba a: {recipient}")
-        
+
         success = await service.send_notification(
         success = await service.send_notification(
             recipient=recipient,
             recipient=recipient,
             message="🧪 Test de notificación desde SquidStats\n\nSi recibes este mensaje, la integración funciona correctamente.",
             message="🧪 Test de notificación desde SquidStats\n\nSi recibes este mensaje, la integración funciona correctamente.",
             priority=NotificationPriority.NORMAL,
             priority=NotificationPriority.NORMAL,
-            source="Test Suite"
+            source="Test Suite",
         )
         )
-        
+
         if success:
         if success:
             print("✅ Notificación enviada exitosamente")
             print("✅ Notificación enviada exitosamente")
         else:
         else:
             print("❌ No se pudo enviar la notificación")
             print("❌ No se pudo enviar la notificación")
-        
+
         await service.disconnect()
         await service.disconnect()
         return success
         return success
-        
+
     except Exception as e:
     except Exception as e:
         print(f"❌ Error enviando notificación: {e}")
         print(f"❌ Error enviando notificación: {e}")
         import traceback
         import traceback
+
         traceback.print_exc()
         traceback.print_exc()
         return False
         return False
 
 
@@ -162,35 +175,35 @@ async def test_send_basic_notification():
 async def test_priority_notifications():
 async def test_priority_notifications():
     """Probar notificaciones con diferentes prioridades"""
     """Probar notificaciones con diferentes prioridades"""
     print_separator("Test de Prioridades")
     print_separator("Test de Prioridades")
-    
+
     try:
     try:
         service = get_telegram_service()
         service = get_telegram_service()
         await service.connect()
         await service.connect()
-        
+
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipient = recipients[0]
         recipient = recipients[0]
-        
+
         priorities = [
         priorities = [
             (NotificationPriority.LOW, "Información de baja prioridad"),
             (NotificationPriority.LOW, "Información de baja prioridad"),
             (NotificationPriority.NORMAL, "Notificación estándar"),
             (NotificationPriority.NORMAL, "Notificación estándar"),
             (NotificationPriority.HIGH, "Advertencia importante"),
             (NotificationPriority.HIGH, "Advertencia importante"),
-            (NotificationPriority.CRITICAL, "¡Alerta crítica!")
+            (NotificationPriority.CRITICAL, "¡Alerta crítica!"),
         ]
         ]
-        
+
         for priority, message in priorities:
         for priority, message in priorities:
             print(f"Enviando {priority.name}...")
             print(f"Enviando {priority.name}...")
             await service.send_notification(
             await service.send_notification(
                 recipient=recipient,
                 recipient=recipient,
                 message=message,
                 message=message,
                 priority=priority,
                 priority=priority,
-                source="Priority Test"
+                source="Priority Test",
             )
             )
             await asyncio.sleep(1)  # Evitar rate limiting
             await asyncio.sleep(1)  # Evitar rate limiting
-        
+
         print("✅ Todas las prioridades enviadas")
         print("✅ Todas las prioridades enviadas")
         await service.disconnect()
         await service.disconnect()
         return True
         return True
-        
+
     except Exception as e:
     except Exception as e:
         print(f"❌ Error en test de prioridades: {e}")
         print(f"❌ Error en test de prioridades: {e}")
         return False
         return False
@@ -199,14 +212,14 @@ async def test_priority_notifications():
 async def test_formatted_notifications():
 async def test_formatted_notifications():
     """Probar notificaciones con datos extra"""
     """Probar notificaciones con datos extra"""
     print_separator("Test de Mensajes Formateados")
     print_separator("Test de Mensajes Formateados")
-    
+
     try:
     try:
         service = get_telegram_service()
         service = get_telegram_service()
         await service.connect()
         await service.connect()
-        
+
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipient = recipients[0]
         recipient = recipients[0]
-        
+
         print("Enviando notificación con metadata...")
         print("Enviando notificación con metadata...")
         await service.send_notification(
         await service.send_notification(
             recipient=recipient,
             recipient=recipient,
@@ -217,14 +230,14 @@ async def test_formatted_notifications():
                 "CPU": "85%",
                 "CPU": "85%",
                 "RAM": "7.2 GB / 16 GB",
                 "RAM": "7.2 GB / 16 GB",
                 "Disco": "45.3 GB disponibles",
                 "Disco": "45.3 GB disponibles",
-                "Uptime": "5 días, 3 horas"
-            }
+                "Uptime": "5 días, 3 horas",
+            },
         )
         )
-        
+
         print("✅ Notificación formateada enviada")
         print("✅ Notificación formateada enviada")
         await service.disconnect()
         await service.disconnect()
         return True
         return True
-        
+
     except Exception as e:
     except Exception as e:
         print(f"❌ Error en test de formato: {e}")
         print(f"❌ Error en test de formato: {e}")
         return False
         return False
@@ -233,7 +246,7 @@ async def test_formatted_notifications():
 def test_integration_wrapper():
 def test_integration_wrapper():
     """Probar wrapper de integración (funciones síncronas)"""
     """Probar wrapper de integración (funciones síncronas)"""
     print_separator("Test de Wrapper de Integración")
     print_separator("Test de Wrapper de Integración")
-    
+
     try:
     try:
         # Inicializar servicio
         # Inicializar servicio
         print("Inicializando servicio de Telegram...")
         print("Inicializando servicio de Telegram...")
@@ -241,72 +254,69 @@ def test_integration_wrapper():
             print("❌ No se pudo inicializar el servicio")
             print("❌ No se pudo inicializar el servicio")
             return False
             return False
         print("✅ Servicio inicializado")
         print("✅ Servicio inicializado")
-        
+
         # Health check
         # Health check
         print("\nVerificando estado...")
         print("\nVerificando estado...")
         health = telegram_health_check()
         health = telegram_health_check()
         print(f"Estado: {health}")
         print(f"Estado: {health}")
-        
-        if not health.get('connected'):
+
+        if not health.get("connected"):
             print("⚠️ No conectado - algunas funciones no estarán disponibles")
             print("⚠️ No conectado - algunas funciones no estarán disponibles")
-        
+
         # Enviar notificación genérica
         # Enviar notificación genérica
         print("\nEnviando notificación genérica...")
         print("\nEnviando notificación genérica...")
         success1 = send_telegram_notification(
         success1 = send_telegram_notification(
-            notification_type='info',
-            message='Test de integración wrapper',
-            source='Integration Test'
+            notification_type="info",
+            message="Test de integración wrapper",
+            source="Integration Test",
         )
         )
         print(f"Resultado: {'✅ Enviado' if success1 else '❌ Fallo'}")
         print(f"Resultado: {'✅ Enviado' if success1 else '❌ Fallo'}")
-        
+
         # Enviar alerta de seguridad
         # Enviar alerta de seguridad
         print("\nEnviando alerta de seguridad...")
         print("\nEnviando alerta de seguridad...")
         success2 = send_security_alert_telegram(
         success2 = send_security_alert_telegram(
-            alert_type='Acceso sospechoso detectado',
+            alert_type="Acceso sospechoso detectado",
             details={
             details={
-                'IP': '192.168.1.100',
-                'Usuario': 'test_user',
-                'Timestamp': '2026-01-17 15:00:00'
-            }
+                "IP": "192.168.1.100",
+                "Usuario": "test_user",
+                "Timestamp": "2026-01-17 15:00:00",
+            },
         )
         )
         print(f"Resultado: {'✅ Enviado' if success2 else '❌ Fallo'}")
         print(f"Resultado: {'✅ Enviado' if success2 else '❌ Fallo'}")
-        
+
         # Enviar alerta del sistema
         # Enviar alerta del sistema
         print("\nEnviando alerta del sistema...")
         print("\nEnviando alerta del sistema...")
         success3 = send_system_alert_telegram(
         success3 = send_system_alert_telegram(
-            alert_message='Uso elevado de recursos detectado',
-            metrics={
-                'CPU': '92%',
-                'Memoria': '14.8 GB / 16 GB',
-                'Temperatura': '78°C'
-            }
+            alert_message="Uso elevado de recursos detectado",
+            metrics={"CPU": "92%", "Memoria": "14.8 GB / 16 GB", "Temperatura": "78°C"},
         )
         )
         print(f"Resultado: {'✅ Enviado' if success3 else '❌ Fallo'}")
         print(f"Resultado: {'✅ Enviado' if success3 else '❌ Fallo'}")
-        
+
         # Enviar alerta de actividad de usuario
         # Enviar alerta de actividad de usuario
         print("\nEnviando alerta de actividad de usuario...")
         print("\nEnviando alerta de actividad de usuario...")
         success4 = send_user_activity_alert_telegram(
         success4 = send_user_activity_alert_telegram(
-            username='john_doe',
+            username="john_doe",
             activity_data={
             activity_data={
-                'Requests': '1,234',
-                'Datos descargados': '45.3 GB',
-                'Sitios únicos': '87'
-            }
+                "Requests": "1,234",
+                "Datos descargados": "45.3 GB",
+                "Sitios únicos": "87",
+            },
         )
         )
         print(f"Resultado: {'✅ Enviado' if success4 else '❌ Fallo'}")
         print(f"Resultado: {'✅ Enviado' if success4 else '❌ Fallo'}")
-        
+
         all_success = all([success1, success2, success3, success4])
         all_success = all([success1, success2, success3, success4])
-        
+
         if all_success:
         if all_success:
             print("\n✅ Todos los tests del wrapper exitosos")
             print("\n✅ Todos los tests del wrapper exitosos")
         else:
         else:
             print("\n⚠️ Algunos tests fallaron")
             print("\n⚠️ Algunos tests fallaron")
-        
+
         return all_success
         return all_success
-        
+
     except Exception as e:
     except Exception as e:
         print(f"\n❌ Error en test de wrapper: {e}")
         print(f"\n❌ Error en test de wrapper: {e}")
         import traceback
         import traceback
+
         traceback.print_exc()
         traceback.print_exc()
         return False
         return False
 
 
@@ -314,44 +324,47 @@ def test_integration_wrapper():
 async def run_async_tests():
 async def run_async_tests():
     """Ejecutar tests asíncronos"""
     """Ejecutar tests asíncronos"""
     results = []
     results = []
-    
+
     # Test de conexión
     # Test de conexión
     results.append(await test_connection())
     results.append(await test_connection())
     await asyncio.sleep(2)
     await asyncio.sleep(2)
-    
+
     # Test de notificación básica
     # Test de notificación básica
     results.append(await test_send_basic_notification())
     results.append(await test_send_basic_notification())
     await asyncio.sleep(2)
     await asyncio.sleep(2)
-    
+
     # Test de prioridades
     # Test de prioridades
     results.append(await test_priority_notifications())
     results.append(await test_priority_notifications())
     await asyncio.sleep(2)
     await asyncio.sleep(2)
-    
+
     # Test de formato
     # Test de formato
     results.append(await test_formatted_notifications())
     results.append(await test_formatted_notifications())
-    
+
     return results
     return results
 
 
 
 
 def test_proxy_parsing():
 def test_proxy_parsing():
     """Test parsing de URLs de proxy HTTP"""
     """Test parsing de URLs de proxy HTTP"""
     print_separator("🧪 Test de Parsing de Proxy")
     print_separator("🧪 Test de Parsing de Proxy")
-    
+
     test_cases = [
     test_cases = [
         # (input, expected_output_keys)
         # (input, expected_output_keys)
         ("", None),
         ("", None),
         ("http://proxy.example.com:8080", ["proxy_type", "addr", "port"]),
         ("http://proxy.example.com:8080", ["proxy_type", "addr", "port"]),
-        ("http://user:pass@proxy.example.com:8080", ["proxy_type", "addr", "port", "username", "password"]),
+        (
+            "http://user:pass@proxy.example.com:8080",
+            ["proxy_type", "addr", "port", "username", "password"],
+        ),
         ("https://proxy.example.com:8080", None),  # Solo HTTP soportado
         ("https://proxy.example.com:8080", None),  # Solo HTTP soportado
         ("invalid-url", None),
         ("invalid-url", None),
     ]
     ]
-    
+
     all_passed = True
     all_passed = True
-    
+
     for i, (proxy_url, expected_keys) in enumerate(test_cases, 1):
     for i, (proxy_url, expected_keys) in enumerate(test_cases, 1):
         try:
         try:
             result = parse_http_proxy_url(proxy_url)
             result = parse_http_proxy_url(proxy_url)
-            
+
             if expected_keys is None:
             if expected_keys is None:
                 if result is None:
                 if result is None:
                     print(f"✅ Test {i}: '{proxy_url}' → None (correcto)")
                     print(f"✅ Test {i}: '{proxy_url}' → None (correcto)")
@@ -362,44 +375,46 @@ def test_proxy_parsing():
                 if result and all(key in result for key in expected_keys):
                 if result and all(key in result for key in expected_keys):
                     print(f"✅ Test {i}: '{proxy_url}' → {result}")
                     print(f"✅ Test {i}: '{proxy_url}' → {result}")
                 else:
                 else:
-                    print(f"❌ Test {i}: '{proxy_url}' → {result} (faltan keys: {expected_keys})")
+                    print(
+                        f"❌ Test {i}: '{proxy_url}' → {result} (faltan keys: {expected_keys})"
+                    )
                     all_passed = False
                     all_passed = False
-                    
+
         except Exception as e:
         except Exception as e:
             print(f"❌ Test {i}: Error parsing '{proxy_url}': {e}")
             print(f"❌ Test {i}: Error parsing '{proxy_url}': {e}")
             all_passed = False
             all_passed = False
-    
+
     if all_passed:
     if all_passed:
         print("\n✅ Todos los tests de proxy pasaron")
         print("\n✅ Todos los tests de proxy pasaron")
     else:
     else:
         print("\n❌ Algunos tests de proxy fallaron")
         print("\n❌ Algunos tests de proxy fallaron")
-    
+
     return all_passed
     return all_passed
 
 
 
 
 def main():
 def main():
     """Función principal"""
     """Función principal"""
     print_separator("🧪 Test de Integración de Telegram")
     print_separator("🧪 Test de Integración de Telegram")
-    
+
     # Verificar configuración
     # Verificar configuración
     if not check_configuration():
     if not check_configuration():
         print("\n❌ Configuración incompleta. Corrige los errores y vuelve a intentar.")
         print("\n❌ Configuración incompleta. Corrige los errores y vuelve a intentar.")
         sys.exit(1)
         sys.exit(1)
-    
+
     # Test de parsing de proxy
     # Test de parsing de proxy
     proxy_test_passed = test_proxy_parsing()
     proxy_test_passed = test_proxy_parsing()
-    
+
     # Ejecutar tests asíncronos
     # Ejecutar tests asíncronos
     print("\n🚀 Iniciando tests asíncronos...")
     print("\n🚀 Iniciando tests asíncronos...")
     async_results = asyncio.run(run_async_tests())
     async_results = asyncio.run(run_async_tests())
-    
+
     # Ejecutar tests síncronos (wrapper)
     # Ejecutar tests síncronos (wrapper)
     print("\n🚀 Iniciando tests de wrapper...")
     print("\n🚀 Iniciando tests de wrapper...")
     sync_result = test_integration_wrapper()
     sync_result = test_integration_wrapper()
-    
+
     # Resumen
     # Resumen
     print_separator("📊 Resumen de Tests")
     print_separator("📊 Resumen de Tests")
-    
+
     tests = [
     tests = [
         ("Parsing de Proxy", proxy_test_passed),
         ("Parsing de Proxy", proxy_test_passed),
         ("Conexión", async_results[0] if len(async_results) > 0 else False),
         ("Conexión", async_results[0] if len(async_results) > 0 else False),
@@ -408,18 +423,20 @@ def main():
         ("Formato", async_results[3] if len(async_results) > 3 else False),
         ("Formato", async_results[3] if len(async_results) > 3 else False),
         ("Wrapper de integración", sync_result),
         ("Wrapper de integración", sync_result),
     ]
     ]
-    
+
     for test_name, result in tests:
     for test_name, result in tests:
         status = "✅ PASS" if result else "❌ FAIL"
         status = "✅ PASS" if result else "❌ FAIL"
         print(f"{status} - {test_name}")
         print(f"{status} - {test_name}")
-    
+
     total = len(tests)
     total = len(tests)
     passed = sum(1 for _, result in tests if result)
     passed = sum(1 for _, result in tests if result)
-    
+
     print(f"\n📈 Resultados: {passed}/{total} tests exitosos")
     print(f"\n📈 Resultados: {passed}/{total} tests exitosos")
-    
+
     if passed == total:
     if passed == total:
-        print("\n🎉 ¡Todos los tests pasaron! La integración de Telegram está funcionando correctamente.")
+        print(
+            "\n🎉 ¡Todos los tests pasaron! La integración de Telegram está funcionando correctamente."
+        )
         return 0
         return 0
     else:
     else:
         print("\n⚠️ Algunos tests fallaron. Revisa los logs para más detalles.")
         print("\n⚠️ Algunos tests fallaron. Revisa los logs para más detalles.")
@@ -436,5 +453,6 @@ if __name__ == "__main__":
     except Exception as e:
     except Exception as e:
         print(f"\n\n❌ Error fatal: {e}")
         print(f"\n\n❌ Error fatal: {e}")
         import traceback
         import traceback
+
         traceback.print_exc()
         traceback.print_exc()
         sys.exit(1)
         sys.exit(1)