企业微信自定义应用发送消息Python脚本

149 次查看 0 条评论

本脚本可用于zabbix告警,通过调用该脚本给用户发送告警信息。

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys,requests,time,json
reload(sys)
sys.setdefaultencoding('utf8')
# 企业微信相关配置信息
corpid = 'ww76be1f123c5c4asc'
agentid = '1000002'
corpsecret = 'Cthlu-g_tnzql8w7Hybouy94nKt4wPWZrVYQxD3lds'
# 获取access_oken函数(已实现缓存机制)
def get_access_token(corpid,corpsecret) :
    path = './access_token.json'
    with open(path,'r') as f :
        access_token = json.loads(f.readline())
        if access_token['expires_time'] < int(time.time()) :
            url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid={corpid}&corpsecret={corpsecret}'
            url_rep = url.format(corpid=corpid,corpsecret=corpsecret)
            res = requests.get(url_rep,timeout=5)
            if res.status_code == 200 :
                json_text = res.text
                access_token = json.loads(json_text)
                access_token['expires_time'] = int(time.time())+7000
                with open(path,'w+') as f:
                    f.write(json.dumps(access_token))
                    f.close()
        return access_token['access_token']
# 发送消息函数(文本消息)
def send_msg(userId,msg) :
    url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token={ACCESS_TOKEN}'
    token = get_access_token(corpid,corpsecret)
    url_rep = url.format(ACCESS_TOKEN=token)
    data = {
       "touser" : userId,
       "msgtype" : "text",
       "agentid" : agentid,
       "text" : {
           "content" : msg
       },
       "safe":0
    }
    res = requests.post(url_rep,data=json.dumps(data,'utf-8'),timeout=5)
    if res.status_code == 200 :
        print res.text
    else :
        print 'Send message failed, response code ',res.status_code,'.'
# 程序入口
if __name__ == "__main__" :
    send_msg('qy01ed322795cce8cf53beb40c20','主机:dctest1\n分区/data1可用空间不足10%。\n告警时间:2019-03-22 11:14')

配置下 corpid,agentid,corpsecret 这三个企业微信相关参数,执行脚本即可发送消息。

80230-scl8qi73bl.png

Python 微信 , 监控

暂无评论,快来抢沙发。