Skip to content
Snippets Groups Projects
rocketchat-bot.py.j2 2.37 KiB
Newer Older
  • Learn to ignore specific revisions
  • nd's avatar
    nd committed
    #!/usr/bin/env python3
    import os
    import sys
    from dateutil import parser
    import json, logging
    from flask import Flask, request
    from rocketchat_API.rocketchat import RocketChat
    from requests import sessions
    
    
    listenPort = 29120
    listenIP = '::1'
    botUser = '{{ prometheus_alertmanager.rocketchatbot.user }}'
    botPass = '{{ prometheus_alertmanager.rocketchatbot.pass }}'
    botChatURL ='{{ prometheus_alertmanager.rocketchatbot.url }}'
    
    app = Flask(__name__)
    app.secret_key = os.urandom(128)
    
    api_session = sessions.Session()
    api = RocketChat(botUser, botPass, server_url=botChatURL, session=api_session)
    
    @app.route('/<chatName>/alert', methods = ['POST'])
    def postAlertmanager(chatName):
    	try:
    		content = json.loads(request.get_data())
    		for alert in content['alerts']:
    			message = "Status: "+alert['status']+"\n"
    			if 'name' in alert['labels']:
    				message += "Instance: "+alert['labels'].get('instance', 'unknown')+"("+alert['labels']['name']+")\n"
    			else:
    				message += "Instance: "+alert['labels'].get('instance', 'unknown')+"\n"
    			if 'info' in alert['annotations']:
    				message += "Info: "+alert['annotations']['info']+"\n"
    			if 'summary' in alert['annotations']:
    				message += "Summary: "+alert['annotations']['summary']+"\n"
    			if 'description' in alert['annotations']:
    				message += "Description: "+alert['annotations']['description']+"\n"
    			if alert['status'] == "resolved":
    				correctDate = parser.parse(alert['endsAt']).strftime('%Y-%m-%d %H:%M:%S')
    				message += "Resolved: "+correctDate+"\n"
    			elif alert['status'] == "firing":
    				correctDate = parser.parse(alert['startsAt']).strftime('%Y-%m-%d %H:%M:%S')
    				message += "Started: "+correctDate+"\n"
    			message += "labels: \n"
    			message += "```\n"
    			labels = ""
    			for l in alert['labels']:
    				labels += l + " : "+alert['labels'][l] + "\n"
    			message += labels + "```"
    			if api.chat_post_message(message, channel=chatName, alias='Alertmanager').ok:
    				return "Alert OK", 200
    			else:
    				return "Alert fail", 200
    	except Exception as error:	   
    		bot.sendMessage(chat_id=chatID, text="Error to read json: "+str(error))
    		app.logger.info("\t%s",error)
    		return "Alert fail", 200
    
    if __name__ == '__main__':
    	if len(sys.argv) == 1:
    		logging.basicConfig(level=logging.INFO)
    		app.run(host=listenIP, port=listenPort)
    	else:
    		from gevent.pywsgi import WSGIServer
    		http_server = WSGIServer((listenIP, listenPort), app)
    		http_server.serve_forever()