1. 程式人生 > >python調用企業微信接口發送報警信息

python調用企業微信接口發送報警信息

adf elf 企業微信 cto tid 應用信息 gen lse user

在運維的日常工作中常常需要同監控打交道,而監控中最常用的功能介紹報警,最簡單的方式就是使用郵件進行報警,但是郵件報警不是特別及時(像我這種一天都不怎麽看郵件的估計得等服務掛了才知道),所以我們需要一種及時通信工具進行報警,常見的有短信,微信公眾號,QQ公眾號等,但是這三種方式在報警及時的同時也會在一定程度上打擾到我們的生活,那麽有沒有一種既能及時傳遞信息又能不打擾到我們日常的生活的那??

騰訊在微信之外還推出了一款類似於微信的應用,即使企業微信。企業微信一般只用於辦公所有不同可能會影響我們的日常生活而且又能及時報警。

企業微信官網:https://work.weixin.qq.com/


企業微信登錄管理員後臺的頁面

技術分享圖片




點擊 "我的企業" 獲取企業 ID (等一下代碼中會用到)

技術分享圖片




點擊 "應用與小程序" 創建應用 (報警信息將發送到應用中)

技術分享圖片




根據要求填寫應用信息創建應用

技術分享圖片




獲取 Agentid 和 Secret (等一下代碼中會用到)

技術分享圖片





代碼實現:

import json
import requests

class WeChat(object):
    def __init__(self, corpid, secret, agentid, msg):
        self.url = "https://qyapi.weixin.qq.com"
        self.corpid = corpid
        self.secret = secret
        self.agentid = agentid
        self.msg = msg

    # 獲取企業微信的 access_token
    def access_token(self):
        url_arg = ‘/cgi-bin/gettoken?corpid={id}&corpsecret={crt}‘.format(id=self.corpid, crt=self.secret)
        url = self.url + url_arg
        response = requests.get(url=url)
        text = response.text
        self.token = json.loads(text)[‘access_token‘]

    # 構建消息格式
    def messages(self):
        values = {
            "touser": ‘@all‘,
            "msgtype": ‘text‘,
            "agentid": self.agentid,
            "text": {‘content‘: self.msg},
            "safe": 0
        }
        self.msg = (bytes(json.dumps(values), ‘utf-8‘))

    # 發送信息
    def send_message(self):
        self.access_token()
        self.messages()

        send_url = ‘{url}/cgi-bin/message/send?access_token={token}‘.format(url=self.url, token=self.token)
        response = requests.post(url=send_url, data=self.msg)
        errcode = json.loads(response.text)[‘errcode‘]

        if errcode == 0:
            print(‘Succesfully‘)
        else:
            print(‘Failed‘)

具體參數意義查看:  https://open.work.weixin.qq.com/api/doc#10167

python調用企業微信接口發送報警信息