Skip to content

Instantly share code, notes, and snippets.

@mordaha
Last active January 21, 2019 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mordaha/1dccf895af447543fd88be17259a3570 to your computer and use it in GitHub Desktop.
Save mordaha/1dccf895af447543fd88be17259a3570 to your computer and use it in GitHub Desktop.
Simple telegram bot for alertmanager webhook alerting
#!python
# coding: utf-8
from sanic import Sanic
from sanic.response import json
from telegram import Bot
TOKEN = 'bot token'
CHAT_ID = 'chat id'
emoji_map = {
"resolved": "✅",
"firing": "🔥",
}
bot = Bot(TOKEN)
app = Sanic()
@app.route("/")
async def test(request):
return json({"status": "ok"})
#
# Sample Alert:
#
# {
# "receiver": "alertmananger-bot",
# "status": "firing",
# "alerts": [{
# "status": "firing",
# "labels": {
# "alertname": "main_site",
# "instance": "https://site.tld",
# "job": "blackbox-domaintest",
# "monitor": "monitoring",
# "severity": "critical"
# },
# "annotations": {
# "description": "Site down: https://site.tld",
# "summary": "Site down: https://site.tld"
# },
# "startsAt": "2019-01-21T12:32:02.491139969Z",
# "endsAt": "2019-01-21T12:35:02.491139969Z",
# "generatorURL": "http://51900cf0db25:9090/graph?g0.expr=probe_success+%21%3D+1&g0.tab=1"
# }],
# "groupLabels": {},
# "commonLabels": {
# "alertname": "main_site",
# "instance": "https://site.tld",
# "job": "blackbox-domaintest",
# "monitor": "monitoring",
# "severity": "critical"
# },
# "commonAnnotations": {
# "description": "Site down: https://site.tld",
# "summary": "Site down: https://site.tld"
# },
# "externalURL": "http://77ae3b802079:9093",
# "version": "4",
# "groupKey": "{}:{}"
# }
@app.route("/alert-webhook", methods=["POST",])
async def alert_webhook(request):
# print('RECEIVED: ', request.json)
for alert in request.json.get('alerts', []):
icon = emoji_map.get(alert.get('status'), '')
message = """{} {}, name={} for instance={}
{}
""".format(
icon,
alert['status'],
alert['labels'].get('alertname', ''),
alert['labels'].get('instance', ''),
alert['annotations'].get('description'),
)
bot.send_message(CHAT_ID, message, disable_web_page_preview=True, )
return json({"status": "ok"})
if __name__ == "__main__":
bot.send_message(CHAT_ID, "Shields up, weapons online!", disable_web_page_preview=True, )
app.run(host="0.0.0.0", port=8000)
@mordaha
Copy link
Author

mordaha commented Jan 21, 2019

pip requirements:

sanic
python-telegram-bot

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment