企业微信做运维通知教程

每次使用邮件(不方便) 或者 短信(没钱)。
穷人用法。毕竟能少就剩了不少钱。省的就是赚的。

代码只需稍微改下参数。跟逻辑代码就可以搬走。能不能搬走就你自己本事咯。

#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author : chencxiaoyu
# Email  : [email protected]
# Date   : 2017/6/12
# Readme :

import time
import requests
import json


# 企业微信应用信息
corpid = 'xxx',
corpsecret = 'yyy'
agentid = 1000002
# 报警通知联系人账号
NOTICE_USER_LIST = "ChenXiaoYu"

class weixinClass(object):
    def __init__(self):
        self.token = self.get_token()

    def get_token(self):
        token_url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken'
        values = {'corpid': corpid, 'corpsecret': corpsecret}
        req = requests.get(token_url, values)
        if req.status_code == 200:
            data = json.loads(req.text)
            if data.get('errcode') == 0:
                print 'get token OK'
                return data["access_token"]

            else:
                print data
        else:
            print req.text
        return ''

    def send_msg(self, msg, to_user=NOTICE_USER_LIST):
        send_msg_url = "https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + self.token
        now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
        print self.token
        if isinstance(msg, str):
            msg = msg + '
发送时间:' + now_time elif isinstance(msg, unicode): msg = msg + u'
发送时间:' + now_time data = { "touser": to_user, "msgtype": "text", "agentid": agentid, "text": { "content": msg } } req = requests.post(send_msg_url, data=json.dumps(data)) if req.status_code == 200: data = json.loads(req.text) errcode = data.get('errcode') # token过期或者过期,重新获取token并重新发送本条信息 if errcode in [41001, 42001]: print 'Send message False, to resend!' self.token = self.get_token() self.send_msg(msg) if errcode == 0: print 'Send message OK' else: print "http_code: %s, error: %s" % (req.status_code, req.text) if __name__ == '__main__': a = weixinClass() a.send_msg(u'111测试微信报警功能')

你可能感兴趣的:(企业微信做运维通知教程)