用企业微信发送告警

1.遇到的坑

 {"errcode":40001,"errmsg":"invalid credential, hint: [1507881186_cb1093c9bcaedaf108b7ce2ea10f2d38]"}40001 不合法的secret参数 secret在应用详情/通讯录管理助手可查看排查secret的取值也没有错啊。就郁闷了。最后发现问题:是corpid写错了。把企业id写成了应用id。因为“全局错误码”里没有提到corpid错误了会造成40001错误,所以一直以为是scerent的错。参考:https://www.cnblogs.com/luoahong/articles/9018223.html

2.实用Python脚本

[root@cm ~]# cat test_jj.py #!python3# -*- coding: utf-8 -*-import jsonimport requestsclass 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) print(i am here) text = response.text print(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 = "wwdbe2bhaha48965a3012"secret = "-rLV8ahtMIcYlRZMhahaik7y5ikASozwjjppx8ZPaBXyk"agentid = 10200237msg = "supply high quolity and low price product......"wechat = WeChat(corpid, secret, agentid)wechat.access_token()wechat.send_message(msg)

 

用企业微信发送告警

相关文章