准备工做:html
到企业微信官网,注册一个企业;登陆企业微信后台,建立一个“自建”应用, 获取企业ID、agentid、secret这3个必要的参数;在企业微信的通信录中,建立多个测试帐号;在手机端安装“企业微信”APP,使用测试帐号登陆到企业微信,准备接收消息。python
程序代码:json
企业微信提供API开发接口,经过HTTPS的GET、POST方法与企业微信后台进行交互,完成获取令牌、发送数据、获取数据的操做。c#
Python代码主要使用requests库,将企业微信API进行简单封装,模拟https的GET、POST操做,向指定的用户发送企业微信消息。api
#!/usr/bin/env python # -*- coding: utf-8 -*- import time import requests import json class WeChat: def __init__(self): self.CORPID = 'ww2e1234567895498f5498f' #企业ID,在管理后台获取 self.CORPSECRET = 'xy11234567898hk_ecJ123456789DhKy4_1y12345OI'#自建应用的Secret,每一个自建应用里都有单独的secret self.AGENTID = '1000002' #应用ID,在后台应用中获取 self.TOUSER = "maomao|dingding" # 接收者用户名,多个用户用|分割 def _get_access_token(self): url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken' values = {'corpid': self.CORPID, 'corpsecret': self.CORPSECRET, } req = requests.post(url, params=values) data = json.loads(req.text) return data["access_token"] def get_access_token(self): try: with open('./tmp/access_token.conf', 'r') as f: t, access_token = f.read().split() except: with open('./tmp/access_token.conf', 'w') as f: access_token = self._get_access_token() cur_time = time.time() f.write('\t'.join([str(cur_time), access_token])) return access_token else: cur_time = time.time() if 0 < cur_time - float(t) < 7260: return access_token else: with open('./tmp/access_token.conf', 'w') as f: access_token = self._get_access_token() f.write('\t'.join([str(cur_time), access_token])) return access_token def send_data(self, message): send_url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' + self.get_access_token() send_values = { "touser": self.TOUSER, "msgtype": "text", "agentid": self.AGENTID, "text": { "content": message }, "safe": "0" } send_msges=(bytes(json.dumps(send_values), 'utf-8')) respone = requests.post(send_url, send_msges) respone = respone.json() #当返回的数据是json串的时候直接用.json便可将respone转换成字典 return respone["errmsg"] if __name__ == '__main__': wx = WeChat() wx.send_data("这是程序发送的第1条消息!\n Python程序调用企业微信API,从自建应用“告警测试应用”发送给管理员的消息!") wx.send_data("这是程序发送的第2条消息!")
运行截图:微信
参考连接:post
python实现经过企业微信发送消息测试
http://www.javashuo.com/article/p-qewqrvyn-cp.htmlurl
python脚本--用企业微信实现发送信息spa
http://www.javashuo.com/article/p-unaouiyh-kx.html
企业微信后台管理:
企业微信API文档: