#!/usr/bin/env python#-*- coding: utf-8 -*-
#@Time : 2018/4/25 17:06#@Author : zms#@Site :#@File : WeChat.py#@Software: PyCharm Community Edition
#!/usr/bin/env python#coding:utf-8#file wechat.py
importtimeimportrequestsimportjsonimportsysclassWeChat:def __init__(self):
self.CORPID= '企业号'self.CORPSECRET= '应用号见图2箭头2' # 应用加密字符串self.AGENTID= '1000002' # 应用号self.TOUSER= "联系人1|联系人2|联系人3"
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)#print(data)
return data["access_token"]defget_access_token(self):try:
with open('../Common/tmp/access_token.conf', 'r') as f:
t, access_token=f.read().split()#print(access_token)
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]))returnaccess_tokenelse:
cur_time=time.time()if 0 < cur_time - float(t) < 7260:returnaccess_tokenelse:
with open('./access_token.conf', 'w') as f:
access_token=self._get_access_token()
f.write('\t'.join([str(cur_time), access_token]))returnaccess_tokendefsend_data(self,msg):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": msg
},"safe": "0"}
send_data= '{"msgtype": "text", "safe": "0", "agentid": %s, "touser": "%s", "text": {"content": "%s"}}' %(
self.AGENTID, self.TOUSER, msg)
r= requests.post(send_url, json=send_values)#print r.content
returnr.contentif __name__ == '__main__':
wx=WeChat()
wx.send_data('测试中文')