alertmanager-bark-hook/views/apis/bark_service.py
2022-08-17 16:58:45 +08:00

68 lines
2.6 KiB
Python

from flask import request, render_template
from flask_restful import Resource
from utils.error_handler import error_handler
from app.app import app
from app.api import api
from munch import Munch
import requests
class BarkResource(Resource):
def post(self):
try:
data = Munch.fromDict(request.get_json(silent=True))
app.logger.debug(data)
config = Munch.fromDict(app.config["APP_CONFIG"])
content = Munch.fromDict({
'title': config.title.firing if data.status == 'firing' else config.title.resolved if data.status == 'resolved' else config.title.default,
'category': 'category'
})
# TODO: alertmanager message to bark content.
'''
{
"version": "4",
"groupKey": <string>, // key identifying the group of alerts (e.g. to deduplicate)
"truncatedAlerts": <int>, // how many alerts have been truncated due to "max_alerts"
"status": "<resolved|firing>",
"receiver": <string>,
"groupLabels": <object>,
"commonLabels": <object>,
"commonAnnotations": <object>,
"externalURL": <string>, // backlink to the Alertmanager.
"alerts": [
{
"status": "<resolved|firing>",
"labels": <object>,
"annotations": <object>,
"startsAt": "<rfc3339>",
"endsAt": "<rfc3339>",
"generatorURL": <string>, // identifies the entity that caused the alert
"fingerprint": <string> // fingerprint to identify the alert
},
...
]
}
'''
content.body = render_template(config.template_file, **data)
app.logger.debug(content.body)
for to in config.to:
content.device_key = to
response = requests.post(
url = config.bark_api,
headers = {
"Content-Type": "application/json; charset=utf-8",
},
json=content
)
app.logger.info(response)
return {
'success': True,
'message': '',
'data': {},
}
except Exception as e:
return error_handler(e)
api.add_resource(BarkResource, '/api/send')