大家好,我是Linux运维工程师 Linke 。技术过硬,从不挖坑~
某些脚本监控的东西,发送邮件出来礼拜天顾不上看,俺们又没有专门负责通知监控报警的人员。
钉钉礼拜天看的频率毕竟没有微信的高,因此把重要报警通过微信、电话、短信发出来,是很靠谱的。于是乎,Linke就写了个微信报警模块儿,在各个自开发的监控接口中加入此通知模块儿。
#-*- coding:utf-8 -*-
#corpid 从企业微信页面的 My Company/Company ID 获取
#corpsecret 从企业微信页面的 App Management/Self-built/自建群/Secret 获取
#agentid 从企业微信页面的 App Management/Self-built/自建群/AgentId 获取
#mes 为报警内容
#touser(不加发给群里所有人)
#如果要发送消息给群中某几个人接收,那么给 touser 传这样的值(微信名): YangLinJiangJun|BaoSiRiAoDao|YiShiYi
import requests
import json
def sWx(corpid,corpsecret,agentid,mes,touser="@all"):
url = "https://qyapi.weixin.qq.com"
tokenurl = "%s/cgi-bin/gettoken?corpid=%s&corpsecret=%s"%(url,corpid,corpsecret)
response_token = requests.get(url=tokenurl)
text = response_token.text
token = json.loads(text)['access_token']
###
mesdic = {
"touser" : touser,
"toparty" : "@all",
"totag" : "@all",
"msgtype" : "text",
"agentid" : agentid,
"text" : {"content" : mes},
"safe" : 0,
"enable_id_trans" : 0
}
send_url = '%s/cgi-bin/message/send?access_token=%s'%(url,token)
response = requests.post(url=send_url,data=json.dumps(mesdic))
errcode = json.loads(response.text)['errcode']
if errcode == 0:
print('Succesfully')
return 0
else:
print('Failed')
return 1
if __name__ == "__main__":
mesd = "测试python代码调用微信接口"
corpid = "wwd2675aba78a0c2345"
agentid = 1000004
corpsecret = "Hqdfsbw8jWDfv5AtW5DxI56gpMdf34grAfqSDFGwJjA"
sWx(corpid,corpsecret,agentid,mesd)