1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| from flask import Flask, request, jsonify import time import requests import re
app = Flask(__name__)
TELEGRAM_BOT_TOKEN = 'your token' TELEGRAM_CHAT_ID = 'your chat id'
def extract_nodename(text): match = re.search(r'nodename:([^\s\]]+)', text) if match: return match.group(1) else: return None
def send_message_to_telegram(text): url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage" payload = { 'chat_id': TELEGRAM_CHAT_ID, 'text': text, 'parse_mode': 'Markdown' } response = requests.post(url, json=payload) return response
@app.route('/webhook', methods=['POST']) def webhook(): try: data = request.json print("Received data:", data) alerts = data.get('alerts', []) for alert in alerts: status = alert.get('status', 'unknown') labels = alert.get('labels', {}) annotations = alert.get('annotations', {}) instance = labels.get('instance', 'unknown') summary = annotations.get('summary', '-') description = annotations.get('description', 'No description')
nodename = extract_nodename(description)
if status == 'firing': message = f"*告警:* {summary}\n*主机:* {nodename}\n*描述:* {description}" elif status == 'resolved': message = f"**已恢复**\n*恢复:* {summary}\n*主机:* {nodename}\n*描述:* {description}" send_message_to_telegram(message) return jsonify({'status': 'success'}) except Exception as error: app.logger.info("\t%s",error) print(f"\t{error}\n") return jsonify({'status': 'fail', 'reason': f"error: {error}"})
if __name__ == '__main__': app.run(host='0.0.0.0', port=5001)
|