python 之 企業微信報警
coding=utf8
Author:dongml
from urllib2 import urlopen
from urllib2 import Request
import sys, json
解決中文轉碼
reload(sys)
sys.setdefaultencoding( “utf-8” )
獲取企業微信token
def get_token(url, corpid, corpsecret):
token_url = ‘%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s’ % (url, corpid, corpsecret)
token = json.loads(urlopen(token_url).read().decode())[‘access_token’]
return token
構建告警資訊json
def messages(msg):
values = {
“touser”: ‘@all’,
“msgtype”: ‘text’,
“agentid”: 1000003, #注意修改為對應應用的agentid
,如圖有說明
“text”: {‘content’: msg},
“safe”: 0
}
msges=(bytes(json.dumps(values)))
return msges
傳送告警資訊
def send_message(url,token, data):
send_url = ‘%s/cgi-bin/message/send?access_token=%s’ % (url,token)
respone=urlopen(Request(url=send_url, data=data)).read()
x = json.loads(respone.decode())[‘errcode’]
# print(x)
if x == 0:
print (‘Succesfully’)
else:
print (‘Failed’)
corpid = ‘wxxx’
corpsecret = ‘Txxx’
url = ‘https://qyapi.weixin.qq.com’
msg=’企業微信測試’
函式呼叫
test_token=get_token(url, corpid, corpsecret)
msg_data= messages(msg)
send_message(url,test_token, msg_data)
說明:corpid在管理後臺:我的企業—》企業資訊—》企業ID
:corpsecret需要建立自建應用:企業應用—》自建應用。如下圖!(https://img-blog.csdn.net/20180717200552373?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3FxXzM1Mjk5ODYz/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70