matrix-alertbot/matrix_alertbot/alert.py
2022-07-28 11:11:50 +02:00

67 lines
1.8 KiB
Python

from __future__ import annotations
import logging
from typing import Dict
logger = logging.getLogger(__name__)
class Alert:
EMOJIS = {"critical": "🔥", "warning": "⚠️", "resolved": "🥦"}
COLORS = {"critical": "dc3545", "warning": "ffc107", "resolved": "33cc33"}
def __init__(
self,
fingerprint: str,
url: str,
labels: Dict[str, str],
annotations: Dict[str, str],
firing: bool = True,
):
self.fingerprint = fingerprint
self.url = url
self.firing = firing
self.labels = labels
self.annotations = annotations
if self.firing:
self.status = self.labels["severity"]
else:
self.status = "resolved"
@staticmethod
def from_dict(data: Dict) -> Alert:
return Alert(
fingerprint=data["fingerprint"],
url=data["generatorURL"],
firing=data["status"] == "firing",
labels=data["labels"],
annotations=data["annotations"],
)
@property
def emoji(self) -> str:
return self.EMOJIS[self.status]
@property
def color(self) -> str:
return self.COLORS[self.status]
def plaintext(self) -> str:
alertname = self.labels["alertname"]
description = self.annotations["description"]
return f"[{self.emoji} {self.status.upper()}] {alertname}: {description}"
def html(self) -> str:
alertname = self.labels["alertname"]
job = self.labels.get("job", "")
if job:
job = f"({job})"
description = self.annotations["description"]
return (
f"<font color='#{self.color}'><b>[{self.emoji} {self.status.upper()}]</b></font> "
f"<a href='{self.url}'>{alertname}</a> {job}<br/>{description}"
)