diff --git a/README.md b/README.md index 2dca44d..1b41ca8 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,10 @@ Provide ways to send notifications to signal-cli through webhooks virtualenv -p python3 --system-site-packages venv source venv/bin/activate pip install -r requirements.txt + +# Configure +cp signal_webhook/configuration.sample.py signal_webhook/configuration.py +$EDITOR signal_webhook/configuration.py ``` **Beware!** Sending messages to Signal requires `gi`, which cannot be installed diff --git a/signal_webhook/.gitignore b/signal_webhook/.gitignore new file mode 100644 index 0000000..7c0b746 --- /dev/null +++ b/signal_webhook/.gitignore @@ -0,0 +1 @@ +configuration.py diff --git a/signal_webhook/app.py b/signal_webhook/app.py index ffcf84e..b600c9a 100644 --- a/signal_webhook/app.py +++ b/signal_webhook/app.py @@ -1,6 +1,8 @@ import typing as t +from collections import defaultdict from flask import Flask, request from . import signal +from . import configuration app = Flask(__name__) @@ -13,6 +15,7 @@ def root() -> t.Tuple[str, int]: @app.route("/alertmanager", methods=["POST"]) def alertmanager(): data = request.get_json(cache=False) + if "version" not in data or int(data["version"]) != 4: return "Bad API version", 400 if "alerts" not in data: @@ -23,5 +26,22 @@ def alertmanager(): # Ignore return "OK", 200 + severities = defaultdict(int) + alert_lines = [] for alert in data["alerts"]: - ... + try: + severities[alert["labels"]["severity"]] += 1 + alert_lines.append( + f"<{alert['labels']['alertname']}> {alert['annotations']['description']}" + ) + except KeyError as exn: + alert_lines.append(f"(malformed alert — {exn})") + + msg = f"[PROMETHEUS] {len(data['alerts'])} firing: " + msg += ", ".join([f"{count} {typ}" for typ, count in severities.items()]) + msg += "\n\n" + msg += "\n".join(["* " + line for line in alert_lines]) + + signal.signal_send(configuration.RECIPIENTS[configuration.DEFAULT_RECIPIENT], msg) + + return "OK", 200 diff --git a/signal_webhook/configuration.sample.py b/signal_webhook/configuration.sample.py new file mode 100644 index 0000000..bc1920b --- /dev/null +++ b/signal_webhook/configuration.sample.py @@ -0,0 +1,5 @@ +# Signal 'address book' +RECIPIENTS = {"foo": "+42..."} # FIXME + +# Recipient from the dict above to send to by default +DEFAULT_RECIPIENT = "foo" # FIXME