File size: 12,400 Bytes
fd357f4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 |
#!/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 <run_id> 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 <run_id>`")
def handle_help_command(self, channel_id: str):
"""Handle /dto help command"""
help_text = """
*DTO Slack Bot Commands:*
β’ `/dto status <run_id>` - 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") |