diff --git a/Readme.md b/Readme.md index 7a1921e..6924dd1 100644 --- a/Readme.md +++ b/Readme.md @@ -54,13 +54,13 @@ Use [sample config](./config.sample.yaml) as an example. - [ ] Notification services - [x] Discord - [x] Gotify - - [ ] Mattermost + - [x] Mattermost - [ ] Slack - [ ] Telegram - [ ] Automation (GitHub Actions) - [ ] Coverage tests - [x] pre-commit - - [ ] Trivy security scan + - [x] Trivy security scan - [x] Docker build & push (latest + releases) ## References diff --git a/config.sample.yaml b/config.sample.yaml index becd815..f9cb6be 100644 --- a/config.sample.yaml +++ b/config.sample.yaml @@ -23,6 +23,11 @@ notifications: webhook: toto username: kube-notify # avatar_url: changeme + mattermost: + webhook: https://chat.local/hooks/aaaaaaaaa + # username: kube-notify + # icon_url: https://kubernetes.io/images/k8s-10th-birthday.svg + # channel: Kube-notify custom_group: resources: - name: customResources diff --git a/kube_notify/mattermost.py b/kube_notify/mattermost.py new file mode 100644 index 0000000..303e522 --- /dev/null +++ b/kube_notify/mattermost.py @@ -0,0 +1,30 @@ +import json + +import requests + +import kube_notify.logger as logger + + +def send_mattermost_message( + url: str, + title: str, + description: str, + fields: dict, + channel: str | None = None, + username: str | None = None, + icon_url: str | None = None, +) -> None: + # Construct the HTTP request for sending a message to Mattermost + headers = {"Content-Type": "application/json"} + message = f"### {title}\n\n" + message += f"**Description : {description}**\n\n" + + for key, value in fields.items(): + message += f"*{key} :*\n{value}\n\n" + data = {"text": message} + channel and data.update({"channel": channel}) + username and data.update({"username": username}) + icon_url and data.update({"icon_url": icon_url}) + response = requests.post(url, headers=headers, data=json.dumps(data)) + if response.status_code != 200: + logger.logger.error("Failed to send notification to Mattermost") diff --git a/kube_notify/notifications.py b/kube_notify/notifications.py index f13811b..3706e8e 100644 --- a/kube_notify/notifications.py +++ b/kube_notify/notifications.py @@ -2,6 +2,7 @@ import kube_notify.discord as discord import kube_notify.gotify as gotify import kube_notify.logger as logger +import kube_notify.mattermost as mattermost import kube_notify.selectors as selectors @@ -72,4 +73,15 @@ async def handle_notify( description, fields, ) + if group_values := group.get("mattermost"): + notifs.append(f"{group_name}/mattermost") + mattermost.send_mattermost_message( + group_values["url"], + title, + description, + fields, + group_values.get("channel"), + group_values.get("username"), + group_values.get("icon_url"), + ) logger.logger.info(f"{event_info[0]} [{','.join(notifs)}] {description}")