Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /notifications /backends /telegram.py
| """ | |
| Telegram Notification Backend for Zen-AI-Pentest | |
| """ | |
| import logging | |
| from datetime import datetime, timezone | |
| from typing import Any, Dict, Final, Optional | |
| import requests | |
| logger = logging.getLogger(__name__) | |
| TELEGRAM_API_BASE: Final[str] = "https://api.telegram.org" | |
| class TelegramBackend: | |
| """Telegram Notification Backend with rate limiting and retry support""" | |
| def __init__( | |
| self, | |
| bot_token: str, | |
| chat_id: str, | |
| timeout: int = 10, | |
| max_retries: int = 3, | |
| parse_mode: str = "Markdown", | |
| ) -> None: | |
| """ | |
| Initialize Telegram backend. | |
| Args: | |
| bot_token: Bot token from @BotFather | |
| chat_id: Chat ID or channel name (e.g., @channelname) | |
| timeout: Request timeout in seconds | |
| max_retries: Maximum retry attempts | |
| parse_mode: Message parse mode (Markdown, HTML, or None) | |
| """ | |
| self.bot_token = bot_token | |
| self.chat_id = chat_id | |
| self.timeout = timeout | |
| self.max_retries = max_retries | |
| self.parse_mode = parse_mode | |
| self.api_url = f"{TELEGRAM_API_BASE}/bot{bot_token}" | |
| def send( | |
| self, | |
| message: str, | |
| parse_mode: Optional[str] = None, | |
| disable_web_page_preview: bool = True, | |
| reply_markup: Optional[Dict[str, Any]] = None, | |
| ) -> Dict[str, Any]: | |
| """ | |
| Send message to Telegram. | |
| Args: | |
| message: Message text (max 4096 characters) | |
| parse_mode: Parse mode override | |
| disable_web_page_preview: Disable link previews | |
| reply_markup: Optional inline keyboard markup | |
| Returns: | |
| Dict with success status | |
| """ | |
| # Truncate if needed | |
| if len(message) > 4096: | |
| message = message[:4093] + "..." | |
| payload = { | |
| "chat_id": self.chat_id, | |
| "text": message, | |
| "disable_web_page_preview": disable_web_page_preview, | |
| } | |
| mode = parse_mode or self.parse_mode | |
| if mode: | |
| payload["parse_mode"] = mode | |
| if reply_markup: | |
| payload["reply_markup"] = reply_markup | |
| return self._send_with_retry("sendMessage", payload) | |
| def send_photo( | |
| self, | |
| photo_url: str, | |
| caption: Optional[str] = None, | |
| parse_mode: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| """Send photo with optional caption""" | |
| payload = { | |
| "chat_id": self.chat_id, | |
| "photo": photo_url, | |
| } | |
| if caption: | |
| if len(caption) > 1024: | |
| caption = caption[:1021] + "..." | |
| payload["caption"] = caption | |
| mode = parse_mode or self.parse_mode | |
| if mode: | |
| payload["parse_mode"] = mode | |
| return self._send_with_retry("sendPhoto", payload) | |
| def send_document( | |
| self, | |
| document_path: str, | |
| caption: Optional[str] = None, | |
| ) -> Dict[str, Any]: | |
| """Send document/file""" | |
| url = f"{self.api_url}/sendDocument" | |
| try: | |
| with open(document_path, "rb") as f: | |
| files = {"document": f} | |
| data = { | |
| "chat_id": self.chat_id, | |
| } | |
| if caption: | |
| data["caption"] = caption[:1024] if len(caption) > 1024 else caption | |
| response = requests.post( | |
| url, | |
| data=data, | |
| files=files, | |
| timeout=self.timeout, | |
| ) | |
| if response.status_code == 200: | |
| return {"success": True, "status_code": response.status_code} | |
| else: | |
| return { | |
| "success": False, | |
| "error": f"HTTP {response.status_code}: {response.text}", | |
| } | |
| except Exception as e: | |
| return {"success": False, "error": str(e)} | |
| def send_event( | |
| self, | |
| event_type: str, | |
| data: Dict[str, Any], | |
| template_data: Optional[Dict[str, Any]] = None, | |
| ) -> Dict[str, Any]: | |
| """ | |
| Send event notification. | |
| Args: | |
| event_type: Type of event | |
| data: Event data | |
| template_data: Optional pre-rendered template data | |
| Returns: | |
| Dict with success status | |
| """ | |
| if template_data: | |
| return self.send(template_data.get("message", "")) | |
| builders = { | |
| "scan_started": self._build_scan_started, | |
| "scan_completed": self._build_scan_completed, | |
| "critical_finding": self._build_critical_finding, | |
| "high_severity_cve": self._build_high_severity_cve, | |
| "system_alert": self._build_system_alert, | |
| "report_ready": self._build_report_ready, | |
| } | |
| builder = builders.get(event_type, self._build_generic) | |
| message = builder(data) | |
| return self.send(message) | |
| def _build_scan_started(self, data: Dict[str, Any]) -> str: | |
| """Build scan started message""" | |
| return f"""๐ *Scan Started* | |
| ๐ *Target:* `{data.get("target", "Unknown")}` | |
| ๐ *Scan ID:* `{data.get("scan_id", "N/A")}` | |
| ๐ *Type:* {data.get("scan_type", "N/A")} | |
| ๐ค *Started By:* {data.get("started_by", "N/A")} | |
| _This scan is now running. You will receive another notification when it completes._ | |
| โฑ๏ธ {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}""" | |
| def _build_scan_completed(self, data: Dict[str, Any]) -> str: | |
| """Build scan completed message""" | |
| findings = data.get("findings_count", 0) | |
| critical = data.get("critical_count", 0) | |
| high = data.get("high_count", 0) | |
| if critical > 0: | |
| icon = "๐ด" | |
| status = "CRITICAL ISSUES FOUND" | |
| elif high > 0: | |
| icon = "๐ " | |
| status = "HIGH SEVERITY ISSUES" | |
| elif findings > 0: | |
| icon = "๐ก" | |
| status = "ISSUES FOUND" | |
| else: | |
| icon = "๐ข" | |
| status = "NO ISSUES FOUND" | |
| return f"""{icon} *Scan Completed - {status}* | |
| ๐ *Target:* `{data.get("target", "Unknown")}` | |
| ๐ *Scan ID:* `{data.get("scan_id", "N/A")}` | |
| โฑ๏ธ *Duration:* {data.get("duration", "N/A")}s | |
| *Findings Summary* | |
| โข Total: {findings} | |
| โข Critical: {critical} | |
| โข High: {high} | |
| โข Medium: {data.get("medium_count", 0)} | |
| โข Low: {data.get("low_count", 0)} | |
| _{datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}_""" | |
| def _build_critical_finding(self, data: Dict[str, Any]) -> str: | |
| """Build critical finding message""" | |
| description = data.get("description", "") | |
| if len(description) > 500: | |
| description = description[:497] + "..." | |
| return f"""๐จ *CRITICAL VULNERABILITY DETECTED* | |
| *{data.get("title", "Unknown")}* | |
| ๐ *Target:* `{data.get("target", "N/A")}` | |
| ๐ *CVE:* `{data.get("cve", "N/A")}` | |
| ๐ *CVSS:* `{data.get("cvss", "N/A")}` | |
| ๐ง *Tool:* {data.get("tool", "Unknown")} | |
| ๐ *Port:* {data.get("port", "N/A")} | |
| {description} | |
| โ ๏ธ *IMMEDIATE ACTION REQUIRED* | |
| _{datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}_""" | |
| def _build_high_severity_cve(self, data: Dict[str, Any]) -> str: | |
| """Build high severity CVE message""" | |
| description = data.get("description", "") | |
| if len(description) > 500: | |
| description = description[:497] + "..." | |
| return f"""โ ๏ธ *High Severity CVE: {data.get("cve", "Unknown")}* | |
| {description} | |
| ๐ *CVSS Score:* `{data.get("cvss", "N/A")}` | |
| ๐ *EPSS Score:* `{data.get("epss", "N/A")}` | |
| ๐ฆ *Affected:* `{data.get("affected", "N/A")}` | |
| _{datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}_""" | |
| def _build_system_alert(self, data: Dict[str, Any]) -> str: | |
| """Build system alert message""" | |
| alert_type = data.get("alert_type", "info") | |
| icons = { | |
| "error": "๐ด", | |
| "warning": "๐ ", | |
| "info": "๐ต", | |
| "success": "๐ข", | |
| } | |
| icon = icons.get(alert_type, "๐") | |
| return f"""{icon} *System Alert: {data.get("title", "Notification")}* | |
| {data.get("message", "")} | |
| ๐ง *Component:* {data.get("component", "N/A")} | |
| โก *Severity:* {alert_type.upper()} | |
| _{datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}_""" | |
| def _build_report_ready(self, data: Dict[str, Any]) -> str: | |
| """Build report ready message""" | |
| return f"""๐ *Report Ready* | |
| Your security report for *{data.get("target", "Unknown")}* is ready for download. | |
| ๐ *Report ID:* `{data.get("report_id", "N/A")}` | |
| ๐ *Scan ID:* `{data.get("scan_id", "N/A")}` | |
| ๐ *Format:* {data.get("format", "PDF").upper()} | |
| ๐ฆ *Size:* {data.get("size", "N/A")} | |
| _You can download the report from the dashboard or via the API._ | |
| _{datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}_""" | |
| def _build_generic(self, data: Dict[str, Any]) -> str: | |
| """Build generic message""" | |
| return f"""*{data.get("title", "Notification")}* | |
| {data.get("message", "")} | |
| _{datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}_""" | |
| def _send_with_retry(self, method: str, payload: Dict[str, Any]) -> Dict[str, Any]: | |
| """Send API request with retry logic""" | |
| url = f"{self.api_url}/{method}" | |
| last_error = None | |
| for attempt in range(self.max_retries): | |
| try: | |
| response = requests.post( | |
| url, | |
| json=payload, | |
| timeout=self.timeout, | |
| ) | |
| if response.status_code == 200: | |
| return { | |
| "success": True, | |
| "status_code": response.status_code, | |
| "attempt": attempt + 1, | |
| } | |
| elif response.status_code == 429: # Rate limited | |
| retry_after = int(response.headers.get("Retry-After", 5)) | |
| logger.warning(f"Telegram rate limited, retrying after {retry_after}s") | |
| import time | |
| time.sleep(retry_after) | |
| last_error = f"Rate limited (HTTP {response.status_code})" | |
| else: | |
| result = response.json() | |
| error_msg = result.get("description", response.text) | |
| last_error = f"HTTP {response.status_code}: {error_msg}" | |
| logger.warning(f"Telegram API error: {last_error}") | |
| except requests.RequestException as e: | |
| last_error = str(e) | |
| logger.warning(f"Telegram request error (attempt {attempt + 1}): {e}") | |
| # Exponential backoff | |
| if attempt < self.max_retries - 1: | |
| import time | |
| time.sleep(2**attempt) | |
| return { | |
| "success": False, | |
| "error": last_error, | |
| "attempts": self.max_retries, | |
| } | |
| def test(self) -> Dict[str, Any]: | |
| """Test the Telegram connection""" | |
| message = f"""๐ *Test Notification* | |
| This is a test notification from *Zen-AI-Pentest*. | |
| โ If you received this message, your Telegram notification settings are configured correctly. | |
| ๐ {datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")}""" | |
| return self.send(message) | |
| def get_chat_info(self) -> Dict[str, Any]: | |
| """Get information about the chat""" | |
| url = f"{self.api_url}/getChat" | |
| payload = {"chat_id": self.chat_id} | |
| try: | |
| response = requests.post(url, json=payload, timeout=self.timeout) | |
| if response.status_code == 200: | |
| result = response.json() | |
| if result.get("ok"): | |
| return { | |
| "success": True, | |
| "chat": result.get("result", {}), | |
| } | |
| else: | |
| return { | |
| "success": False, | |
| "error": result.get("description", "Unknown error"), | |
| } | |
| else: | |
| return { | |
| "success": False, | |
| "error": f"HTTP {response.status_code}", | |
| } | |
| except Exception as e: | |
| return {"success": False, "error": str(e)} | |
Xet Storage Details
- Size:
- 12.3 kB
- Xet hash:
- 56c9dc11c9673017d20d26777a945d6704e02bf9fc206db1fb6f7ada3a1c52b8
ยท
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.