python利用企業微信api來進行發送自定義報警的類實現

python利用企業微信api來進行發送自定義報警的類實現

  1. 企業微信註冊

    打開http://work.weixin.qq.com/企業微信主頁;

    wKioL1mQWsHgzC_4AAUT2UUM0Nw651.png-wh_50a

    點擊企業註冊;

wKioL1mQWyHz_PniAAB76ksmaao280.png-wh_50

填寫相關信息,營業執照和註冊號可以不用填,直接下一步,按照提示操作即可;

註冊完成後,登陸,就顯示如下界面:

wKiom1mQXEbTXR84AAD2Y4eqMnc163.png-wh_50

點擊我的企業標籤:

wKioL1mQXMuzIM8CAACK0TjYlnM839.png-wh_50

看到如上界面,複製CorpID對應的值;

點擊企業應用

wKiom1mQXWfilkKhAAB28XmBUZI997.png-wh_50

點擊 創建應用

wKioL1mQXciBgtotAABo__DcRVg329.png-wh_50

填寫對應內容,點擊創建應用即可;

然後再點擊企業應用,就可以在自建應用裏看到自己創建的應用;

點擊應用圖標,看到如下圖

wKioL1mQXjKDZtrIAACidJ1quzE226.png-wh_50

複製AgentId、Secret

至此我們需要的三個值就都有(AgentId、Secret、CorpID

2.程序實現

接下來我們用python的類來實現

git clone https://github.com/yxxhero/weixinalarm.git

#!/usr/bin/env python
# encoding: utf-8
# -*- coding: utf8 -*-
import urllib
import urllib2
import json
import sys
import time
import os
import logging
reload(sys)
sys.setdefaultencoding('utf8')
#日誌模式初始化
logging.basicConfig(level="DEBUG",
                format='%(asctime)s  %(levelname)s %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S',
                filename='./log/status.log',
                filemode='a')
class weixinalarm(object):
    def __init__(self,corpid,secrect,agentid): #構造函數,獲取關鍵變量
        self.corpid=corpid
        self.secrect=secrect
        self.agentid=agentid
    def get_access_token(self): #獲取token
        access_token_url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid="+self.corpid+"&corpsecret="+self.secrect
        try:
            res_data = urllib2.urlopen(access_token_url,timeout=3)
            access_token=json.loads(res_data.read())["access_token"]
        except Exception,e:
            logging.info(str(e))
            logging.info("access_token獲取超時")
            return None 
        else:
            return access_token
    def check_token(self): #檢查token的緩存文件是否存在或者超時,如果不存在或者超時重新獲取。
        if os.path.exists("/tmp/weixinalarm"):
            with open("/tmp/weixinalarm","r+") as fd:
	        result_info=fd.read().split("^")
                timestamp=result_info[1]
                if time.time()-int(timestamp) <7200:
                    access_token=result_info[0]
		    return access_token
                else:
                    access_token=self.get_access_token()
                    timestamp=time.time()
                    tokentime=access_token+"^"+str(timestamp).split(".")[0]
                    with open("/tmp/weixinalarm","w") as fd:
                        fd.write(tokentime)
		    return access_token
        else:
            access_token=self.get_access_token()
            timestamp=time.time()
            tokentime=access_token+"^"+str(timestamp).split(".")[0]
            with open("/tmp/weixinalarm","w") as fd:
                fd.write(tokentime)
	    return access_token
    def sendmsg(self,title,description): #利用api發送消息,具體的api格式可以參考官方文檔
        try:
	    access_token=self.check_token()
            if access_token:
                send_url="https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token="+access_token
                send_info={
	        	"touser" : "@all",
	        	"msgtype" : "text",
	        	"agentid" : self.agentid,
                "text":{
                    "content":str(title)+":"+str(description)
                    }
	        	}
                logging.info(send_info)
                send_info_urlencode = json.dumps(send_info)
                #send_info_urlencode = json.dumps(send_info,ensure_ascii=False)
                req=urllib2.Request(url = send_url,data =send_info_urlencode)
                response=urllib2.urlopen(req,timeout=3)
                res_info=response.read()
            else:
                logging.error("no access_token")
        except Exception,e:
            logging.error(str(e))
        else:
            alarm_result=json.loads(res_info)
            if int(alarm_result["errcode"])==0:
                logging.info("報警正常")
            else:
                logging.info(alarm_result["errmsg"])
        finally:
            if response:
                response.close()

代碼很簡單,有想和我交流的可以加我微信18333610114

基本使用:

from weixinalarm import weixinalarm
sender=weixinalarm(corpid=Secret,secrect=Secret,agentid=AgentId)
發送消息:
sender.sendmsg(title="自定義",description="自定義")
即可
日誌放在log下,log目錄需自行創建,和weixinalarm.py同級即可;
教程完畢。



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章