-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshadowhunter_alerts.py
More file actions
1180 lines (971 loc) · 37.8 KB
/
shadowhunter_alerts.py
File metadata and controls
1180 lines (971 loc) · 37.8 KB
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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
ShadowHunter - Dark Web Credential Intelligence Platform
Module: Unified Multi-Channel Alerting System
Author: Fevra
Version: 0.1.0
Consolidated from Darkweb Monitor research - provides:
- Multi-channel alert delivery (Email, Telegram, Discord, Webhook)
- Priority-based routing and rate limiting
- Alert aggregation and deduplication
- Customizable alert templates
- Delivery tracking and retry logic
- Integration with scheduler and verify modules
Extends the email module with additional channels and unified interface.
References:
- shadowhunter_email.py patterns
- Darkweb Monitor alerting concepts
"""
import asyncio
import json
import hashlib
import aiohttp
from datetime import datetime, timezone, timedelta
from typing import List, Dict, Optional, Any, Callable, Set, Tuple
from dataclasses import dataclass, field
from enum import Enum
from abc import ABC, abstractmethod
import threading
# Import ShadowHunter modules
try:
from shadowhunter_logger import get_logger, LogLevel
from shadowhunter_email import EmailSender, EmailConfig, EmailAlert, AlertType, AlertSeverity
except ImportError:
import logging
def get_logger(name, **kwargs):
return logging.getLogger(name)
EmailSender = None
EmailConfig = None
EmailAlert = None
AlertType = None
AlertSeverity = None
# Initialize module logger
logger = get_logger("Alerts", log_level=LogLevel.DEBUG)
# ============================================================================
# CONFIGURATION & ENUMS
# ============================================================================
class AlertChannel(str, Enum):
"""Available alert delivery channels."""
EMAIL = "email"
TELEGRAM = "telegram"
DISCORD = "discord"
SLACK = "slack"
WEBHOOK = "webhook"
CONSOLE = "console"
class AlertPriority(str, Enum):
"""Alert priority levels."""
CRITICAL = "critical" # Immediate delivery, all channels
HIGH = "high" # Fast delivery, primary channels
MEDIUM = "medium" # Standard delivery
LOW = "low" # Batched/digest delivery
INFO = "info" # Optional, log only
class DeliveryStatus(str, Enum):
"""Alert delivery status."""
PENDING = "pending"
SENDING = "sending"
DELIVERED = "delivered"
FAILED = "failed"
RETRYING = "retrying"
SUPPRESSED = "suppressed"
# ============================================================================
# DATA MODELS
# ============================================================================
@dataclass
class AlertConfig:
"""
Configuration for the unified alerting system.
Defines channels, rate limits, and routing rules.
"""
# Channel configurations
email_config: Optional[Dict[str, Any]] = None
telegram_config: Optional[Dict[str, Any]] = None
discord_config: Optional[Dict[str, Any]] = None
slack_config: Optional[Dict[str, Any]] = None
webhook_urls: List[str] = field(default_factory=list)
# Rate limiting
max_alerts_per_hour: int = 100
max_alerts_per_day: int = 1000
cooldown_seconds: int = 60 # Min time between same alert type
# Retry settings
max_retries: int = 3
retry_delay_seconds: int = 60
# Deduplication
dedup_window_minutes: int = 30
# Routing rules (priority -> channels)
routing_rules: Dict[str, List[str]] = field(default_factory=lambda: {
"critical": ["email", "telegram", "discord", "webhook"],
"high": ["email", "telegram", "webhook"],
"medium": ["email", "webhook"],
"low": ["email"],
"info": ["console"]
})
@dataclass
class Alert:
"""
Unified alert structure for all channels.
Represents a single alert that can be delivered
through multiple channels based on priority and routing.
"""
id: str
title: str
message: str
priority: AlertPriority
source: str # Module that generated the alert
category: str # credential_leak, ransomware, change_detected, etc.
timestamp: datetime = field(default_factory=lambda: datetime.now(timezone.utc))
metadata: Dict[str, Any] = field(default_factory=dict)
affected_domains: List[str] = field(default_factory=list)
actions: List[str] = field(default_factory=list) # Recommended actions
tags: List[str] = field(default_factory=list)
def get_dedup_key(self) -> str:
"""Generate deduplication key for alert."""
key_parts = [
self.category,
self.source,
','.join(sorted(self.affected_domains)),
self.title
]
return hashlib.sha256('|'.join(key_parts).encode()).hexdigest()[:16]
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"id": self.id,
"title": self.title,
"message": self.message,
"priority": self.priority.value,
"source": self.source,
"category": self.category,
"timestamp": self.timestamp.isoformat(),
"affected_domains": self.affected_domains,
"actions": self.actions,
"tags": self.tags,
"metadata": self.metadata
}
def get_priority_emoji(self) -> str:
"""Get emoji for priority level."""
emojis = {
AlertPriority.CRITICAL: "🔴",
AlertPriority.HIGH: "🟠",
AlertPriority.MEDIUM: "🟡",
AlertPriority.LOW: "🔵",
AlertPriority.INFO: "ℹ️"
}
return emojis.get(self.priority, "⚪")
@dataclass
class DeliveryRecord:
"""
Record of an alert delivery attempt.
Tracks delivery status, timing, and errors for
each channel the alert was sent to.
"""
alert_id: str
channel: AlertChannel
status: DeliveryStatus
attempt: int
timestamp: datetime
error: Optional[str] = None
response: Optional[str] = None
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary."""
return {
"alert_id": self.alert_id,
"channel": self.channel.value,
"status": self.status.value,
"attempt": self.attempt,
"timestamp": self.timestamp.isoformat(),
"error": self.error
}
# ============================================================================
# CHANNEL HANDLERS
# ============================================================================
class ChannelHandler(ABC):
"""
Abstract base class for alert channel handlers.
Each channel (email, telegram, etc.) implements this interface
to provide consistent delivery behavior.
"""
@property
@abstractmethod
def channel_type(self) -> AlertChannel:
"""Return the channel type."""
pass
@abstractmethod
async def send(self, alert: Alert) -> Tuple[bool, Optional[str]]:
"""
Send alert through this channel.
Args:
alert: Alert to send
Returns:
Tuple of (success, error_message)
"""
pass
@abstractmethod
def is_configured(self) -> bool:
"""Check if channel is properly configured."""
pass
def format_message(self, alert: Alert) -> str:
"""Format alert message for this channel."""
return f"{alert.get_priority_emoji()} [{alert.priority.value.upper()}] {alert.title}\n\n{alert.message}"
class TelegramHandler(ChannelHandler):
"""
Telegram bot alert handler.
Sends alerts to configured Telegram chat(s) via Bot API.
"""
def __init__(
self,
bot_token: str,
chat_ids: List[str],
parse_mode: str = "HTML"
):
"""
Initialize Telegram handler.
Args:
bot_token: Telegram bot API token
chat_ids: List of chat IDs to send alerts to
parse_mode: Message parse mode (HTML or Markdown)
"""
self.bot_token = bot_token
self.chat_ids = chat_ids
self.parse_mode = parse_mode
self.api_base = f"https://api.telegram.org/bot{bot_token}"
@property
def channel_type(self) -> AlertChannel:
return AlertChannel.TELEGRAM
def is_configured(self) -> bool:
return bool(self.bot_token and self.chat_ids)
def format_message(self, alert: Alert) -> str:
"""Format message for Telegram HTML."""
emoji = alert.get_priority_emoji()
message = f"""
{emoji} <b>{alert.priority.value.upper()} ALERT</b>
<b>🔔 {alert.title}</b>
{alert.message}
<b>📋 Details:</b>
• Source: {alert.source}
• Category: {alert.category}
• Time: {alert.timestamp.strftime('%Y-%m-%d %H:%M:%S UTC')}
"""
if alert.affected_domains:
message += f"\n• Affected: {', '.join(alert.affected_domains[:5])}"
if alert.actions:
message += "\n\n<b>⚡ Recommended Actions:</b>\n"
for i, action in enumerate(alert.actions[:5], 1):
message += f"{i}. {action}\n"
if alert.tags:
message += f"\n🏷 {' '.join(f'#{tag}' for tag in alert.tags[:5])}"
return message.strip()
async def send(self, alert: Alert) -> Tuple[bool, Optional[str]]:
"""Send alert to Telegram."""
if not self.is_configured():
return False, "Telegram not configured"
message = self.format_message(alert)
success_count = 0
errors = []
async with aiohttp.ClientSession() as session:
for chat_id in self.chat_ids:
try:
async with session.post(
f"{self.api_base}/sendMessage",
json={
"chat_id": chat_id,
"text": message,
"parse_mode": self.parse_mode,
"disable_web_page_preview": True
},
timeout=aiohttp.ClientTimeout(total=10)
) as response:
result = await response.json()
if result.get("ok"):
success_count += 1
logger.info(f"Telegram alert sent to chat {chat_id}")
else:
error = result.get("description", "Unknown error")
errors.append(f"{chat_id}: {error}")
logger.warn(f"Telegram send failed: {error}")
except Exception as e:
errors.append(f"{chat_id}: {str(e)}")
logger.error(f"Telegram error: {e}")
if success_count == len(self.chat_ids):
return True, None
elif success_count > 0:
return True, f"Partial delivery: {'; '.join(errors)}"
else:
return False, '; '.join(errors)
class DiscordHandler(ChannelHandler):
"""
Discord webhook alert handler.
Sends alerts to Discord channels via webhooks with rich embeds.
"""
def __init__(self, webhook_urls: List[str]):
"""
Initialize Discord handler.
Args:
webhook_urls: List of Discord webhook URLs
"""
self.webhook_urls = webhook_urls
@property
def channel_type(self) -> AlertChannel:
return AlertChannel.DISCORD
def is_configured(self) -> bool:
return bool(self.webhook_urls)
def _get_color(self, priority: AlertPriority) -> int:
"""Get embed color based on priority."""
colors = {
AlertPriority.CRITICAL: 0xDC2626, # Red
AlertPriority.HIGH: 0xEA580C, # Orange
AlertPriority.MEDIUM: 0xCA8A04, # Yellow
AlertPriority.LOW: 0x2563EB, # Blue
AlertPriority.INFO: 0x64748B # Gray
}
return colors.get(priority, 0x6B7280)
def format_embed(self, alert: Alert) -> Dict[str, Any]:
"""Format alert as Discord embed."""
embed = {
"title": f"{alert.get_priority_emoji()} {alert.title}",
"description": alert.message[:2000], # Discord limit
"color": self._get_color(alert.priority),
"timestamp": alert.timestamp.isoformat(),
"footer": {
"text": f"ShadowHunter | {alert.source}"
},
"fields": [
{
"name": "Priority",
"value": alert.priority.value.upper(),
"inline": True
},
{
"name": "Category",
"value": alert.category,
"inline": True
}
]
}
if alert.affected_domains:
embed["fields"].append({
"name": "Affected Domains",
"value": ', '.join(alert.affected_domains[:10]),
"inline": False
})
if alert.actions:
embed["fields"].append({
"name": "⚡ Recommended Actions",
"value": '\n'.join(f"• {a}" for a in alert.actions[:5]),
"inline": False
})
return embed
async def send(self, alert: Alert) -> Tuple[bool, Optional[str]]:
"""Send alert to Discord."""
if not self.is_configured():
return False, "Discord not configured"
embed = self.format_embed(alert)
payload = {
"username": "ShadowHunter",
"embeds": [embed]
}
success_count = 0
errors = []
async with aiohttp.ClientSession() as session:
for webhook_url in self.webhook_urls:
try:
async with session.post(
webhook_url,
json=payload,
timeout=aiohttp.ClientTimeout(total=10)
) as response:
if response.status in [200, 204]:
success_count += 1
logger.info("Discord alert sent")
else:
error = await response.text()
errors.append(error[:100])
logger.warn(f"Discord send failed: {response.status}")
except Exception as e:
errors.append(str(e))
logger.error(f"Discord error: {e}")
if success_count == len(self.webhook_urls):
return True, None
elif success_count > 0:
return True, f"Partial delivery: {'; '.join(errors)}"
else:
return False, '; '.join(errors)
class SlackHandler(ChannelHandler):
"""
Slack webhook alert handler.
Sends alerts to Slack channels via incoming webhooks.
"""
def __init__(self, webhook_url: str):
"""
Initialize Slack handler.
Args:
webhook_url: Slack incoming webhook URL
"""
self.webhook_url = webhook_url
@property
def channel_type(self) -> AlertChannel:
return AlertChannel.SLACK
def is_configured(self) -> bool:
return bool(self.webhook_url)
def _get_color(self, priority: AlertPriority) -> str:
"""Get attachment color based on priority."""
colors = {
AlertPriority.CRITICAL: "danger",
AlertPriority.HIGH: "warning",
AlertPriority.MEDIUM: "#CA8A04",
AlertPriority.LOW: "good",
AlertPriority.INFO: "#64748B"
}
return colors.get(priority, "#6B7280")
def format_blocks(self, alert: Alert) -> Dict[str, Any]:
"""Format alert as Slack blocks."""
blocks = [
{
"type": "header",
"text": {
"type": "plain_text",
"text": f"{alert.get_priority_emoji()} {alert.title}"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": alert.message[:2900] # Slack limit
}
},
{
"type": "context",
"elements": [
{
"type": "mrkdwn",
"text": f"*Priority:* {alert.priority.value.upper()} | *Source:* {alert.source} | *Category:* {alert.category}"
}
]
}
]
if alert.actions:
actions_text = '\n'.join(f"• {a}" for a in alert.actions[:5])
blocks.append({
"type": "section",
"text": {
"type": "mrkdwn",
"text": f"*⚡ Recommended Actions:*\n{actions_text}"
}
})
blocks.append({"type": "divider"})
return {
"attachments": [{
"color": self._get_color(alert.priority),
"blocks": blocks
}]
}
async def send(self, alert: Alert) -> Tuple[bool, Optional[str]]:
"""Send alert to Slack."""
if not self.is_configured():
return False, "Slack not configured"
payload = self.format_blocks(alert)
try:
async with aiohttp.ClientSession() as session:
async with session.post(
self.webhook_url,
json=payload,
timeout=aiohttp.ClientTimeout(total=10)
) as response:
if response.status == 200:
logger.info("Slack alert sent")
return True, None
else:
error = await response.text()
logger.warn(f"Slack send failed: {response.status}")
return False, error
except Exception as e:
logger.error(f"Slack error: {e}")
return False, str(e)
class WebhookHandler(ChannelHandler):
"""
Generic webhook alert handler.
Sends alerts as JSON to configured webhook endpoints.
"""
def __init__(
self,
webhook_urls: List[str],
headers: Optional[Dict[str, str]] = None
):
"""
Initialize webhook handler.
Args:
webhook_urls: List of webhook URLs
headers: Optional custom headers
"""
self.webhook_urls = webhook_urls
self.headers = headers or {"Content-Type": "application/json"}
@property
def channel_type(self) -> AlertChannel:
return AlertChannel.WEBHOOK
def is_configured(self) -> bool:
return bool(self.webhook_urls)
async def send(self, alert: Alert) -> Tuple[bool, Optional[str]]:
"""Send alert to webhooks."""
if not self.is_configured():
return False, "Webhooks not configured"
payload = {
"event": "shadowhunter_alert",
"alert": alert.to_dict()
}
success_count = 0
errors = []
async with aiohttp.ClientSession() as session:
for webhook_url in self.webhook_urls:
try:
async with session.post(
webhook_url,
json=payload,
headers=self.headers,
timeout=aiohttp.ClientTimeout(total=10)
) as response:
if response.status in range(200, 300):
success_count += 1
logger.info(f"Webhook alert sent to {webhook_url[:50]}")
else:
errors.append(f"HTTP {response.status}")
logger.warn(f"Webhook failed: {response.status}")
except Exception as e:
errors.append(str(e))
logger.error(f"Webhook error: {e}")
if success_count == len(self.webhook_urls):
return True, None
elif success_count > 0:
return True, f"Partial: {len(errors)} failed"
else:
return False, '; '.join(errors)
class ConsoleHandler(ChannelHandler):
"""
Console output alert handler for development/testing.
"""
@property
def channel_type(self) -> AlertChannel:
return AlertChannel.CONSOLE
def is_configured(self) -> bool:
return True
async def send(self, alert: Alert) -> Tuple[bool, Optional[str]]:
"""Print alert to console."""
print("\n" + "=" * 60)
print(f"{alert.get_priority_emoji()} [{alert.priority.value.upper()}] ALERT")
print("=" * 60)
print(f"📋 {alert.title}")
print(f"\n{alert.message}")
print(f"\n• Source: {alert.source}")
print(f"• Category: {alert.category}")
print(f"• Time: {alert.timestamp.strftime('%Y-%m-%d %H:%M:%S UTC')}")
if alert.affected_domains:
print(f"• Affected: {', '.join(alert.affected_domains)}")
if alert.actions:
print("\n⚡ Recommended Actions:")
for i, action in enumerate(alert.actions, 1):
print(f" {i}. {action}")
print("=" * 60 + "\n")
return True, None
# ============================================================================
# ALERT MANAGER
# ============================================================================
class AlertManager:
"""
Unified alert management system.
Provides:
- Multi-channel alert routing
- Rate limiting and deduplication
- Delivery tracking and retries
- Alert aggregation for digests
Usage:
manager = AlertManager(config)
manager.register_channel(TelegramHandler(...))
await manager.send_alert(alert)
"""
def __init__(self, config: AlertConfig):
"""
Initialize alert manager.
Args:
config: Alert configuration
"""
self.config = config
self.handlers: Dict[AlertChannel, ChannelHandler] = {}
self.delivery_history: List[DeliveryRecord] = []
self.alert_hashes: Dict[str, datetime] = {} # For deduplication
self.rate_tracker = {"hour": 0, "day": 0}
self.last_reset = {"hour": datetime.now(), "day": datetime.now()}
self._lock = threading.Lock()
# Register console handler by default
self.register_channel(ConsoleHandler())
logger.info("Alert manager initialized", {
"max_per_hour": config.max_alerts_per_hour,
"max_per_day": config.max_alerts_per_day
})
def register_channel(self, handler: ChannelHandler):
"""
Register a channel handler.
Args:
handler: Channel handler to register
"""
self.handlers[handler.channel_type] = handler
logger.info(f"Registered channel: {handler.channel_type.value}", {
"configured": handler.is_configured()
})
def _check_rate_limit(self) -> bool:
"""Check if rate limit allows sending."""
now = datetime.now()
with self._lock:
# Reset hourly counter
if (now - self.last_reset["hour"]).total_seconds() > 3600:
self.rate_tracker["hour"] = 0
self.last_reset["hour"] = now
# Reset daily counter
if (now - self.last_reset["day"]).total_seconds() > 86400:
self.rate_tracker["day"] = 0
self.last_reset["day"] = now
# Check limits
if self.rate_tracker["hour"] >= self.config.max_alerts_per_hour:
return False
if self.rate_tracker["day"] >= self.config.max_alerts_per_day:
return False
return True
def _is_duplicate(self, alert: Alert) -> bool:
"""Check if alert is a duplicate within dedup window."""
dedup_key = alert.get_dedup_key()
with self._lock:
if dedup_key in self.alert_hashes:
last_sent = self.alert_hashes[dedup_key]
window = timedelta(minutes=self.config.dedup_window_minutes)
if datetime.now(timezone.utc) - last_sent < window:
return True
return False
def _record_alert(self, alert: Alert):
"""Record alert for deduplication."""
dedup_key = alert.get_dedup_key()
with self._lock:
self.alert_hashes[dedup_key] = alert.timestamp
self.rate_tracker["hour"] += 1
self.rate_tracker["day"] += 1
def _get_channels_for_priority(self, priority: AlertPriority) -> List[AlertChannel]:
"""Get channels to use for priority level."""
channel_names = self.config.routing_rules.get(priority.value, ["console"])
channels = []
for name in channel_names:
try:
channel = AlertChannel(name)
if channel in self.handlers and self.handlers[channel].is_configured():
channels.append(channel)
except ValueError:
pass
return channels
async def send_alert(
self,
alert: Alert,
force: bool = False,
channels: Optional[List[AlertChannel]] = None
) -> Dict[AlertChannel, DeliveryRecord]:
"""
Send alert through configured channels.
Args:
alert: Alert to send
force: Force send even if duplicate/rate limited
channels: Override channel selection
Returns:
Dictionary of channel -> delivery record
"""
results = {}
# Check rate limit
if not force and not self._check_rate_limit():
logger.warn("Alert rate limit exceeded", {
"alert_id": alert.id,
"hour_count": self.rate_tracker["hour"],
"day_count": self.rate_tracker["day"]
})
return results
# Check deduplication
if not force and self._is_duplicate(alert):
logger.info("Duplicate alert suppressed", {
"alert_id": alert.id,
"dedup_key": alert.get_dedup_key()
})
# Return suppressed record
for channel in self._get_channels_for_priority(alert.priority):
results[channel] = DeliveryRecord(
alert_id=alert.id,
channel=channel,
status=DeliveryStatus.SUPPRESSED,
attempt=0,
timestamp=datetime.now(timezone.utc)
)
return results
# Determine channels
target_channels = channels or self._get_channels_for_priority(alert.priority)
if not target_channels:
logger.warn("No channels configured for priority", {
"priority": alert.priority.value
})
return results
logger.info(f"Sending alert: {alert.title}", {
"alert_id": alert.id,
"priority": alert.priority.value,
"channels": [c.value for c in target_channels]
})
# Send to each channel
for channel in target_channels:
handler = self.handlers.get(channel)
if not handler:
continue
attempt = 1
success = False
error = None
while attempt <= self.config.max_retries and not success:
try:
success, error = await handler.send(alert)
if not success and attempt < self.config.max_retries:
logger.warn(f"Retry {attempt}/{self.config.max_retries} for {channel.value}")
await asyncio.sleep(self.config.retry_delay_seconds)
except Exception as e:
error = str(e)
logger.error(f"Channel error: {channel.value} - {e}")
attempt += 1
# Record delivery
record = DeliveryRecord(
alert_id=alert.id,
channel=channel,
status=DeliveryStatus.DELIVERED if success else DeliveryStatus.FAILED,
attempt=attempt - 1,
timestamp=datetime.now(timezone.utc),
error=error
)
results[channel] = record
self.delivery_history.append(record)
# Record alert for deduplication
self._record_alert(alert)
return results
async def send_batch(
self,
alerts: List[Alert],
parallel: bool = True
) -> Dict[str, Dict[AlertChannel, DeliveryRecord]]:
"""
Send multiple alerts.
Args:
alerts: List of alerts to send
parallel: Send alerts in parallel
Returns:
Dictionary of alert_id -> delivery results
"""
results = {}
if parallel:
tasks = [self.send_alert(alert) for alert in alerts]
delivery_results = await asyncio.gather(*tasks)
for alert, result in zip(alerts, delivery_results):
results[alert.id] = result
else:
for alert in alerts:
results[alert.id] = await self.send_alert(alert)
return results
def get_statistics(self) -> Dict[str, Any]:
"""Get alerting statistics."""
with self._lock:
# Count by status
status_counts = {}
channel_counts = {}
for record in self.delivery_history[-1000:]: # Last 1000
status = record.status.value
channel = record.channel.value
status_counts[status] = status_counts.get(status, 0) + 1
channel_counts[channel] = channel_counts.get(channel, 0) + 1
return {
"alerts_this_hour": self.rate_tracker["hour"],
"alerts_today": self.rate_tracker["day"],
"hourly_limit": self.config.max_alerts_per_hour,
"daily_limit": self.config.max_alerts_per_day,
"registered_channels": [c.value for c in self.handlers.keys()],
"configured_channels": [
c.value for c, h in self.handlers.items()
if h.is_configured()
],
"delivery_status_counts": status_counts,
"channel_counts": channel_counts,
"total_deliveries": len(self.delivery_history)
}
def get_recent_alerts(self, limit: int = 50) -> List[DeliveryRecord]:
"""Get recent delivery records."""
return self.delivery_history[-limit:]
# ============================================================================
# FACTORY FUNCTION
# ============================================================================
def create_alert_manager(
telegram_token: Optional[str] = None,
telegram_chat_ids: Optional[List[str]] = None,
discord_webhooks: Optional[List[str]] = None,
slack_webhook: Optional[str] = None,
custom_webhooks: Optional[List[str]] = None,
config: Optional[AlertConfig] = None
) -> AlertManager:
"""
Create and configure an alert manager.
Args:
telegram_token: Telegram bot token
telegram_chat_ids: Telegram chat IDs
discord_webhooks: Discord webhook URLs
slack_webhook: Slack webhook URL
custom_webhooks: Custom webhook URLs
config: Alert configuration
Returns:
Configured AlertManager
"""
config = config or AlertConfig()
manager = AlertManager(config)