forked from vincenting/weChat-python-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.py
167 lines (153 loc) · 6.32 KB
/
base.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
# -*- coding: utf-8 -*-
__author__ = 'Vincent Ting'
import cookielib
import urllib2
import urllib
import json
import poster
import hashlib
import time
import re
class BaseClient(object):
def __init__(self, email=None, password=None):
"""
登录公共平台服务器,如果失败将报客户端登录异常错误
:param email:
:param password:
:raise:
"""
if not email or not password:
raise ValueError
self.setOpener()
url_login = "http://mp.weixin.qq.com/cgi-bin/login?lang=en_US"
m = hashlib.md5(password[0:16])
m.digest()
password = m.hexdigest()
body = (('username', email), ('pwd', password), ('imgcode', ''), ('f', 'json'))
try:
msg = json.loads(self.opener.open(url_login, urllib.urlencode(body), timeout=5).read())
except urllib2.URLError:
raise ClientLoginException
if msg['ErrCode'] not in (0, 65202):
raise ClientLoginException
self.token = msg['ErrMsg'].split('=')[-1]
time.sleep(1)
def setOpener(self):
"""
设置请求头部信息模拟浏览器
"""
self.opener = poster.streaminghttp.register_openers()
self.opener.add_handler(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))
self.opener.addheaders = [('Accept', 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),
('Accept-Charset', 'GBK,utf-8;q=0.7,*;q=0.3'),
('Accept-Encoding', 'gzip,deflate,sdch'),
('Cache-Control', 'max-age=0'),
('Connection', 'keep-alive'),
('Host', 'mp.weixin.qq.com'),
('Origin', 'mp.weixin.qq.com'),
('X-Requested-With', 'XMLHttpRequest'),
('User-Agent', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.22 '
'(KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22')]
def _sendMsg(self, sendTo, data):
"""
基础发送信息的方法
:param sendTo:
:param data:
:return:
"""
if type(sendTo) == type([]):
for _sendTo in sendTo:
self._sendMsg(_sendTo, data)
return
self.opener.addheaders += [('Referer', 'http://mp.weixin.qq.com/cgi-bin/singlemsgpage?fromfakeid={0}'
'&msgid=&source=&count=20&t=wxm-singlechat&lang=zh_CN'.format(sendTo))]
body = {
'error': 'false',
'token': self.token,
'tofakeid': sendTo,
'ajax': 1}
body.update(data)
try:
msg = json.loads(self.opener.open("https://mp.weixin.qq.com/cgi-bin/singlesend?t=ajax-response&"
"lang=zh_CN", urllib.urlencode(body), timeout=5).read())['msg']
except urllib2.URLError:
time.sleep(1)
return self._sendMsg(sendTo, data)
print msg
time.sleep(1)
return msg
def _uploadImg(self, img):
"""
根据图片地址来上传图片,返回上传结果id
:param img:
:return:
"""
params = {'uploadfile': open(img, "rb")}
data, headers = poster.encode.multipart_encode(params)
request = urllib2.Request('http://mp.weixin.qq.com/cgi-bin/uploadmaterial?'
'cgi=uploadmaterial&type=2&token={0}&t=iframe-uploadfile&'
'lang=zh_CN&formId=file_from_{1}000'.format(self.token, int(time.time())),
data, headers)
result = urllib2.urlopen(request)
find_id = re.compile("\d+")
time.sleep(1)
return find_id.findall(result.read())[-1]
def _delImg(self, file_id):
"""
根据图片ID来删除图片
:param file_id:
"""
self.opener.open('http://mp.weixin.qq.com/cgi-bin/modifyfile?oper=del&lang=zh_CN&t=ajax-response',
urllib.urlencode({'fileid': file_id,
'token': self.token,
'ajax': 1}))
time.sleep(1)
def _addAppMsg(self, title, content, file_id, digest='', sourceurl=''):
"""
上传图文消息
:param title:
:param content:
:param file_id:
:param digest:
:param sourceurl:
:return:
"""
msg = json.loads(self.opener.open(
'http://mp.weixin.qq.com/cgi-bin/operate_appmsg?token={0}&lang=zh_CN&t=ajax-response&sub=create'.format(
self.token),
urllib.urlencode({'error': 'false',
'count': 1,
'AppMsgId': '',
'title0': title,
'digest0': digest,
'content0': content,
'fileid0': file_id,
'sourceurl0': sourceurl,
'token': self.token,
'ajax': 1})).read())
time.sleep(1)
return msg['msg'] == 'OK'
def _getAppMsgId(self):
"""
获取最新上传id
:return:
"""
msg = json.loads(self.opener.open(
'http://mp.weixin.qq.com/cgi-bin/operate_appmsg?token={0}&lang=zh_CN&sub=list&t=ajax-appmsgs-fileselect&type=10&pageIdx=0&pagesize=10&formid=file_from_{1}000&subtype=3'.format(
self.token, int(time.time())),
urllib.urlencode({'token': self.token,
'ajax': 1})).read())
time.sleep(1)
return msg['List'][0]['appId']
def _delAppMsg(self, app_msg_id):
"""
根据id删除图文
:param app_msg_id:
"""
print self.opener.open('http://mp.weixin.qq.com/cgi-bin/operate_appmsg?sub=del&t=ajax-response',
urllib.urlencode({'AppMsgId': app_msg_id,
'token': self.token,
'ajax': 1})).read()
time.sleep(1)
class ClientLoginException(Exception):
pass