首先:发送企业微信告警需要四个参数:corpid(公司id)secret agentid和token, corpid(公司id)secret agentid三个参数均由管理员提供,员工无法获取,首先问管理员获取这三个数据,token由corpid(公司id和secret获取
其次,告警需要发给谁,可以由管理员在网页版企业微信后台增加对应的人员
代码:
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
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
}
self.msg = (bytes(json.dumps(values), 'utf-8'))
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('send Succesfully')
else:
print('send Failed')
corpid = ""
secret = ""
agentid = ""
wechat = WeChat(corpid, secret, agentid)
wechat.access_token()
msg="hello world"
wechat.send_message(msg)
代码逻辑:获取token->组建消息->发送消息