python:发送消息给微信企业号
1 # -*- coding:utf-8 -*- 2 3 import requests 4 import json 5 6 ''' 7 基础环境:微信企业号 8 version:python 2.7 9 ''' 10 11 class Send_Message(): 12 def __init__(self, text): 13 self.text = text 14 def Token(self): 15 url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken' 16 # corpid,corpsecret 为微信端获取 17 params = {'corpid':'xxxxxxx', 18 'corpsecret': r'xxxxxxxxxxx' 19 } 20 url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken' 21 r = requests.get(url=url, params=params) 22 token=json.loads(r.text)['access_token'] 23 return token 24 25 def send_message(self): 26 data={"touser": "@all", 27 "toparty": " PartyID1 | PartyID2 ", 28 "totag": " TagID1 | TagID2 ", 29 "msgtype": "text", 30 "agentid": '2', 31 "text": { 32 "content": "%s" %(self.text) 33 }, 34 "safe":0 35 } 36 # json.dumps在解析格式时,会使用ascii字符集,所以解析后的数据无法显示中文,ensure_ascii不解析为ascii字符集,使用原有字符集 37 value = json.dumps(data, ensure_ascii=False) 38 token = self.Token() 39 url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=%s' %(token) 40 r = requests.post(url, data=value) 41 return r.text 42 43 if __name__ == '__main__': 44 s = Send_Message("你好,欢迎") 45 s.send_message()
每天学习一点点,重在积累!