#!/usr/bin/env python3 """ DTO Slack Bot - Integration for real-time notifications and status queries """ import os import json from typing import Dict, Any, Optional from slack_sdk import WebClient from slack_sdk.errors import SlackApiError from slack_sdk.socket_mode import SocketModeClient from slack_sdk.socket_mode.request import SocketModeRequest from slack_sdk.socket_mode.response import SocketModeResponse class DTOSlackBot: def __init__(self, bot_token: Optional[str] = None, app_token: Optional[str] = None): self.bot_token = bot_token or os.getenv('SLACK_BOT_TOKEN') self.app_token = app_token or os.getenv('SLACK_APP_TOKEN') self.web_client = None self.socket_client = None def connect_web_client(self) -> bool: """Connect to Slack Web API""" if not self.bot_token: print("❌ Slack bot token not configured") return False try: self.web_client = WebClient(token=self.bot_token) # Test connection self.web_client.auth_test() print("✅ Connected to Slack Web API") return True except SlackApiError as e: print(f"❌ Failed to connect to Slack Web API: {e}") return False def connect_socket_mode(self) -> bool: """Connect to Slack Socket Mode for real-time events""" if not self.app_token: print("❌ Slack app token not configured for Socket Mode") return False try: self.socket_client = SocketModeClient( app_token=self.app_token, web_client=self.web_client ) # Register event handlers self.socket_client.socket_mode_request_listeners.append(self.handle_socket_request) print("✅ Connected to Slack Socket Mode") return True except Exception as e: print(f"❌ Failed to connect to Slack Socket Mode: {e}") return False def send_message(self, channel: str, message: str, blocks: Optional[list] = None) -> bool: """Send message to Slack channel""" if not self.web_client: if not self.connect_web_client(): return False try: if blocks: response = self.web_client.chat_postMessage( channel=channel, text=message, blocks=blocks ) else: response = self.web_client.chat_postMessage( channel=channel, text=message ) print(f"✅ Message sent to {channel}: {message}") return True except SlackApiError as e: print(f"❌ Failed to send message: {e}") return False def send_alert(self, channel: str, title: str, message: str, severity: str = "warning") -> bool: """Send formatted alert message""" severity_colors = { "info": "#3498DB", "warning": "#F39C12", "error": "#E74C3C", "success": "#2ECC71", "critical": "#FF0000" } blocks = [ { "type": "header", "text": { "type": "plain_text", "text": title, "emoji": True } }, { "type": "section", "text": { "type": "mrkdwn", "text": message } }, { "type": "divider" }, { "type": "context", "elements": [ { "type": "mrkdwn", "text": f"*Severity:* {severity.upper()}" } ] } ] return self.send_message(channel, title, blocks) def send_run_status(self, channel: str, run_data: Dict[str, Any]) -> bool: """Send run status update""" run_id = run_data.get('run_id', 'unknown') status = run_data.get('status', 'unknown') progress = run_data.get('progress_percent', 0) throughput = run_data.get('throughput_mbps', 0) status_emoji = { "planned": "📋", "in_progress": "🔄", "completed": "✅", "failed": "❌", "rolled_back": "↩️" } blocks = [ { "type": "header", "text": { "type": "plain_text", "text": f"DTO Run Status: {run_id}", "emoji": True } }, { "type": "section", "fields": [ { "type": "mrkdwn", "text": f"*Status:* {status_emoji.get(status, '📊')} {status.upper()}" }, { "type": "mrkdwn", "text": f"*Progress:* {progress}%" }, { "type": "mrkdwn", "text": f"*Throughput:* {throughput:.1f} MB/s" }, { "type": "mrkdwn", "text": f"*Class:* {run_data.get('data_class', 'N/A')}" } ] } ] # Add progress bar if in progress if status == "in_progress" and progress > 0: progress_blocks = int(progress / 10) progress_bar = "🟩" * progress_blocks + "⬜" * (10 - progress_blocks) blocks.append({ "type": "section", "text": { "type": "mrkdwn", "text": f"`{progress_bar}` {progress}%" } }) # Add buttons for actions if status == "in_progress": blocks.append({ "type": "actions", "elements": [ { "type": "button", "text": { "type": "plain_text", "text": "View Details", "emoji": True }, "value": f"view_{run_id}", "action_id": "view_run_details" }, { "type": "button", "text": { "type": "plain_text", "text": "Rollback", "emoji": True }, "value": f"rollback_{run_id}", "action_id": "request_rollback", "style": "danger" } ] }) return self.send_message(channel, f"DTO Run {run_id} - {status}", blocks) def handle_socket_request(self, client: SocketModeClient, request: SocketModeRequest): """Handle Socket Mode requests""" if request.type == "slash_commands": self.handle_slash_command(request) elif request.type == "interactive": self.handle_interaction(request) # Always acknowledge the request response = SocketModeResponse(envelope_id=request.envelope_id) client.send_socket_mode_response(response) def handle_slash_command(self, request: SocketModeRequest): """Handle slash commands like /dto status""" command = request.payload.get('command', '') text = request.payload.get('text', '') user_id = request.payload.get('user_id', '') channel_id = request.payload.get('channel_id', '') if command == "/dto": if text.startswith("status"): self.handle_status_command(text, channel_id, user_id) elif text.startswith("help"): self.handle_help_command(channel_id) else: self.send_message(channel_id, "Unknown DTO command. Use `/dto help` for available commands.") def handle_status_command(self, text: str, channel_id: str, user_id: str): """Handle /dto status command""" # Parse run_id from command text parts = text.split() run_id = parts[1] if len(parts) > 1 else None if run_id: # TODO: Fetch actual run status from cache/database mock_status = { 'run_id': run_id, 'status': 'in_progress', 'progress_percent': 75.5, 'throughput_mbps': 604.0, 'data_class': 'CLASS_A' } self.send_run_status(channel_id, mock_status) else: self.send_message(channel_id, "Please specify a run ID: `/dto status `") def handle_help_command(self, channel_id: str): """Handle /dto help command""" help_text = """ *DTO Slack Bot Commands:* • `/dto status ` - Get status of a specific run • `/dto help` - Show this help message *Available Actions:* • View run details • Request rollback for in-progress runs • Receive real-time alerts for SLO breaches """ self.send_message(channel_id, help_text.strip()) def handle_interaction(self, request: SocketModeRequest): """Handle button interactions""" payload = json.loads(request.payload.get('payload', '{}')) action_id = payload.get('actions', [{}])[0].get('action_id', '') value = payload.get('actions', [{}])[0].get('value', '') user_id = payload.get('user', {}).get('id', '') channel_id = payload.get('channel', {}).get('id', '') if action_id == "view_run_details": run_id = value.replace('view_', '') self.send_message(channel_id, f"Fetching details for run {run_id}...") # TODO: Fetch and display detailed run information elif action_id == "request_rollback": run_id = value.replace('rollback_', '') self.send_message(channel_id, f"Rollback requested for run {run_id} by <@{user_id}>") # TODO: Emit rollback event to NATS def start_listening(self): """Start listening for Socket Mode events""" if not self.socket_client: if not self.connect_socket_mode(): return False try: print("Starting Slack Socket Mode listener...") self.socket_client.connect() return True except Exception as e: print(f"❌ Failed to start Socket Mode listener: {e}") return False # Test function def test_slack_connectivity(): """Test Slack bot connectivity""" bot = DTOSlackBot() if bot.connect_web_client(): # Test sending a message (will fail without proper token/channel) print("✅ Slack Web API connectivity test passed") # Test message formatting test_run = { 'run_id': 'test-run-001', 'status': 'in_progress', 'progress_percent': 45.5, 'throughput_mbps': 604.0, 'data_class': 'CLASS_A' } print("Run status message would be sent with:") print(f" Run ID: {test_run['run_id']}") print(f" Status: {test_run['status']}") print(f" Progress: {test_run['progress_percent']}%") print(f" Throughput: {test_run['throughput_mbps']} MB/s") return True else: print("❌ Slack connectivity test failed (expected without proper tokens)") return False if __name__ == "__main__": print("Testing DTO Slack Bot...") print("=" * 50) test_slack_connectivity() print("\nTo use the Slack bot, set these environment variables:") print("export SLACK_BOT_TOKEN=xoxb-your-bot-token") print("export SLACK_APP_TOKEN=xapp-your-app-token")