From 2d232fe1f7b8f0839e9219e3eb4fff7823d61fe7 Mon Sep 17 00:00:00 2001 From: Guilhem Saurel Date: Sat, 31 Jul 2021 13:06:36 +0200 Subject: [PATCH] add grafana formatter This was initially designed and implemented in #4 Co-authored-by: Sven Seeberg --- CHANGELOG.md | 1 + matrix_webhook/__main__.py | 8 +++++++- matrix_webhook/formatters.py | 15 +++++++++++++++ 3 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 matrix_webhook/formatters.py diff --git a/CHANGELOG.md b/CHANGELOG.md index baff78f..d7778fc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +- add grafana formatter - add formatted_body to bypass markdown with direct [matrix-custom-HTML](https://matrix.org/docs/spec/client_server/r0.6.1#m-room-message-msgtypes) - allow "key" to be passed as a parameter diff --git a/matrix_webhook/__main__.py b/matrix_webhook/__main__.py index 005a3eb..c1ac638 100644 --- a/matrix_webhook/__main__.py +++ b/matrix_webhook/__main__.py @@ -16,7 +16,7 @@ from nio import AsyncClient from nio.exceptions import LocalProtocolError from nio.responses import RoomSendError -from . import conf +from . import conf, formatters ERROR_MAP = {"M_FORBIDDEN": HTTPStatus.FORBIDDEN} @@ -46,6 +46,12 @@ async def handler(request): if "key" in request.rel_url.query and "key" not in data: data["key"] = request.rel_url.query["key"] + if "formatter" in request.rel_url.query: + try: + data = getattr(formatters, request.rel_url.query["formatter"])(data) + except AttributeError: + return create_json_response(HTTPStatus.BAD_REQUEST, "Unknown formatter") + if not all(key in data for key in ["body", "key"]): return create_json_response( HTTPStatus.BAD_REQUEST, "Missing body and/or API key property" diff --git a/matrix_webhook/formatters.py b/matrix_webhook/formatters.py new file mode 100644 index 0000000..1e4600e --- /dev/null +++ b/matrix_webhook/formatters.py @@ -0,0 +1,15 @@ +"""Formatters for matrix webhook.""" + + +def grafana(data): + """Pretty-print a grafana notification.""" + text = "" + if "title" in data: + text = "### " + data["title"] + "\n" + if "message" in data: + text = text + data["message"] + "\n\n" + if "evalMatches" in data: + for match in data["evalMatches"]: + text = text + "* " + match["metric"] + ": " + str(match["value"]) + "\n" + data["body"] = text + return data