Merge pull request #155 from Haskely/master

转换为python3代码完成,同时更新了Synchost使其能够成功进入消息循环
This commit is contained in:
Urinx
2017-02-22 12:19:20 +08:00
committed by GitHub
3 changed files with 119 additions and 103 deletions
+1
View File
@@ -94,3 +94,4 @@ ENV/
.idea .idea
*.pyc *.pyc
saved/qrcodes/qrcode.jpg
Binary file not shown.

After

Width:  |  Height:  |  Size: 40 KiB

+117 -102
View File
@@ -1,9 +1,9 @@
#!/usr/bin/env python #!/usr/bin/env python
# coding: utf-8 # coding: utf-8
import qrcode import qrcode
import urllib import urllib.request, urllib.parse, urllib.error
import urllib2 import urllib.request, urllib.error, urllib.parse
import cookielib import http.cookiejar
import requests import requests
import xml.dom.minidom import xml.dom.minidom
import json import json
@@ -16,9 +16,9 @@ import random
import multiprocessing import multiprocessing
import platform import platform
import logging import logging
import httplib import http.client
from collections import defaultdict from collections import defaultdict
from urlparse import urlparse from urllib.parse import urlparse
from lxml import html from lxml import html
#import pdb #import pdb
@@ -32,7 +32,7 @@ def catchKeyboardInterrupt(fn):
try: try:
return fn(*args) return fn(*args)
except KeyboardInterrupt: except KeyboardInterrupt:
print '\n[*] 强制退出程序' print('\n[*] 强制退出程序')
logging.debug('[*] 强制退出程序') logging.debug('[*] 强制退出程序')
return wrapper return wrapper
@@ -40,7 +40,7 @@ def catchKeyboardInterrupt(fn):
def _decode_list(data): def _decode_list(data):
rv = [] rv = []
for item in data: for item in data:
if isinstance(item, unicode): if isinstance(item, str):
item = item.encode('utf-8') item = item.encode('utf-8')
elif isinstance(item, list): elif isinstance(item, list):
item = _decode_list(item) item = _decode_list(item)
@@ -52,10 +52,10 @@ def _decode_list(data):
def _decode_dict(data): def _decode_dict(data):
rv = {} rv = {}
for key, value in data.iteritems(): for key, value in data.items():
if isinstance(key, unicode): if isinstance(key, str):
key = key.encode('utf-8') key = key.encode('utf-8')
if isinstance(value, unicode): if isinstance(value, str):
value = value.encode('utf-8') value = value.encode('utf-8')
elif isinstance(value, list): elif isinstance(value, list):
value = _decode_list(value) value = _decode_list(value)
@@ -118,10 +118,10 @@ class WebWeixin(object):
self.TimeOut = 20 # 同步最短时间间隔(单位:秒) self.TimeOut = 20 # 同步最短时间间隔(单位:秒)
self.media_count = -1 self.media_count = -1
self.cookie = cookielib.CookieJar() self.cookie = http.cookiejar.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(self.cookie)) opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(self.cookie))
opener.addheaders = [('User-agent', self.user_agent)] opener.addheaders = [('User-agent', self.user_agent)]
urllib2.install_opener(opener) urllib.request.install_opener(opener)
def loadConfig(self, config): def loadConfig(self, config):
if config['DEBUG']: if config['DEBUG']:
@@ -143,7 +143,10 @@ class WebWeixin(object):
'lang': self.lang, 'lang': self.lang,
'_': int(time.time()), '_': int(time.time()),
} }
data = self._post(url, params, False) #r = requests.get(url=url, params=params)
#r.encoding = 'utf-8'
#data = r.text
data = self._post(url, params, False).decode("utf-8")
if data == '': if data == '':
return False return False
regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"' regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
@@ -163,7 +166,7 @@ class WebWeixin(object):
else: else:
self._str2qr('https://login.weixin.qq.com/l/' + self.uuid) self._str2qr('https://login.weixin.qq.com/l/' + self.uuid)
def _showQRCodeImg(self, os): def _showQRCodeImg(self, str):
url = 'https://login.weixin.qq.com/qrcode/' + self.uuid url = 'https://login.weixin.qq.com/qrcode/' + self.uuid
params = { params = {
't': 'webwx', 't': 'webwx',
@@ -174,9 +177,9 @@ class WebWeixin(object):
if data == '': if data == '':
return return
QRCODE_PATH = self._saveFile('qrcode.jpg', data, '_showQRCodeImg') QRCODE_PATH = self._saveFile('qrcode.jpg', data, '_showQRCodeImg')
if os == 'win': if str == 'win':
os.startfile(QRCODE_PATH) os.startfile(QRCODE_PATH)
elif os == 'macos': elif str == 'macos':
subprocess.call(["open", QRCODE_PATH]) subprocess.call(["open", QRCODE_PATH])
else: else:
return return
@@ -188,7 +191,7 @@ class WebWeixin(object):
data = self._get(url) data = self._get(url)
if data == '': if data == '':
return False return False
pm = re.search(r'window.code=(\d+);', data) pm = re.search(r"window.code=(\d+);", data)
code = pm.group(1) code = pm.group(1)
if code == '201': if code == '201':
@@ -281,7 +284,7 @@ class WebWeixin(object):
PublicUsersList = self.PublicUsersList[:] PublicUsersList = self.PublicUsersList[:]
SpecialUsersList = self.SpecialUsersList[:] SpecialUsersList = self.SpecialUsersList[:]
for i in xrange(len(ContactList) - 1, -1, -1): for i in range(len(ContactList) - 1, -1, -1):
Contact = ContactList[i] Contact = ContactList[i]
if Contact['VerifyFlag'] & 8 != 0: # 公众号/服务号 if Contact['VerifyFlag'] & 8 != 0: # 公众号/服务号
ContactList.remove(Contact) ContactList.remove(Contact)
@@ -316,7 +319,7 @@ class WebWeixin(object):
ContactCount = dic['Count'] ContactCount = dic['Count']
self.GroupList = ContactList self.GroupList = ContactList
for i in xrange(len(ContactList) - 1, -1, -1): for i in range(len(ContactList) - 1, -1, -1):
Contact = ContactList[i] Contact = ContactList[i]
MemberList = Contact['MemberList'] MemberList = Contact['MemberList']
for member in MemberList: for member in MemberList:
@@ -340,16 +343,22 @@ class WebWeixin(object):
return dic['ContactList'] return dic['ContactList']
def testsynccheck(self): def testsynccheck(self):
SyncHost = [ SyncHost = ['wx2.qq.com',
'webpush.weixin.qq.com', 'webpush.wx2.qq.com',
#'webpush2.weixin.qq.com', 'wx8.qq.com',
'webpush.wechat.com', 'webpush.wx8.qq.com',
'webpush1.wechat.com', 'qq.com',
'webpush2.wechat.com', 'webpush.wx.qq.com',
'webpush.wx.qq.com', 'web2.wechat.com',
'webpush2.wx.qq.com' 'webpush.web2.wechat.com',
# 'webpush.wechatapp.com' 'wechat.com',
] 'webpush.web.wechat.com',
'webpush.weixin.qq.com',
'webpush.wechat.com',
'webpush1.wechat.com',
'webpush2.wechat.com',
'webpush.wx.qq.com',
'webpush2.wx.qq.com']
for host in SyncHost: for host in SyncHost:
self.syncHost = host self.syncHost = host
[retcode, selector] = self.synccheck() [retcode, selector] = self.synccheck()
@@ -367,11 +376,11 @@ class WebWeixin(object):
'synckey': self.synckey, 'synckey': self.synckey,
'_': int(time.time()), '_': int(time.time()),
} }
url = 'https://' + self.syncHost + \ url = 'https://' + self.syncHost + '/cgi-bin/mmwebwx-bin/synccheck?' + urllib.parse.urlencode(params)
'/cgi-bin/mmwebwx-bin/synccheck?' + urllib.urlencode(params)
data = self._get(url) data = self._get(url)
if data == '': if data == '':
return [-1,-1] return [-1,-1]
pm = re.search( pm = re.search(
r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}', data) r'window.synccheck={retcode:"(\d+)",selector:"(\d+)"}', data)
retcode = pm.group(1) retcode = pm.group(1)
@@ -391,7 +400,7 @@ class WebWeixin(object):
if dic == '': if dic == '':
return None return None
if self.DEBUG: if self.DEBUG:
print json.dumps(dic, indent=4) print(json.dumps(dic, indent=4))
(json.dumps(dic, indent=4)) (json.dumps(dic, indent=4))
if dic['BaseResponse']['Ret'] == 0: if dic['BaseResponse']['Ret'] == 0:
@@ -539,7 +548,7 @@ class WebWeixin(object):
r = requests.post(url, data=data, headers=headers) r = requests.post(url, data=data, headers=headers)
dic = r.json() dic = r.json()
if self.DEBUG: if self.DEBUG:
print json.dumps(dic, indent=4) print(json.dumps(dic, indent=4))
logging.debug(json.dumps(dic, indent=4)) logging.debug(json.dumps(dic, indent=4))
return dic['BaseResponse']['Ret'] == 0 return dic['BaseResponse']['Ret'] == 0
@@ -722,28 +731,28 @@ class WebWeixin(object):
msg['message'] = content msg['message'] = content
# 指定了消息内容 # 指定了消息内容
if 'message' in msg.keys(): if 'message' in list(msg.keys()):
content = msg['message'] content = msg['message']
if groupName != None: if groupName != None:
print '%s |%s| %s -> %s: %s' % (message_id, groupName.strip(), srcName.strip(), dstName.strip(), content.replace('<br/>', '\n')) print('%s |%s| %s -> %s: %s' % (message_id, groupName.strip(), srcName.strip(), dstName.strip(), content.replace('<br/>', '\n')))
logging.info('%s |%s| %s -> %s: %s' % (message_id, groupName.strip(), logging.info('%s |%s| %s -> %s: %s' % (message_id, groupName.strip(),
srcName.strip(), dstName.strip(), content.replace('<br/>', '\n'))) srcName.strip(), dstName.strip(), content.replace('<br/>', '\n')))
else: else:
print '%s %s -> %s: %s' % (message_id, srcName.strip(), dstName.strip(), content.replace('<br/>', '\n')) print('%s %s -> %s: %s' % (message_id, srcName.strip(), dstName.strip(), content.replace('<br/>', '\n')))
logging.info('%s %s -> %s: %s' % (message_id, srcName.strip(), logging.info('%s %s -> %s: %s' % (message_id, srcName.strip(),
dstName.strip(), content.replace('<br/>', '\n'))) dstName.strip(), content.replace('<br/>', '\n')))
def handleMsg(self, r): def handleMsg(self, r):
for msg in r['AddMsgList']: for msg in r['AddMsgList']:
print '[*] 你有新的消息,请注意查收' print('[*] 你有新的消息,请注意查收')
logging.debug('[*] 你有新的消息,请注意查收') logging.debug('[*] 你有新的消息,请注意查收')
if self.DEBUG: if self.DEBUG:
fn = 'msg' + str(int(random.random() * 1000)) + '.json' fn = 'msg' + str(int(random.random() * 1000)) + '.json'
with open(fn, 'w') as f: with open(fn, 'w') as f:
f.write(json.dumps(msg)) f.write(json.dumps(msg))
print '[*] 该消息已储存到文件: ' + fn print('[*] 该消息已储存到文件: ' + fn)
logging.debug('[*] 该消息已储存到文件: %s' % (fn)) logging.debug('[*] 该消息已储存到文件: %s' % (fn))
msgType = msg['MsgType'] msgType = msg['MsgType']
@@ -754,13 +763,17 @@ class WebWeixin(object):
if msgType == 1: if msgType == 1:
raw_msg = {'raw_msg': msg} raw_msg = {'raw_msg': msg}
self._showMsg(raw_msg) self._showMsg(raw_msg)
#自己加的代码-------------------------------------------#
#if self.autoReplyRevokeMode:
# store
#自己加的代码-------------------------------------------#
if self.autoReplyMode: if self.autoReplyMode:
ans = self._xiaodoubi(content) + '\n[微信机器人自动回复]' ans = self._xiaodoubi(content) + '\n[微信机器人自动回复]'
if self.webwxsendmsg(ans, msg['FromUserName']): if self.webwxsendmsg(ans, msg['FromUserName']):
print '自动回复: ' + ans print('自动回复: ' + ans)
logging.info('自动回复: ' + ans) logging.info('自动回复: ' + ans)
else: else:
print '自动回复失败' print('自动回复失败')
logging.info('自动回复失败') logging.info('自动回复失败')
elif msgType == 3: elif msgType == 3:
image = self.webwxgetmsgimg(msgid) image = self.webwxgetmsgimg(msgid)
@@ -776,13 +789,13 @@ class WebWeixin(object):
self._safe_open(voice) self._safe_open(voice)
elif msgType == 42: elif msgType == 42:
info = msg['RecommendInfo'] info = msg['RecommendInfo']
print '%s 发送了一张名片:' % name print('%s 发送了一张名片:' % name)
print '=========================' print('=========================')
print '= 昵称: %s' % info['NickName'] print('= 昵称: %s' % info['NickName'])
print '= 微信号: %s' % info['Alias'] print('= 微信号: %s' % info['Alias'])
print '= 地区: %s %s' % (info['Province'], info['City']) print('= 地区: %s %s' % (info['Province'], info['City']))
print '= 性别: %s' % ['未知', '', ''][info['Sex']] print('= 性别: %s' % ['未知', '', ''][info['Sex']])
print '=========================' print('=========================')
raw_msg = {'raw_msg': msg, 'message': '%s 发送了一张名片: %s' % ( raw_msg = {'raw_msg': msg, 'message': '%s 发送了一张名片: %s' % (
name.strip(), json.dumps(info))} name.strip(), json.dumps(info))}
self._showMsg(raw_msg) self._showMsg(raw_msg)
@@ -795,13 +808,13 @@ class WebWeixin(object):
elif msgType == 49: elif msgType == 49:
appMsgType = defaultdict(lambda: "") appMsgType = defaultdict(lambda: "")
appMsgType.update({5: '链接', 3: '音乐', 7: '微博'}) appMsgType.update({5: '链接', 3: '音乐', 7: '微博'})
print '%s 分享了一个%s:' % (name, appMsgType[msg['AppMsgType']]) print('%s 分享了一个%s:' % (name, appMsgType[msg['AppMsgType']]))
print '=========================' print('=========================')
print '= 标题: %s' % msg['FileName'] print('= 标题: %s' % msg['FileName'])
print '= 描述: %s' % self._searchContent('des', content, 'xml') print('= 描述: %s' % self._searchContent('des', content, 'xml'))
print '= 链接: %s' % msg['Url'] print('= 链接: %s' % msg['Url'])
print '= 来自: %s' % self._searchContent('appname', content, 'xml') print('= 来自: %s' % self._searchContent('appname', content, 'xml'))
print '=========================' print('=========================')
card = { card = {
'title': msg['FileName'], 'title': msg['FileName'],
'description': self._searchContent('des', content, 'xml'), 'description': self._searchContent('des', content, 'xml'),
@@ -831,7 +844,7 @@ class WebWeixin(object):
self._showMsg(raw_msg) self._showMsg(raw_msg)
def listenMsgMode(self): def listenMsgMode(self):
print '[*] 进入消息监听模式 ... 成功' print('[*] 进入消息监听模式 ... 成功')
logging.debug('[*] 进入消息监听模式 ... 成功') logging.debug('[*] 进入消息监听模式 ... 成功')
self._run('[*] 进行同步线路测试 ... ', self.testsynccheck) self._run('[*] 进行同步线路测试 ... ', self.testsynccheck)
playWeChat = 0 playWeChat = 0
@@ -840,14 +853,14 @@ class WebWeixin(object):
self.lastCheckTs = time.time() self.lastCheckTs = time.time()
[retcode, selector] = self.synccheck() [retcode, selector] = self.synccheck()
if self.DEBUG: if self.DEBUG:
print 'retcode: %s, selector: %s' % (retcode, selector) print('retcode: %s, selector: %s' % (retcode, selector))
logging.debug('retcode: %s, selector: %s' % (retcode, selector)) logging.debug('retcode: %s, selector: %s' % (retcode, selector))
if retcode == '1100': if retcode == '1100':
print '[*] 你在手机上登出了微信,债见' print('[*] 你在手机上登出了微信,债见')
logging.debug('[*] 你在手机上登出了微信,债见') logging.debug('[*] 你在手机上登出了微信,债见')
break break
if retcode == '1101': if retcode == '1101':
print '[*] 你在其他地方登录了 WEB 版微信,债见' print('[*] 你在其他地方登录了 WEB 版微信,债见')
logging.debug('[*] 你在其他地方登录了 WEB 版微信,债见') logging.debug('[*] 你在其他地方登录了 WEB 版微信,债见')
break break
elif retcode == '0': elif retcode == '0':
@@ -858,11 +871,11 @@ class WebWeixin(object):
elif selector == '6': elif selector == '6':
# TODO # TODO
redEnvelope += 1 redEnvelope += 1
print '[*] 收到疑似红包消息 %d' % redEnvelope print('[*] 收到疑似红包消息 %d' % redEnvelope)
logging.debug('[*] 收到疑似红包消息 %d' % redEnvelope) logging.debug('[*] 收到疑似红包消息 %d' % redEnvelope)
elif selector == '7': elif selector == '7':
playWeChat += 1 playWeChat += 1
print '[*] 你在手机上玩微信被我发现了 %d' % playWeChat print('[*] 你在手机上玩微信被我发现了 %d' % playWeChat)
logging.debug('[*] 你在手机上玩微信被我发现了 %d' % playWeChat) logging.debug('[*] 你在手机上玩微信被我发现了 %d' % playWeChat)
r = self.webwxsync() r = self.webwxsync()
elif selector == '0': elif selector == '0':
@@ -879,19 +892,19 @@ class WebWeixin(object):
line = line.replace('\n', '') line = line.replace('\n', '')
self._echo('-> ' + name + ': ' + line) self._echo('-> ' + name + ': ' + line)
if self.webwxsendmsg(line, id): if self.webwxsendmsg(line, id):
print ' [成功]' print(' [成功]')
else: else:
print ' [失败]' print(' [失败]')
time.sleep(1) time.sleep(1)
else: else:
if self.webwxsendmsg(word, id): if self.webwxsendmsg(word, id):
print '[*] 消息发送成功' print('[*] 消息发送成功')
logging.debug('[*] 消息发送成功') logging.debug('[*] 消息发送成功')
else: else:
print '[*] 消息发送失败' print('[*] 消息发送失败')
logging.debug('[*] 消息发送失败') logging.debug('[*] 消息发送失败')
else: else:
print '[*] 此用户不存在' print('[*] 此用户不存在')
logging.debug('[*] 此用户不存在') logging.debug('[*] 此用户不存在')
def sendMsgToAll(self, word): def sendMsgToAll(self, word):
@@ -901,9 +914,9 @@ class WebWeixin(object):
id = contact['UserName'] id = contact['UserName']
self._echo('-> ' + name + ': ' + word) self._echo('-> ' + name + ': ' + word)
if self.webwxsendmsg(word, id): if self.webwxsendmsg(word, id):
print ' [成功]' print(' [成功]')
else: else:
print ' [失败]' print(' [失败]')
time.sleep(1) time.sleep(1)
def sendImg(self, name, file_name): def sendImg(self, name, file_name):
@@ -925,18 +938,18 @@ class WebWeixin(object):
@catchKeyboardInterrupt @catchKeyboardInterrupt
def start(self): def start(self):
self._echo('[*] 微信网页版 ... 开动') self._echo('[*] 微信网页版 ... 开动')
print print()
logging.debug('[*] 微信网页版 ... 开动') logging.debug('[*] 微信网页版 ... 开动')
while True: while True:
self._run('[*] 正在获取 uuid ... ', self.getUUID) self._run('[*] 正在获取 uuid ... ', self.getUUID)
self._echo('[*] 正在获取二维码 ... 成功') self._echo('[*] 正在获取二维码 ... 成功')
print print()
logging.debug('[*] 微信网页版 ... 开动') logging.debug('[*] 微信网页版 ... 开动')
self.genQRCode() self.genQRCode()
print '[*] 请使用微信扫描二维码以登录 ... ' print('[*] 请使用微信扫描二维码以登录 ... ')
if not self.waitForLogin(): if not self.waitForLogin():
continue continue
print '[*] 请在手机上点击确认以登录 ... ' print('[*] 请在手机上点击确认以登录 ... ')
if not self.waitForLogin(0): if not self.waitForLogin(0):
continue continue
break break
@@ -947,33 +960,33 @@ class WebWeixin(object):
self._run('[*] 获取联系人 ... ', self.webwxgetcontact) self._run('[*] 获取联系人 ... ', self.webwxgetcontact)
self._echo('[*] 应有 %s 个联系人,读取到联系人 %d' % self._echo('[*] 应有 %s 个联系人,读取到联系人 %d' %
(self.MemberCount, len(self.MemberList))) (self.MemberCount, len(self.MemberList)))
print print()
self._echo('[*] 共有 %d 个群 | %d 个直接联系人 | %d 个特殊账号 %d 公众号或服务号' % (len(self.GroupList), self._echo('[*] 共有 %d 个群 | %d 个直接联系人 | %d 个特殊账号 %d 公众号或服务号' % (len(self.GroupList),
len(self.ContactList), len(self.SpecialUsersList), len(self.PublicUsersList))) len(self.ContactList), len(self.SpecialUsersList), len(self.PublicUsersList)))
print print()
self._run('[*] 获取群 ... ', self.webwxbatchgetcontact) self._run('[*] 获取群 ... ', self.webwxbatchgetcontact)
logging.debug('[*] 微信网页版 ... 开动') logging.debug('[*] 微信网页版 ... 开动')
if self.DEBUG: if self.DEBUG:
print self print(self)
logging.debug(self) logging.debug(self)
if self.interactive and raw_input('[*] 是否开启自动回复模式(y/n): ') == 'y': if self.interactive and input('[*] 是否开启自动回复模式(y/n): ') == 'y':
self.autoReplyMode = True self.autoReplyMode = True
print '[*] 自动回复模式 ... 开启' print('[*] 自动回复模式 ... 开启')
logging.debug('[*] 自动回复模式 ... 开启') logging.debug('[*] 自动回复模式 ... 开启')
else: else:
print '[*] 自动回复模式 ... 关闭' print('[*] 自动回复模式 ... 关闭')
logging.debug('[*] 自动回复模式 ... 关闭') logging.debug('[*] 自动回复模式 ... 关闭')
if sys.platform.startswith('win'): if sys.platform.startswith('win'):
import thread import _thread
thread.start_new_thread(self.listenMsgMode()) _thread.start_new_thread(self.listenMsgMode())
else: else:
listenProcess = multiprocessing.Process(target=self.listenMsgMode) listenProcess = multiprocessing.Process(target=self.listenMsgMode)
listenProcess.start() listenProcess.start()
while True: while True:
text = raw_input('') text = input('')
if text == 'quit': if text == 'quit':
listenProcess.terminate() listenProcess.terminate()
print('[*] 退出微信') print('[*] 退出微信')
@@ -989,15 +1002,15 @@ class WebWeixin(object):
[name, file] = text[3:].split(':') [name, file] = text[3:].split(':')
self.sendMsg(name, file, True) self.sendMsg(name, file, True)
elif text[:3] == 'f->': elif text[:3] == 'f->':
print '发送文件' print('发送文件')
logging.debug('发送文件') logging.debug('发送文件')
elif text[:3] == 'i->': elif text[:3] == 'i->':
print '发送图片' print('发送图片')
[name, file_name] = text[3:].split(':') [name, file_name] = text[3:].split(':')
self.sendImg(name, file_name) self.sendImg(name, file_name)
logging.debug('发送图片') logging.debug('发送图片')
elif text[:3] == 'e->': elif text[:3] == 'e->':
print '发送表情' print('发送表情')
[name, file_name] = text[3:].split(':') [name, file_name] = text[3:].split(':')
self.sendEmotion(name, file_name) self.sendEmotion(name, file_name)
logging.debug('发送表情') logging.debug('发送表情')
@@ -1012,7 +1025,7 @@ class WebWeixin(object):
def _run(self, str, func, *args): def _run(self, str, func, *args):
self._echo(str) self._echo(str)
if func(*args): if func(*args):
print '成功' print('成功')
logging.debug('%s... 成功' % (str)) logging.debug('%s... 成功' % (str))
else: else:
print('失败\n[*] 退出程序') print('失败\n[*] 退出程序')
@@ -1028,7 +1041,7 @@ class WebWeixin(object):
for i in mat: for i in mat:
BLACK = '\033[40m \033[0m' BLACK = '\033[40m \033[0m'
WHITE = '\033[47m \033[0m' WHITE = '\033[47m \033[0m'
print ''.join([BLACK if j else WHITE for j in i]) print(''.join([BLACK if j else WHITE for j in i]))
def _str2qr(self, str): def _str2qr(self, str):
print(str) print(str)
@@ -1046,55 +1059,57 @@ class WebWeixin(object):
if not data: if not data:
return data return data
result = None result = None
if type(data) == unicode: if type(data) == str:
result = data result = data
elif type(data) == str: elif type(data) == str:
result = data.decode('utf-8') result = data.decode('utf-8')
return result return result
def _get(self, url, api=None): def _get(self, url: object, api: object = None) -> object:
request = urllib2.Request(url=url) request = urllib.request.Request(url=url)
request.add_header('Referer', 'https://wx.qq.com/') request.add_header('Referer', 'https://wx.qq.com/')
if api == 'webwxgetvoice': if api == 'webwxgetvoice':
request.add_header('Range', 'bytes=0-') request.add_header('Range', 'bytes=0-')
if api == 'webwxgetvideo': if api == 'webwxgetvideo':
request.add_header('Range', 'bytes=0-') request.add_header('Range', 'bytes=0-')
try: try:
response = urllib2.urlopen(request) response = urllib.request.urlopen(request)
data = response.read() data = response.read().decode('utf-8')
logging.debug(url) logging.debug(url)
return data return data
except urllib2.HTTPError, e: except urllib.error.HTTPError as e:
logging.error('HTTPError = ' + str(e.code)) logging.error('HTTPError = ' + str(e.code))
except urllib2.URLError, e: except urllib.error.URLError as e:
logging.error('URLError = ' + str(e.reason)) logging.error('URLError = ' + str(e.reason))
except httplib.HTTPException, e: except http.client.HTTPException as e:
logging.error('HTTPException') logging.error('HTTPException')
except Exception: except Exception:
import traceback import traceback
logging.error('generic exception: ' + traceback.format_exc()) logging.error('generic exception: ' + traceback.format_exc())
return '' return ''
def _post(self, url, params, jsonfmt=True): def _post(self, url: object, params: object, jsonfmt: object = True) -> object:
if jsonfmt: if jsonfmt:
request = urllib2.Request(url=url, data=json.dumps(params)) data = (json.dumps(params)).encode()
request = urllib.request.Request(url=url, data=data)
request.add_header( request.add_header(
'ContentType', 'application/json; charset=UTF-8') 'ContentType', 'application/json; charset=UTF-8')
else: else:
request = urllib2.Request(url=url, data=urllib.urlencode(params)) request = urllib.request.Request(url=url, data=urllib.parse.urlencode(params).encode(encoding='utf-8'))
try: try:
response = urllib2.urlopen(request) response = urllib.request.urlopen(request)
data = response.read() data = response.read()
if jsonfmt: if jsonfmt:
return json.loads(data, object_hook=_decode_dict) return json.loads(data.decode('utf-8') )#object_hook=_decode_dict)
return data return data
except urllib2.HTTPError, e: except urllib.error.HTTPError as e:
logging.error('HTTPError = ' + str(e.code)) logging.error('HTTPError = ' + str(e.code))
except urllib2.URLError, e: except urllib.error.URLError as e:
logging.error('URLError = ' + str(e.reason)) logging.error('URLError = ' + str(e.reason))
except httplib.HTTPException, e: except http.client.HTTPException as e:
logging.error('HTTPException') logging.error('HTTPException')
except Exception: except Exception:
import traceback import traceback