Kaynağa Gözat

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 ay önce
ebeveyn
işleme
0878b2ba3e

+ 2 - 1
app.py

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

+ 3 - 1
config.py

@@ -62,7 +62,9 @@ class Config:
     TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
     TELEGRAM_SESSION_NAME = os.getenv("TELEGRAM_SESSION_NAME", "squidstats_bot")
     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
     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)
 try:
     from services.telegram_integration import send_telegram_notification
+
     TELEGRAM_AVAILABLE = True
 except Exception as e:
     logger.debug(f"Telegram integration not available: {e}")
@@ -219,14 +220,12 @@ def add_notification(
                     "unread_count": unread_count,
                 },
             )
-        
+
         # Send to Telegram if enabled and requested
         if send_telegram and TELEGRAM_AVAILABLE and send_telegram_notification:
             try:
                 send_telegram_notification(
-                    notification_type=notification_type,
-                    message=message,
-                    source=source
+                    notification_type=notification_type, message=message, source=source
                 )
             except Exception as e:
                 logger.error(f"Failed to send Telegram notification: {e}")
@@ -468,7 +467,6 @@ def check_system_health():
 def has_remote_commits_with_messages(
     repo_path: str, branch: str = "main"
 ) -> tuple[bool, list[str]]:
-    
     git_dir = os.path.join(repo_path, ".git")
     if not os.path.isdir(git_dir):
         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 logging
+from collections.abc import Callable
 from concurrent.futures import ThreadPoolExecutor
 from functools import wraps
-from typing import Any, Callable, Optional
+from typing import Any
 
 from config import Config
 from services.telegram_service import (
@@ -21,7 +22,7 @@ logger = logging.getLogger(__name__)
 
 # Thread pool for async execution
 _executor = ThreadPoolExecutor(max_workers=2)
-_telegram_service: Optional[TelegramService] = None
+_telegram_service: TelegramService | None = None
 
 
 def run_async(coro):
@@ -54,41 +55,39 @@ def async_to_sync(async_func: Callable) -> Callable:
     Decorator to convert async function to sync
     Runs async function in thread pool to avoid blocking
     """
+
     @wraps(async_func)
     def wrapper(*args, **kwargs):
         # 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 wrapper
 
 
 def initialize_telegram_service() -> bool:
     """
     Initialize Telegram service with config
-    
+
     Returns:
         True if initialized successfully
     """
     global _telegram_service
-    
+
     if not Config.TELEGRAM_ENABLED:
         logger.info("Telegram notifications disabled in config")
         return False
-    
+
     if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
         logger.warning(
             "Telegram API credentials not configured. "
             "Set TELEGRAM_API_ID and TELEGRAM_API_HASH in environment."
         )
         return False
-    
+
     try:
         api_id = int(Config.TELEGRAM_API_ID)
-        
+
         # Configure proxy if available
         proxy_config = None
         if Config.HTTP_PROXY:
@@ -97,7 +96,7 @@ def initialize_telegram_service() -> bool:
                 logger.info(f"Using HTTP proxy: {Config.HTTP_PROXY}")
             else:
                 logger.warning(f"Invalid proxy URL: {Config.HTTP_PROXY}")
-        
+
         _telegram_service = get_telegram_service(
             api_id=api_id,
             api_hash=Config.TELEGRAM_API_HASH,
@@ -105,12 +104,12 @@ def initialize_telegram_service() -> bool:
             session_name=Config.TELEGRAM_SESSION_NAME,
             phone=Config.TELEGRAM_PHONE,
             enabled=Config.TELEGRAM_ENABLED,
-            proxy=proxy_config
+            proxy=proxy_config,
         )
-        
+
         logger.info("Telegram service initialized successfully")
         return True
-        
+
     except ValueError as e:
         logger.error(f"Invalid Telegram API ID: {e}")
         return False
@@ -122,44 +121,44 @@ def initialize_telegram_service() -> bool:
 def map_notification_type_to_priority(notification_type: str) -> NotificationPriority:
     """
     Map notification type to Telegram priority
-    
+
     Args:
         notification_type: Notification type from the system
-    
+
     Returns:
         NotificationPriority enum value
     """
     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)
 
 
 def map_source_to_emoji(source: str) -> str:
     """
     Map notification source to emoji
-    
+
     Args:
         source: Notification source
-    
+
     Returns:
         Emoji string
     """
     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
@@ -167,48 +166,48 @@ async def send_telegram_notification(
     notification_type: str,
     message: str,
     source: str = "system",
-    extra_data: Optional[dict[str, Any]] = None
+    extra_data: dict[str, Any] | None = None,
 ) -> bool:
     """
     Send notification to all configured Telegram recipients
-    
+
     Args:
         notification_type: Type of notification ('info', 'warning', 'error', 'success')
         message: Notification message
         source: Source of the notification
         extra_data: Additional data to include
-    
+
     Returns:
         True if sent to at least one recipient
     """
     if not _telegram_service or not Config.TELEGRAM_ENABLED:
         return False
-    
+
     if not Config.TELEGRAM_RECIPIENTS:
         logger.debug("No Telegram recipients configured")
         return False
-    
+
     # Filter empty recipients
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
-    
+
     if not recipients:
         return False
-    
+
     priority = map_notification_type_to_priority(notification_type)
     emoji = map_source_to_emoji(source)
     source_display = f"{emoji} {source.title()}"
-    
+
     try:
         results = await _telegram_service.send_bulk_notifications(
             recipients=recipients,
             message=message,
             priority=priority,
             source=source_display,
-            extra_data=extra_data
+            extra_data=extra_data,
         )
-        
+
         success_count = sum(1 for success in results.values() if success)
-        
+
         if success_count > 0:
             logger.info(
                 f"Telegram notification sent to {success_count}/{len(recipients)} recipients"
@@ -217,7 +216,7 @@ async def send_telegram_notification(
         else:
             logger.warning("Failed to send Telegram notification to any recipient")
             return False
-            
+
     except Exception as e:
         logger.error(f"Error sending Telegram notification: {e}")
         return False
@@ -225,109 +224,100 @@ async def send_telegram_notification(
 
 @async_to_sync
 async def send_security_alert_telegram(
-    alert_type: str,
-    details: dict[str, Any]
+    alert_type: str, details: dict[str, Any]
 ) -> bool:
     """
     Send security alert to Telegram
-    
+
     Args:
         alert_type: Type of security alert
         details: Alert details
-    
+
     Returns:
         True if sent successfully
     """
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
         return False
-    
+
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     success_count = 0
-    
+
     for recipient in recipients:
         try:
             success = await _telegram_service.send_security_alert(
-                recipient,
-                alert_type,
-                details
+                recipient, alert_type, details
             )
             if success:
                 success_count += 1
         except Exception as e:
             logger.error(f"Failed to send security alert to {recipient}: {e}")
-    
+
     return success_count > 0
 
 
 @async_to_sync
 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:
     """
     Send system alert to Telegram
-    
+
     Args:
         alert_message: Alert message
         metrics: System metrics
-    
+
     Returns:
         True if sent successfully
     """
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
         return False
-    
+
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     success_count = 0
-    
+
     for recipient in recipients:
         try:
             success = await _telegram_service.send_system_alert(
-                recipient,
-                alert_message,
-                metrics
+                recipient, alert_message, metrics
             )
             if success:
                 success_count += 1
         except Exception as e:
             logger.error(f"Failed to send system alert to {recipient}: {e}")
-    
+
     return success_count > 0
 
 
 @async_to_sync
 async def send_user_activity_alert_telegram(
-    username: str,
-    activity_data: dict[str, Any]
+    username: str, activity_data: dict[str, Any]
 ) -> bool:
     """
     Send user activity alert to Telegram
-    
+
     Args:
         username: Username with high activity
         activity_data: Activity details
-    
+
     Returns:
         True if sent successfully
     """
     if not _telegram_service or not Config.TELEGRAM_RECIPIENTS:
         return False
-    
+
     recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
     success_count = 0
-    
+
     for recipient in recipients:
         try:
             success = await _telegram_service.send_user_activity_alert(
-                recipient,
-                username,
-                activity_data
+                recipient, username, activity_data
             )
             if success:
                 success_count += 1
         except Exception as e:
             logger.error(f"Failed to send user activity alert to {recipient}: {e}")
-    
+
     return success_count > 0
 
 
@@ -335,7 +325,7 @@ async def send_user_activity_alert_telegram(
 async def telegram_health_check() -> dict[str, Any]:
     """
     Check Telegram service health
-    
+
     Returns:
         Health status dictionary
     """
@@ -343,9 +333,9 @@ async def telegram_health_check() -> dict[str, Any]:
         return {
             "enabled": Config.TELEGRAM_ENABLED,
             "initialized": False,
-            "connected": False
+            "connected": False,
         }
-    
+
     try:
         health = await _telegram_service.health_check()
         return health
@@ -355,14 +345,14 @@ async def telegram_health_check() -> dict[str, Any]:
             "enabled": Config.TELEGRAM_ENABLED,
             "initialized": True,
             "connected": False,
-            "error": str(e)
+            "error": str(e),
         }
 
 
 def cleanup_telegram() -> None:
     """Cleanup Telegram service on shutdown"""
     global _telegram_service
-    
+
     if _telegram_service:
         try:
             run_async(_telegram_service.disconnect())
@@ -371,5 +361,5 @@ def cleanup_telegram() -> None:
             logger.error(f"Error during Telegram cleanup: {e}")
         finally:
             _telegram_service = None
-    
+
     _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__)
 
 
-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
-    
+
     Args:
         proxy_url: HTTP proxy URL (http://user:pass@host:port or http://host:port)
-    
+
     Returns:
         Dict compatible with Telethon proxy format, or None if invalid
-    
+
     Example:
         "http://proxy.example.com:8080" -> {
             "proxy_type": "http",
             "addr": "proxy.example.com",
             "port": 8080
         }
-        
+
         "http://user:pass@proxy.example.com:8080" -> {
             "proxy_type": "http",
-            "addr": "proxy.example.com", 
+            "addr": "proxy.example.com",
             "port": 8080,
             "username": "user",
             "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():
         return None
-    
+
     try:
         parsed = urlparse(proxy_url.strip())
-        
+
         # Only accept HTTP proxies
-        if parsed.scheme.lower() != 'http':
+        if parsed.scheme.lower() != "http":
             logger.warning(f"Unsupported proxy scheme '{parsed.scheme}': {proxy_url}")
             return None
-        
+
         if not parsed.hostname or not parsed.port:
             logger.warning(f"Invalid proxy URL format: {proxy_url}")
             return None
-        
+
         proxy_dict = {
             "proxy_type": "http",
             "addr": parsed.hostname,
-            "port": parsed.port
+            "port": parsed.port,
         }
-        
+
         # Add authentication if present
         if parsed.username:
             proxy_dict["username"] = parsed.username
         if parsed.password:
             proxy_dict["password"] = parsed.password
-        
+
         logger.debug(f"Parsed proxy: {proxy_dict}")
         return proxy_dict
-        
+
     except Exception as e:
         logger.error(f"Failed to parse proxy URL '{proxy_url}': {e}")
         return None
@@ -82,16 +82,19 @@ class NotificationPriority(Enum):
 
 class TelegramNotificationError(Exception):
     """Base exception for Telegram notification errors"""
+
     pass
 
 
 class TelegramConnectionError(TelegramNotificationError):
     """Raised when connection to Telegram fails"""
+
     pass
 
 
 class TelegramSendError(TelegramNotificationError):
     """Raised when sending message fails"""
+
     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):
             current_delay = delay
             last_exception = None
-            
+
             for attempt in range(max_attempts):
                 try:
                     return await func(*args, **kwargs)
                 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(
                         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
                 except Exception as e:
                     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:
                         await asyncio.sleep(current_delay)
                         current_delay *= backoff
                     last_exception = e
-                except Exception as e:
-                    logger.error(f"Unexpected error in {func.__name__}: {e}")
-                    last_exception = e
                     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 decorator
 
 
 class TelegramService:
-   
-    _instance: Optional['TelegramService'] = None
+    _instance: Optional["TelegramService"] = None
     _lock = asyncio.Lock()
-    
+
     def __new__(cls, *args, **kwargs):
         if cls._instance is None:
             cls._instance = super().__new__(cls)
             cls._instance._initialized = False
         return cls._instance
-    
+
     def __init__(
         self,
         api_id: int,
         api_hash: str,
-        bot_token: Optional[str] = None,
+        bot_token: str | None = None,
         session_name: str = "squidstats_bot",
-        phone: Optional[str] = None,
+        phone: str | None = None,
         enabled: bool = True,
-        proxy: Optional[dict[str, Any]] = None
+        proxy: dict[str, Any] | None = None,
     ):
         if self._initialized:
             return
-        
+
         self.api_id = api_id
         self.api_hash = api_hash
         self.bot_token = bot_token
@@ -162,20 +164,20 @@ class TelegramService:
         self.phone = phone
         self.enabled = enabled
         self.proxy = proxy
-        
-        self._client: Optional[TelegramClient] = None
+
+        self._client: TelegramClient | None = None
         self._connected = False
-        self._event_loop: Optional[asyncio.AbstractEventLoop] = None
+        self._event_loop: asyncio.AbstractEventLoop | None = None
         self._recipients: dict[str, InputPeerUser] = {}
-        
+
         self._initialized = True
         logger.info("TelegramService initialized")
-    
+
     async def _ensure_connected(self) -> None:
         """Ensure client is connected, connect if necessary"""
         if not self.enabled:
             raise TelegramNotificationError("Telegram notifications are disabled")
-        
+
         if self._client and self._connected:
             try:
                 await self._client.get_me()
@@ -183,15 +185,15 @@ class TelegramService:
             except Exception as e:
                 logger.warning(f"Connection check failed: {e}")
                 self._connected = False
-        
+
         await self.connect()
-    
+
     async def connect(self) -> None:
         """Establish connection to Telegram"""
         if not self.enabled:
             logger.info("Telegram notifications disabled, skipping connection")
             return
-        
+
         async with self._lock:
             try:
                 if self._client:
@@ -199,16 +201,13 @@ class TelegramService:
                         await self._client.disconnect()
                     except Exception:
                         pass
-                
+
                 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()
-                
+
                 if self.bot_token:
                     # Bot mode
                     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"
                         )
                     logger.info("Connected using existing session")
-                
+
                 self._connected = True
-                
+
             except errors.ApiIdInvalidError:
                 raise TelegramConnectionError("Invalid API ID or Hash")
             except errors.PhoneNumberInvalidError:
@@ -239,7 +238,7 @@ class TelegramService:
             except Exception as e:
                 self._connected = False
                 raise TelegramConnectionError(f"Failed to connect: {e}") from e
-    
+
     async def disconnect(self) -> None:
         """Disconnect from Telegram"""
         if self._client:
@@ -249,29 +248,7 @@ class TelegramService:
                 logger.info("Disconnected from Telegram")
             except Exception as 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
     async def session(self):
         """Context manager for Telegram session"""
@@ -281,46 +258,46 @@ class TelegramService:
         except Exception as e:
             logger.error(f"Error in Telegram session: {e}")
             raise
-    
+
     def _format_message(
         self,
         message: str,
         priority: NotificationPriority = NotificationPriority.NORMAL,
         source: str = "SquidStats",
         timestamp: bool = True,
-        extra_data: Optional[dict[str, Any]] = None
+        extra_data: dict[str, Any] | None = None,
     ) -> str:
         parts = [f"{priority.value} **{source}**\n"]
-        
+
         if timestamp:
             time_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
             parts.append(f"🕐 {time_str}\n")
-        
+
         parts.append(f"\n{message}")
-        
+
         if extra_data:
             parts.append("\n\n📊 **Detalles:**")
             for key, value in extra_data.items():
                 parts.append(f"\n• {key}: `{value}`")
-        
+
         return "".join(parts)
-    
+
     async def _resolve_recipient(self, recipient: str | int) -> InputPeerUser | int:
         if isinstance(recipient, int):
             return recipient
-        
+
         # Check cache
         if recipient in self._recipients:
             return self._recipients[recipient]
-        
+
         # Resolve entity
         try:
             async with self.session() as client:
                 # Convert channel IDs to int for better resolution
                 resolve_target = recipient
-                if isinstance(recipient, str) and recipient.startswith('-100'):
+                if isinstance(recipient, str) and recipient.startswith("-100"):
                     resolve_target = int(recipient)
-                
+
                 entity = await client.get_entity(resolve_target)
                 if isinstance(entity, User):
                     self._recipients[recipient] = entity
@@ -328,7 +305,7 @@ class TelegramService:
         except Exception as e:
             logger.error(f"Failed to resolve recipient {recipient}: {e}")
             raise TelegramSendError(f"Invalid recipient: {recipient}") from e
-    
+
     @async_retry(max_attempts=3, delay=1.0, backoff=2.0)
     async def send_notification(
         self,
@@ -337,133 +314,119 @@ class TelegramService:
         priority: NotificationPriority = NotificationPriority.NORMAL,
         source: str = "SquidStats",
         parse_mode: str = "md",
-        **kwargs
+        **kwargs,
     ) -> bool:
         if not self.enabled:
             logger.debug("Telegram notifications disabled")
             return False
-        
+
         try:
             formatted_message = self._format_message(
-                message,
-                priority=priority,
-                source=source,
-                **kwargs
+                message, priority=priority, source=source, **kwargs
             )
-            
+
             entity = await self._resolve_recipient(recipient)
-            
+
             async with self.session() as client:
                 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}")
             return True
-            
+
         except TelegramSendError:
             raise
         except Exception as e:
             logger.error(f"Failed to send notification: {e}")
             raise TelegramSendError(f"Send failed: {e}") from e
-    
+
     async def send_bulk_notifications(
         self,
         recipients: list[str | int],
         message: str,
         priority: NotificationPriority = NotificationPriority.NORMAL,
-        **kwargs
+        **kwargs,
     ) -> dict[str, bool]:
         results = {}
-        
+
         for recipient in recipients:
             try:
                 success = await self.send_notification(
-                    recipient,
-                    message,
-                    priority=priority,
-                    **kwargs
+                    recipient, message, priority=priority, **kwargs
                 )
                 results[str(recipient)] = success
             except Exception as e:
                 logger.error(f"Failed to send to {recipient}: {e}")
                 results[str(recipient)] = False
-        
+
         return results
-    
+
     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:
         message = f"🔐 **Alerta de Seguridad: {alert_type}**"
-        
+
         return await self.send_notification(
             recipient,
             message,
             priority=NotificationPriority.CRITICAL,
             source="Security Monitor",
-            extra_data=details
+            extra_data=details,
         )
-    
+
     async def send_system_alert(
         self,
         recipient: str | int,
         alert_message: str,
-        metrics: Optional[dict[str, Any]] = None
+        metrics: dict[str, Any] | None = None,
     ) -> bool:
         return await self.send_notification(
             recipient,
             alert_message,
             priority=NotificationPriority.HIGH,
             source="System Monitor",
-            extra_data=metrics
+            extra_data=metrics,
         )
-    
+
     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:
         message = f"👤 **Alta actividad detectada: {username}**"
-        
+
         return await self.send_notification(
             recipient,
             message,
             priority=NotificationPriority.HIGH,
             source="User Monitor",
-            extra_data=activity_data
+            extra_data=activity_data,
         )
-    
+
     async def health_check(self) -> dict[str, Any]:
         status = {
             "enabled": self.enabled,
             "connected": False,
             "bot_mode": bool(self.bot_token),
             "session": self.session_name,
-            "error": None
+            "error": None,
         }
-        
+
         if not self.enabled:
             return status
-        
+
         try:
             await self._ensure_connected()
             async with self.session() as client:
                 me = await client.get_me()
                 status["connected"] = True
                 status["user_id"] = me.id
-                status["username"] = getattr(me, 'username', None)
+                status["username"] = getattr(me, "username", None)
         except Exception as e:
             status["error"] = str(e)
             logger.error(f"Health check failed: {e}")
-        
+
         return status
-    
+
     def __del__(self):
         """Cleanup on deletion"""
         if self._client and self._connected:
@@ -476,47 +439,44 @@ class TelegramService:
 
 
 # Singleton instance
-_telegram_service: Optional[TelegramService] = None
+_telegram_service: TelegramService | None = None
 
 
 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:
     """
     Get or create TelegramService singleton instance
-    
+
     Args:
         api_id: Telegram API ID (required on first call)
         api_hash: Telegram API Hash (required on first call)
         proxy: Proxy configuration dict for Telethon
         **kwargs: Additional parameters for TelegramService
-    
+
     Returns:
         TelegramService instance
     """
     global _telegram_service
-    
+
     if _telegram_service is None:
         if api_id is None or api_hash is None:
             raise ValueError("api_id and api_hash required for first initialization")
-        
+
         _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
 
 
 async def cleanup_telegram_service():
     """Cleanup Telegram service on shutdown"""
     global _telegram_service
-    
+
     if _telegram_service:
         await _telegram_service.disconnect()
         _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 os
 import sys
 from pathlib import Path
 
 # Agregar el directorio raíz al path
 sys.path.insert(0, str(Path(__file__).parent.parent))
 
+# Import dotenv and load before other project imports
 from dotenv import load_dotenv
 
-# Cargar variables de entorno
 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,
-    telegram_health_check,
-    send_telegram_notification,
     send_security_alert_telegram,
     send_system_alert_telegram,
+    send_telegram_notification,
     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():
     """Verificar configuración de Telegram"""
     print_separator("Verificación de Configuración")
-    
+
     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_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:
         print("\n⚠️ TELEGRAM_ENABLED=false - Habilita en el archivo .env")
         return False
-    
+
     if not Config.TELEGRAM_API_ID or not Config.TELEGRAM_API_HASH:
         print("\n❌ Faltan credenciales de API")
         print("   Obtén tus credenciales en: https://my.telegram.org/apps")
         return False
-    
+
     if not Config.TELEGRAM_BOT_TOKEN and not Config.TELEGRAM_PHONE:
         print("\n❌ Falta BOT_TOKEN o PHONE")
         print("   Configura TELEGRAM_BOT_TOKEN o TELEGRAM_PHONE")
         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("   Configura TELEGRAM_RECIPIENTS en el archivo .env")
         return False
-    
+
     print("\n✅ Configuración completa")
     return True
 
@@ -81,7 +92,7 @@ def check_configuration():
 async def test_connection():
     """Probar conexión a Telegram"""
     print_separator("Test de Conexión")
-    
+
     try:
         service = get_telegram_service(
             api_id=int(Config.TELEGRAM_API_ID),
@@ -89,37 +100,38 @@ async def test_connection():
             bot_token=Config.TELEGRAM_BOT_TOKEN,
             phone=Config.TELEGRAM_PHONE,
             session_name=Config.TELEGRAM_SESSION_NAME,
-            enabled=Config.TELEGRAM_ENABLED
+            enabled=Config.TELEGRAM_ENABLED,
         )
-        
+
         print("Conectando a Telegram...")
         await service.connect()
         print("✅ Conexión establecida")
-        
+
         print("\nObteniendo información de la cuenta...")
         health = await service.health_check()
-        
-        print(f"\n📊 Estado del servicio:")
+
+        print("\n📊 Estado del servicio:")
         print(f"   Habilitado: {health['enabled']}")
         print(f"   Conectado: {health['connected']}")
         print(f"   Modo Bot: {health['bot_mode']}")
         print(f"   Sesión: {health['session']}")
-        
-        if health['connected']:
+
+        if health["connected"]:
             print(f"   User ID: {health.get('user_id', 'N/A')}")
             print(f"   Username: {health.get('username', 'N/A')}")
             print("\n✅ Test de conexión exitoso")
         else:
-            error = health.get('error', 'Unknown error')
+            error = health.get("error", "Unknown error")
             print(f"\n❌ No se pudo conectar: {error}")
             return False
-        
+
         await service.disconnect()
         return True
-        
+
     except Exception as e:
         print(f"\n❌ Error en test de conexión: {e}")
         import traceback
+
         traceback.print_exc()
         return False
 
@@ -127,34 +139,35 @@ async def test_connection():
 async def test_send_basic_notification():
     """Probar envío de notificación básica"""
     print_separator("Test de Notificación Básica")
-    
+
     try:
         service = get_telegram_service()
         await service.connect()
-        
+
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipient = recipients[0]
-        
+
         print(f"Enviando notificación de prueba a: {recipient}")
-        
+
         success = await service.send_notification(
             recipient=recipient,
             message="🧪 Test de notificación desde SquidStats\n\nSi recibes este mensaje, la integración funciona correctamente.",
             priority=NotificationPriority.NORMAL,
-            source="Test Suite"
+            source="Test Suite",
         )
-        
+
         if success:
             print("✅ Notificación enviada exitosamente")
         else:
             print("❌ No se pudo enviar la notificación")
-        
+
         await service.disconnect()
         return success
-        
+
     except Exception as e:
         print(f"❌ Error enviando notificación: {e}")
         import traceback
+
         traceback.print_exc()
         return False
 
@@ -162,35 +175,35 @@ async def test_send_basic_notification():
 async def test_priority_notifications():
     """Probar notificaciones con diferentes prioridades"""
     print_separator("Test de Prioridades")
-    
+
     try:
         service = get_telegram_service()
         await service.connect()
-        
+
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipient = recipients[0]
-        
+
         priorities = [
             (NotificationPriority.LOW, "Información de baja prioridad"),
             (NotificationPriority.NORMAL, "Notificación estándar"),
             (NotificationPriority.HIGH, "Advertencia importante"),
-            (NotificationPriority.CRITICAL, "¡Alerta crítica!")
+            (NotificationPriority.CRITICAL, "¡Alerta crítica!"),
         ]
-        
+
         for priority, message in priorities:
             print(f"Enviando {priority.name}...")
             await service.send_notification(
                 recipient=recipient,
                 message=message,
                 priority=priority,
-                source="Priority Test"
+                source="Priority Test",
             )
             await asyncio.sleep(1)  # Evitar rate limiting
-        
+
         print("✅ Todas las prioridades enviadas")
         await service.disconnect()
         return True
-        
+
     except Exception as e:
         print(f"❌ Error en test de prioridades: {e}")
         return False
@@ -199,14 +212,14 @@ async def test_priority_notifications():
 async def test_formatted_notifications():
     """Probar notificaciones con datos extra"""
     print_separator("Test de Mensajes Formateados")
-    
+
     try:
         service = get_telegram_service()
         await service.connect()
-        
+
         recipients = [r.strip() for r in Config.TELEGRAM_RECIPIENTS if r.strip()]
         recipient = recipients[0]
-        
+
         print("Enviando notificación con metadata...")
         await service.send_notification(
             recipient=recipient,
@@ -217,14 +230,14 @@ async def test_formatted_notifications():
                 "CPU": "85%",
                 "RAM": "7.2 GB / 16 GB",
                 "Disco": "45.3 GB disponibles",
-                "Uptime": "5 días, 3 horas"
-            }
+                "Uptime": "5 días, 3 horas",
+            },
         )
-        
+
         print("✅ Notificación formateada enviada")
         await service.disconnect()
         return True
-        
+
     except Exception as e:
         print(f"❌ Error en test de formato: {e}")
         return False
@@ -233,7 +246,7 @@ async def test_formatted_notifications():
 def test_integration_wrapper():
     """Probar wrapper de integración (funciones síncronas)"""
     print_separator("Test de Wrapper de Integración")
-    
+
     try:
         # Inicializar servicio
         print("Inicializando servicio de Telegram...")
@@ -241,72 +254,69 @@ def test_integration_wrapper():
             print("❌ No se pudo inicializar el servicio")
             return False
         print("✅ Servicio inicializado")
-        
+
         # Health check
         print("\nVerificando estado...")
         health = telegram_health_check()
         print(f"Estado: {health}")
-        
-        if not health.get('connected'):
+
+        if not health.get("connected"):
             print("⚠️ No conectado - algunas funciones no estarán disponibles")
-        
+
         # Enviar notificación genérica
         print("\nEnviando notificación genérica...")
         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'}")
-        
+
         # Enviar alerta de seguridad
         print("\nEnviando alerta de seguridad...")
         success2 = send_security_alert_telegram(
-            alert_type='Acceso sospechoso detectado',
+            alert_type="Acceso sospechoso detectado",
             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'}")
-        
+
         # Enviar alerta del sistema
         print("\nEnviando alerta del sistema...")
         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'}")
-        
+
         # Enviar alerta de actividad de usuario
         print("\nEnviando alerta de actividad de usuario...")
         success4 = send_user_activity_alert_telegram(
-            username='john_doe',
+            username="john_doe",
             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'}")
-        
+
         all_success = all([success1, success2, success3, success4])
-        
+
         if all_success:
             print("\n✅ Todos los tests del wrapper exitosos")
         else:
             print("\n⚠️ Algunos tests fallaron")
-        
+
         return all_success
-        
+
     except Exception as e:
         print(f"\n❌ Error en test de wrapper: {e}")
         import traceback
+
         traceback.print_exc()
         return False
 
@@ -314,44 +324,47 @@ def test_integration_wrapper():
 async def run_async_tests():
     """Ejecutar tests asíncronos"""
     results = []
-    
+
     # Test de conexión
     results.append(await test_connection())
     await asyncio.sleep(2)
-    
+
     # Test de notificación básica
     results.append(await test_send_basic_notification())
     await asyncio.sleep(2)
-    
+
     # Test de prioridades
     results.append(await test_priority_notifications())
     await asyncio.sleep(2)
-    
+
     # Test de formato
     results.append(await test_formatted_notifications())
-    
+
     return results
 
 
 def test_proxy_parsing():
     """Test parsing de URLs de proxy HTTP"""
     print_separator("🧪 Test de Parsing de Proxy")
-    
+
     test_cases = [
         # (input, expected_output_keys)
         ("", None),
         ("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
         ("invalid-url", None),
     ]
-    
+
     all_passed = True
-    
+
     for i, (proxy_url, expected_keys) in enumerate(test_cases, 1):
         try:
             result = parse_http_proxy_url(proxy_url)
-            
+
             if expected_keys is None:
                 if result is None:
                     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):
                     print(f"✅ Test {i}: '{proxy_url}' → {result}")
                 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
-                    
+
         except Exception as e:
             print(f"❌ Test {i}: Error parsing '{proxy_url}': {e}")
             all_passed = False
-    
+
     if all_passed:
         print("\n✅ Todos los tests de proxy pasaron")
     else:
         print("\n❌ Algunos tests de proxy fallaron")
-    
+
     return all_passed
 
 
 def main():
     """Función principal"""
     print_separator("🧪 Test de Integración de Telegram")
-    
+
     # Verificar configuración
     if not check_configuration():
         print("\n❌ Configuración incompleta. Corrige los errores y vuelve a intentar.")
         sys.exit(1)
-    
+
     # Test de parsing de proxy
     proxy_test_passed = test_proxy_parsing()
-    
+
     # Ejecutar tests asíncronos
     print("\n🚀 Iniciando tests asíncronos...")
     async_results = asyncio.run(run_async_tests())
-    
+
     # Ejecutar tests síncronos (wrapper)
     print("\n🚀 Iniciando tests de wrapper...")
     sync_result = test_integration_wrapper()
-    
+
     # Resumen
     print_separator("📊 Resumen de Tests")
-    
+
     tests = [
         ("Parsing de Proxy", proxy_test_passed),
         ("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),
         ("Wrapper de integración", sync_result),
     ]
-    
+
     for test_name, result in tests:
         status = "✅ PASS" if result else "❌ FAIL"
         print(f"{status} - {test_name}")
-    
+
     total = len(tests)
     passed = sum(1 for _, result in tests if result)
-    
+
     print(f"\n📈 Resultados: {passed}/{total} tests exitosos")
-    
+
     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
     else:
         print("\n⚠️ Algunos tests fallaron. Revisa los logs para más detalles.")
@@ -436,5 +453,6 @@ if __name__ == "__main__":
     except Exception as e:
         print(f"\n\n❌ Error fatal: {e}")
         import traceback
+
         traceback.print_exc()
         sys.exit(1)