grafana告警发到企业微信带有图片

 先来一波效果展示图
grafana告警发到企业微信带有图片的源码,该代码需要已经调试通。

主函数 

grafana2WebchatImage]$ cat grafana2WebchatImage.py 
from flask import request
from flask import Flask
import re
import urllib.request
import json
import os
import wechat_work_webhook
from downloadImage import download_pic

def Open(s):
    Path = '/home/we/temp.json'
    if os.path.exists(Path):
        os.remove(Path)
    f = open(Path, 'w')
    print(s, file = f)
    f.close()


def GetData():
    PostData = request.get_data()
    Data = json.loads(PostData)
    JsonData = json.dumps(Data, ensure_ascii=False, indent=4)
    #print(type(Data))
    return Data

app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False


@app.route('/wechat/<token>', methods=['POST'])
def IssueCreate(token):
    #print('###########')
    #print(GetData())
    #print('###########')
    des = GetData()['commonAnnotations']['summary']
    title =GetData()['commonLabels']['alertname']
    state = GetData()['status']
    panelURL = GetData()['alerts'][0]['panelURL']
    time = GetData()['alerts'][0]['startsAt']
    t1 = str(re.findall(r"(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})", time))
    t2 = str(re.sub("T", " ", t1))
    wechat = wechat_work_webhook.connect(
        "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key="+token)
    wechat.markdown('状态: ' + '['+ state +']' + '\n'
                    '告警主题: ' + title +'\n'
                    '告警信息: '+ des +'\n'
                    '告警时间:' + t2 + '\n'
                    '告警图表: ' + panelURL
                    )
    #if state == 'firing'
    regex = r"%s(.*?)%s" % ("29:3000/d/", "?orgId=1")
    dashboarduid = re.findall(regex, panelURL)
    #print(dashboarduid)
    pannelid = re.split('=', panelURL)
    #print(pannelid[2])
    filename = download_pic(dashboarduid,pannelid[2])
    wechat.image(filename)
    #wechat.text('狼来了',['@all'])
    return "OK"

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=8888)

图片下载函数:

# -*- coding: UTF-8 -*- 
import requests
import time,sys

# 下载pic
def download_pic(dashboarduid,pannelid):
    print(dashboarduid)
    print(pannelid)
    grafana_server = "http://192.10"
    url = "http://192.0/render/d-solo/"+str(dashboarduid[0])+"/?orgId=1&refresh=2m&from=now-1h&to=now&panelId="+str(pannelid)+"&width=1000&height=500&tz=Asia%2FShanghai"
    print(url)
 
    header = {"Content-Type": "application/json","Authorization": "Bearer glsa_imO5ll"} # 用管理员去Grafana生成API Key
    res = requests.get(url,headers=header)
    time_now = int(time.time())
    time_local = time.localtime(time_now)
    dt = time.strftime("%Y-%m-%d-%H-%M-%S",time_local)
    img_name = "img"+dt+".jpg"
    filename =  img_name
    with open(filename, "wb") as f:
        f.write(res.content)

        return filename

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

容器云服务

如果对你有用,一块钱也是爱。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值