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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM