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

在運維的平常工做中經常須要同監控打交道,而監控中最經常使用的功能介紹報警,最簡單的方式就是使用郵件進行報警,可是郵件報警不是特別及時(像我這種一天都不怎麼看郵件的估計得等服務掛了才知道),因此咱們須要一種及時通訊工具進行報警,常見的有短信,微信公衆號,QQ公衆號等,可是這三種方式在報警及時的同時也會在必定程度上打擾到咱們的生活,那麼有沒有一種既能及時傳遞信息又能不打擾到咱們平常的生活的那?? 
 
騰訊在微信以外還推出了一款相似於微信的應用,即便企業微信。企業微信通常只用於辦公全部不一樣可能會影響咱們的平常生活並且又能及時報警。
 
企業微信官網:https://work.weixin.qq.com/
 
 
企業微信登陸管理員後臺的頁面
 
python調用企業微信接口發送報警信息
 
 
 
 
點擊 "個人企業" 獲取企業 ID (等一下代碼中會用到)
 
python調用企業微信接口發送報警信息
 
 
 
 
點擊 "應用與小程序" 建立應用 (報警信息將發送到應用中)
 
python調用企業微信接口發送報警信息
 
 
 
 
根據要求填寫應用信息建立應用
 
python調用企業微信接口發送報警信息
 
 
 
 
獲取 Agentid 和 Secret (等一下代碼中會用到)
 
python調用企業微信接口發送報警信息python

 
 
 
 
代碼實現:mysql

#!/usr/bin/python # -*- coding: utf-8 -*- import json import requests class WeChat(object): def __init__(self, corpid, secret, agentid): self.url = "https://qyapi.weixin.qq.com" self.corpid = corpid self.secret = secret self.agentid = agentid # 獲取企業微信的 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, msg): values = { "touser": '@all', "msgtype": 'text', "agentid": self.agentid, "text": {'content': msg}, "safe": 0 } # python 3 # self.msg = (bytes(json.dumps(values), 'utf-8')) # python 2 self.msg = json.dumps(values) # 發送信息 def send_message(self, msg): self.access_token() self.messages(msg) 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') 使用示例: corpid = "xxxxxxx" secret = "xxxxxxx" agentid = "xxxxxx" msg = "mysql 出現錯誤" wechat = WeChat(corpid, secret, agentid) wechat.send_message(msg) 具體參數意義查看: https://open.work.weixin.qq.com/api/doc#10167
相關文章
相關標籤/搜索