wxbot.py 38 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. import os
  4. import sys
  5. import traceback
  6. import webbrowser
  7. import pyqrcode
  8. import requests
  9. import json
  10. import xml.dom.minidom
  11. import urllib
  12. import time
  13. import re
  14. import random
  15. from requests.exceptions import ConnectionError, ReadTimeout
  16. import HTMLParser
  17. UNKONWN = 'unkonwn'
  18. SUCCESS = '200'
  19. SCANED = '201'
  20. TIMEOUT = '408'
  21. def show_image(file_path):
  22. """
  23. 跨平台显示图片文件
  24. :param file_path: 图片文件路径
  25. """
  26. if sys.version_info >= (3, 3):
  27. from shlex import quote
  28. else:
  29. from pipes import quote
  30. if sys.platform == "darwin":
  31. command = "open -a /Applications/Preview.app %s&" % quote(file_path)
  32. os.system(command)
  33. else:
  34. webbrowser.open(file_path)
  35. class SafeSession(requests.Session):
  36. def request(self, method, url, params=None, data=None, headers=None, cookies=None, files=None, auth=None,
  37. timeout=None, allow_redirects=True, proxies=None, hooks=None, stream=None, verify=None, cert=None,
  38. json=None):
  39. for i in range(3):
  40. try:
  41. return super(SafeSession, self).request(method, url, params, data, headers, cookies, files, auth,
  42. timeout,
  43. allow_redirects, proxies, hooks, stream, verify, cert, json)
  44. except Exception as e:
  45. print e.message,traceback.format_exc()
  46. continue
  47. class WXBot:
  48. """WXBot功能类"""
  49. def __init__(self):
  50. self.DEBUG = False
  51. self.uuid = ''
  52. self.base_uri = ''
  53. self.redirect_uri = ''
  54. self.uin = ''
  55. self.sid = ''
  56. self.skey = ''
  57. self.pass_ticket = ''
  58. self.device_id = 'e' + repr(random.random())[2:17]
  59. self.base_request = {}
  60. self.sync_key_str = ''
  61. self.sync_key = []
  62. self.sync_host = ''
  63. self.session = SafeSession()
  64. self.session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5'})
  65. self.conf = {'qr': 'png'}
  66. self.my_account = {} # 当前账户
  67. # 所有相关账号: 联系人, 公众号, 群组, 特殊账号
  68. self.member_list = []
  69. # 所有群组的成员, {'group_id1': [member1, member2, ...], ...}
  70. self.group_members = {}
  71. # 所有账户, {'group_member':{'id':{'type':'group_member', 'info':{}}, ...}, 'normal_member':{'id':{}, ...}}
  72. self.account_info = {'group_member': {}, 'normal_member': {}}
  73. self.contact_list = [] # 联系人列表
  74. self.public_list = [] # 公众账号列表
  75. self.group_list = [] # 群聊列表
  76. self.special_list = [] # 特殊账号列表
  77. self.encry_chat_room_id_list = [] # 存储群聊的EncryChatRoomId,获取群内成员头像时需要用到
  78. @staticmethod
  79. def to_unicode(string, encoding='utf-8'):
  80. """
  81. 将字符串转换为Unicode
  82. :param string: 待转换字符串
  83. :param encoding: 字符串解码方式
  84. :return: 转换后的Unicode字符串
  85. """
  86. if isinstance(string, str):
  87. return string.decode(encoding)
  88. elif isinstance(string, unicode):
  89. return string
  90. else:
  91. raise Exception('Unknown Type')
  92. def get_contact(self):
  93. """获取当前账户的所有相关账号(包括联系人、公众号、群聊、特殊账号)"""
  94. url = self.base_uri + '/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s' \
  95. % (self.pass_ticket, self.skey, int(time.time()))
  96. r = self.session.post(url, data='{}')
  97. r.encoding = 'utf-8'
  98. if self.DEBUG:
  99. with open('contacts.json', 'w') as f:
  100. f.write(r.text.encode('utf-8'))
  101. dic = json.loads(r.text)
  102. self.member_list = dic['MemberList']
  103. special_users = ['newsapp', 'fmessage', 'filehelper', 'weibo', 'qqmail',
  104. 'fmessage', 'tmessage', 'qmessage', 'qqsync', 'floatbottle',
  105. 'lbsapp', 'shakeapp', 'medianote', 'qqfriend', 'readerapp',
  106. 'blogapp', 'facebookapp', 'masssendapp', 'meishiapp',
  107. 'feedsapp', 'voip', 'blogappweixin', 'weixin', 'brandsessionholder',
  108. 'weixinreminder', 'wxid_novlwrv3lqwv11', 'gh_22b87fa7cb3c',
  109. 'officialaccounts', 'notification_messages', 'wxid_novlwrv3lqwv11',
  110. 'gh_22b87fa7cb3c', 'wxitil', 'userexperience_alarm', 'notification_messages']
  111. self.contact_list = []
  112. self.public_list = []
  113. self.special_list = []
  114. self.group_list = []
  115. for contact in self.member_list:
  116. if contact['VerifyFlag'] & 8 != 0: # 公众号
  117. self.public_list.append(contact)
  118. self.account_info['normal_member'][contact['UserName']] = {'type': 'public', 'info': contact}
  119. elif contact['UserName'] in special_users: # 特殊账户
  120. self.special_list.append(contact)
  121. self.account_info['normal_member'][contact['UserName']] = {'type': 'special', 'info': contact}
  122. elif contact['UserName'].find('@@') != -1: # 群聊
  123. self.group_list.append(contact)
  124. self.account_info['normal_member'][contact['UserName']] = {'type': 'group', 'info': contact}
  125. elif contact['UserName'] == self.my_account['UserName']: # 自己
  126. self.account_info['normal_member'][contact['UserName']] = {'type': 'self', 'info': contact}
  127. pass
  128. else:
  129. self.contact_list.append(contact)
  130. self.account_info['normal_member'][contact['UserName']] = {'type': 'contact', 'info': contact}
  131. self.batch_get_group_members()
  132. for group in self.group_members:
  133. for member in self.group_members[group]:
  134. if member['UserName'] not in self.account_info:
  135. self.account_info['group_member'][member['UserName']] = \
  136. {'type': 'group_member', 'info': member, 'group': group}
  137. if self.DEBUG:
  138. with open('contact_list.json', 'w') as f:
  139. f.write(json.dumps(self.contact_list))
  140. with open('special_list.json', 'w') as f:
  141. f.write(json.dumps(self.special_list))
  142. with open('group_list.json', 'w') as f:
  143. f.write(json.dumps(self.group_list))
  144. with open('public_list.json', 'w') as f:
  145. f.write(json.dumps(self.public_list))
  146. with open('member_list.json', 'w') as f:
  147. f.write(json.dumps(self.member_list))
  148. with open('group_users.json', 'w') as f:
  149. f.write(json.dumps(self.group_members))
  150. with open('account_info.json', 'w') as f:
  151. f.write(json.dumps(self.account_info))
  152. return True
  153. def batch_get_group_members(self):
  154. """批量获取所有群聊成员信息"""
  155. url = self.base_uri + '/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  156. params = {
  157. 'BaseRequest': self.base_request,
  158. "Count": len(self.group_list),
  159. "List": [{"UserName": group['UserName'], "EncryChatRoomId": ""} for group in self.group_list]
  160. }
  161. r = self.session.post(url, data=json.dumps(params))
  162. r.encoding = 'utf-8'
  163. dic = json.loads(r.text)
  164. group_members = {}
  165. encry_chat_room_id = {}
  166. for group in dic['ContactList']:
  167. gid = group['UserName']
  168. members = group['MemberList']
  169. group_members[gid] = members
  170. encry_chat_room_id[gid] = group['EncryChatRoomId']
  171. self.group_members = group_members
  172. self.encry_chat_room_id_list = encry_chat_room_id
  173. def get_group_member_name(self, gid, uid):
  174. """
  175. 获取群聊中指定成员的名称信息
  176. :param gid: 群id
  177. :param uid: 群聊成员id
  178. :return: 名称信息,类似 {"display_name": "test_user", "nickname": "test", "remark_name": "for_test" }
  179. """
  180. if gid not in self.group_members:
  181. return None
  182. group = self.group_members[gid]
  183. for member in group:
  184. if member['UserName'] == uid:
  185. names = {}
  186. if 'RemarkName' in member and member['RemarkName']:
  187. names['remark_name'] = member['RemarkName']
  188. if 'NickName' in member and member['NickName']:
  189. names['nickname'] = member['NickName']
  190. if 'DisplayName' in member and member['DisplayName']:
  191. names['display_name'] = member['DisplayName']
  192. return names
  193. return None
  194. def get_contact_info(self, uid):
  195. if uid in self.account_info['normal_member']:
  196. return self.account_info['normal_member'][uid]
  197. else:
  198. return None
  199. def get_group_member_info(self, uid):
  200. if uid in self.account_info['group_member']:
  201. return self.account_info['group_member'][uid]
  202. else:
  203. return None
  204. def get_contact_name(self, uid):
  205. info = self.get_contact_info(uid)
  206. if info is None:
  207. return None
  208. info = info['info']
  209. name = {}
  210. if 'RemarkName' in info and info['RemarkName']:
  211. name['remark_name'] = info['RemarkName']
  212. if 'NickName' in info and info['NickName']:
  213. name['nickname'] = info['NickName']
  214. if 'DisplayName' in info and info['DisplayName']:
  215. name['display_name'] = info['DisplayName']
  216. if len(name) == 0:
  217. return None
  218. else:
  219. return name
  220. def get_group_member_name(self, uid):
  221. info = self.get_group_member_info(uid)
  222. if info is None:
  223. return None
  224. info = info['info']
  225. name = {}
  226. if 'RemarkName' in info and info['RemarkName']:
  227. name['remark_name'] = info['RemarkName']
  228. if 'NickName' in info and info['NickName']:
  229. name['nickname'] = info['NickName']
  230. if 'DisplayName' in info and info['DisplayName']:
  231. name['display_name'] = info['DisplayName']
  232. if len(name) == 0:
  233. return None
  234. else:
  235. return name
  236. @staticmethod
  237. def get_contact_prefer_name(name):
  238. if name is None:
  239. return None
  240. if 'remark_name' in name:
  241. return name['remark_name']
  242. if 'nickname' in name:
  243. return name['nickname']
  244. if 'display_name' in name:
  245. return name['display_name']
  246. return None
  247. @staticmethod
  248. def get_group_member_prefer_name(name):
  249. if name is None:
  250. return None
  251. if 'remark_name' in name:
  252. return name['remark_name']
  253. if 'display_name' in name:
  254. return name['display_name']
  255. if 'nickname' in name:
  256. return name['nickname']
  257. return None
  258. def get_user_type(self, wx_user_id):
  259. """
  260. 获取特定账号与自己的关系
  261. :param wx_user_id: 账号id:
  262. :return: 与当前账号的关系
  263. """
  264. for account in self.contact_list:
  265. if wx_user_id == account['UserName']:
  266. return 'contact'
  267. for account in self.public_list:
  268. if wx_user_id == account['UserName']:
  269. return 'public'
  270. for account in self.special_list:
  271. if wx_user_id == account['UserName']:
  272. return 'special'
  273. for account in self.group_list:
  274. if wx_user_id == account['UserName']:
  275. return 'group'
  276. for group in self.group_members:
  277. for member in self.group_members[group]:
  278. if member['UserName'] == wx_user_id:
  279. return 'group_member'
  280. return 'unknown'
  281. def is_contact(self, uid):
  282. for account in self.contact_list:
  283. if uid == account['UserName']:
  284. return True
  285. return False
  286. def is_public(self, uid):
  287. for account in self.public_list:
  288. if uid == account['UserName']:
  289. return True
  290. return False
  291. def is_special(self, uid):
  292. for account in self.special_list:
  293. if uid == account['UserName']:
  294. return True
  295. return False
  296. def handle_msg_all(self, msg):
  297. """
  298. 处理所有消息,请子类化后覆盖此函数
  299. msg:
  300. msg_id -> 消息id
  301. msg_type_id -> 消息类型id
  302. user -> 发送消息的账号id
  303. content -> 消息内容
  304. :param msg: 收到的消息
  305. """
  306. pass
  307. @staticmethod
  308. def proc_at_info(msg):
  309. if not msg:
  310. return '', []
  311. segs = msg.split(u'\u2005')
  312. str_msg_all = ''
  313. str_msg = ''
  314. infos = []
  315. if len(segs) > 1:
  316. for i in range(0, len(segs)-1):
  317. segs[i] += u'\u2005'
  318. pm = re.search(u'@.*\u2005', segs[i]).group()
  319. if pm:
  320. name = pm[1:-1]
  321. string = segs[i].replace(pm, '')
  322. str_msg_all += string + '@' + name + ' '
  323. str_msg += string
  324. if string:
  325. infos.append({'type': 'str', 'value': string})
  326. infos.append({'type': 'at', 'value': name})
  327. else:
  328. infos.append({'type': 'str', 'value': segs[i]})
  329. str_msg_all += segs[i]
  330. str_msg += segs[i]
  331. str_msg_all += segs[-1]
  332. str_msg += segs[-1]
  333. infos.append({'type': 'str', 'value': segs[-1]})
  334. else:
  335. infos.append({'type': 'str', 'value': segs[-1]})
  336. str_msg_all = msg
  337. str_msg = msg
  338. return str_msg_all.replace(u'\u2005', ''), str_msg.replace(u'\u2005', ''), infos
  339. def extract_msg_content(self, msg_type_id, msg):
  340. """
  341. content_type_id:
  342. 0 -> Text
  343. 1 -> Location
  344. 3 -> Image
  345. 4 -> Voice
  346. 5 -> Recommend
  347. 6 -> Animation
  348. 7 -> Share
  349. 8 -> Video
  350. 9 -> VideoCall
  351. 10 -> Redraw
  352. 11 -> Empty
  353. 99 -> Unknown
  354. :param msg_type_id: 消息类型id
  355. :param msg: 消息结构体
  356. :return: 解析的消息
  357. """
  358. mtype = msg['MsgType']
  359. content = HTMLParser.HTMLParser().unescape(msg['Content'])
  360. msg_id = msg['MsgId']
  361. msg_content = {}
  362. if msg_type_id == 0:
  363. return {'type': 11, 'data': ''}
  364. elif msg_type_id == 2: # File Helper
  365. return {'type': 0, 'data': content.replace('<br/>', '\n')}
  366. elif msg_type_id == 3: # 群聊
  367. sp = content.find('<br/>')
  368. uid = content[:sp]
  369. content = content[sp:]
  370. content = content.replace('<br/>', '')
  371. uid = uid[:-1]
  372. name = self.get_contact_prefer_name(self.get_contact_name(uid))
  373. if not name:
  374. name = self.get_group_member_prefer_name(self.get_group_member_name(uid, msg['FromUserName']))
  375. if not name:
  376. name = 'unknown'
  377. msg_content['user'] = {'id': uid, 'name': name}
  378. else: # Self, Contact, Special, Public, Unknown
  379. pass
  380. msg_prefix = (msg_content['user']['name'] + ':') if 'user' in msg_content else ''
  381. if mtype == 1:
  382. if content.find('http://weixin.qq.com/cgi-bin/redirectforward?args=') != -1:
  383. r = self.session.get(content)
  384. r.encoding = 'gbk'
  385. data = r.text
  386. pos = self.search_content('title', data, 'xml')
  387. msg_content['type'] = 1
  388. msg_content['data'] = pos
  389. msg_content['detail'] = data
  390. if self.DEBUG:
  391. print ' %s[Location] %s ' % (msg_prefix, pos)
  392. else:
  393. msg_content['type'] = 0
  394. if msg_type_id == 3 or (msg_type_id == 1 and msg['ToUserName'][:2] == '@@'): # Group text message
  395. msg_infos = self.proc_at_info(content)
  396. str_msg_all = msg_infos[0]
  397. str_msg = msg_infos[1]
  398. detail = msg_infos[2]
  399. msg_content['data'] = str_msg_all
  400. msg_content['detail'] = detail
  401. msg_content['desc'] = str_msg
  402. else:
  403. msg_content['data'] = content
  404. if self.DEBUG:
  405. try:
  406. print ' %s[Text] %s' % (msg_prefix, msg_content['data'])
  407. except UnicodeEncodeError:
  408. print ' %s[Text] (illegal text).' % msg_prefix
  409. elif mtype == 3:
  410. msg_content['type'] = 3
  411. msg_content['data'] = self.get_msg_img_url(msg_id)
  412. if self.DEBUG:
  413. image = self.get_msg_img(msg_id)
  414. print ' %s[Image] %s' % (msg_prefix, image)
  415. elif mtype == 34:
  416. msg_content['type'] = 4
  417. msg_content['data'] = self.get_voice_url(msg_id)
  418. if self.DEBUG:
  419. voice = self.get_voice(msg_id)
  420. print ' %s[Voice] %s' % (msg_prefix, voice)
  421. elif mtype == 42:
  422. msg_content['type'] = 5
  423. info = msg['RecommendInfo']
  424. msg_content['data'] = {'nickname': info['NickName'],
  425. 'alias': info['Alias'],
  426. 'province': info['Province'],
  427. 'city': info['City'],
  428. 'gender': ['unknown', 'male', 'female'][info['Sex']]}
  429. if self.DEBUG:
  430. print ' %s[Recommend]' % msg_prefix
  431. print ' -----------------------------'
  432. print ' | NickName: %s' % info['NickName']
  433. print ' | Alias: %s' % info['Alias']
  434. print ' | Local: %s %s' % (info['Province'], info['City'])
  435. print ' | Gender: %s' % ['unknown', 'male', 'female'][info['Sex']]
  436. print ' -----------------------------'
  437. elif mtype == 47:
  438. msg_content['type'] = 6
  439. msg_content['data'] = self.search_content('cdnurl', content)
  440. if self.DEBUG:
  441. print ' %s[Animation] %s' % (msg_prefix, msg_content['data'])
  442. elif mtype == 49:
  443. msg_content['type'] = 7
  444. if msg['AppMsgType'] == 3:
  445. app_msg_type = 'music'
  446. elif msg['AppMsgType'] == 5:
  447. app_msg_type = 'link'
  448. elif msg['AppMsgType'] == 7:
  449. app_msg_type = 'weibo'
  450. else:
  451. app_msg_type = 'unknown'
  452. msg_content['data'] = {'type': app_msg_type,
  453. 'title': msg['FileName'],
  454. 'desc': self.search_content('des', content, 'xml'),
  455. 'url': msg['Url'],
  456. 'from': self.search_content('appname', content, 'xml')}
  457. if self.DEBUG:
  458. print ' %s[Share] %s' % (msg_prefix, app_msg_type)
  459. print ' --------------------------'
  460. print ' | title: %s' % msg['FileName']
  461. print ' | desc: %s' % self.search_content('des', content, 'xml')
  462. print ' | link: %s' % msg['Url']
  463. print ' | from: %s' % self.search_content('appname', content, 'xml')
  464. print ' --------------------------'
  465. elif mtype == 62:
  466. msg_content['type'] = 8
  467. msg_content['data'] = content
  468. if self.DEBUG:
  469. print ' %s[Video] Please check on mobiles' % msg_prefix
  470. elif mtype == 53:
  471. msg_content['type'] = 9
  472. msg_content['data'] = content
  473. if self.DEBUG:
  474. print ' %s[Video Call]' % msg_prefix
  475. elif mtype == 10002:
  476. msg_content['type'] = 10
  477. msg_content['data'] = content
  478. if self.DEBUG:
  479. print ' %s[Redraw]' % msg_prefix
  480. elif mtype == 10000: # unknown, maybe red packet, or group invite
  481. msg_content['type'] = 12
  482. msg_content['data'] = msg['Content']
  483. if self.DEBUG:
  484. print ' [Unknown]'
  485. else:
  486. msg_content['type'] = 99
  487. msg_content['data'] = content
  488. if self.DEBUG:
  489. print ' %s[Unknown]' % msg_prefix
  490. return msg_content
  491. def handle_msg(self, r):
  492. """
  493. 处理原始微信消息的内部函数
  494. msg_type_id:
  495. 0 -> Init
  496. 1 -> Self
  497. 2 -> FileHelper
  498. 3 -> Group
  499. 4 -> Contact
  500. 5 -> Public
  501. 6 -> Special
  502. 99 -> Unknown
  503. :param r: 原始微信消息
  504. """
  505. for msg in r['AddMsgList']:
  506. user = {'id': msg['FromUserName'], 'name': 'unknown'}
  507. if msg['MsgType'] == 51: # init message
  508. msg_type_id = 0
  509. user['name'] = 'system'
  510. elif msg['FromUserName'] == self.my_account['UserName']: # Self
  511. msg_type_id = 1
  512. user['name'] = 'self'
  513. elif msg['ToUserName'] == 'filehelper': # File Helper
  514. msg_type_id = 2
  515. user['name'] = 'file_helper'
  516. elif msg['FromUserName'][:2] == '@@': # Group
  517. msg_type_id = 3
  518. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  519. elif self.is_contact(msg['FromUserName']): # Contact
  520. msg_type_id = 4
  521. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  522. elif self.is_public(msg['FromUserName']): # Public
  523. msg_type_id = 5
  524. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  525. elif self.is_special(msg['FromUserName']): # Special
  526. msg_type_id = 6
  527. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  528. else:
  529. msg_type_id = 99
  530. user['name'] = 'unknown'
  531. if not user['name']:
  532. user['name'] = 'unknown'
  533. user['name'] = HTMLParser.HTMLParser().unescape(user['name'])
  534. if self.DEBUG and msg_type_id != 0:
  535. print '[MSG] %s:' % user['name']
  536. content = self.extract_msg_content(msg_type_id, msg)
  537. message = {'msg_type_id': msg_type_id,
  538. 'msg_id': msg['MsgId'],
  539. 'content': content,
  540. 'to_user_id': msg['ToUserName'],
  541. 'user': user}
  542. self.handle_msg_all(message)
  543. def schedule(self):
  544. """
  545. 做任务型事情的函数,如果需要,可以在子类中覆盖此函数
  546. 此函数在处理消息的间隙被调用,请不要长时间阻塞此函数
  547. """
  548. pass
  549. def proc_msg(self):
  550. self.test_sync_check()
  551. while True:
  552. check_time = time.time()
  553. try:
  554. [retcode, selector] = self.sync_check()
  555. # print '[DEBUG] sync_check:', retcode, selector
  556. if retcode == '1100': # 从微信客户端上登出
  557. break
  558. elif retcode == '1101': # 从其它设备上登了网页微信
  559. break
  560. elif retcode == '0':
  561. if selector == '2': # 有新消息
  562. r = self.sync()
  563. if r is not None:
  564. self.handle_msg(r)
  565. elif selector == '3': # 未知
  566. r = self.sync()
  567. if r is not None:
  568. self.handle_msg(r)
  569. elif selector == '6': # 可能是红包
  570. r = self.sync()
  571. if r is not None:
  572. self.handle_msg(r)
  573. elif selector == '7': # 在手机上操作了微信
  574. r = self.sync()
  575. if r is not None:
  576. self.handle_msg(r)
  577. elif selector == '0': # 无事件
  578. pass
  579. else:
  580. print '[DEBUG] sync_check:', retcode, selector
  581. r = self.sync()
  582. if r is not None:
  583. self.handle_msg(r)
  584. else:
  585. print '[DEBUG] sync_check:', retcode, selector
  586. self.schedule()
  587. except:
  588. print '[ERROR] Except in proc_msg'
  589. check_time = time.time() - check_time
  590. if check_time < 0.8:
  591. time.sleep(1 - check_time)
  592. def send_msg_by_uid(self, word, dst='filehelper'):
  593. url = self.base_uri + '/webwxsendmsg?pass_ticket=%s' % self.pass_ticket
  594. msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
  595. word = self.to_unicode(word)
  596. params = {
  597. 'BaseRequest': self.base_request,
  598. 'Msg': {
  599. "Type": 1,
  600. "Content": word,
  601. "FromUserName": self.my_account['UserName'],
  602. "ToUserName": dst,
  603. "LocalID": msg_id,
  604. "ClientMsgId": msg_id
  605. }
  606. }
  607. headers = {'content-type': 'application/json; charset=UTF-8'}
  608. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  609. try:
  610. r = self.session.post(url, data=data, headers=headers)
  611. except (ConnectionError, ReadTimeout):
  612. return False
  613. dic = r.json()
  614. return dic['BaseResponse']['Ret'] == 0
  615. def get_user_id(self, name):
  616. if name == '':
  617. return None
  618. name = self.to_unicode(name)
  619. for contact in self.contact_list:
  620. if 'RemarkName' in contact and contact['RemarkName'] == name:
  621. return contact['UserName']
  622. elif 'NickName' in contact and contact['NickName'] == name:
  623. return contact['UserName']
  624. elif 'DisplayName' in contact and contact['DisplayName'] == name:
  625. return contact['UserName']
  626. for group in self.group_list:
  627. if 'RemarkName' in group and group['RemarkName'] == name:
  628. return group['UserName']
  629. if 'NickName' in group and group['NickName'] == name:
  630. return group['UserName']
  631. if 'DisplayName' in group and group['DisplayName'] == name:
  632. return group['UserName']
  633. return ''
  634. def send_msg(self, name, word, isfile=False):
  635. uid = self.get_user_id(name)
  636. if uid is not None:
  637. if isfile:
  638. with open(word, 'r') as f:
  639. result = True
  640. for line in f.readlines():
  641. line = line.replace('\n', '')
  642. print '-> ' + name + ': ' + line
  643. if self.send_msg_by_uid(line, uid):
  644. pass
  645. else:
  646. result = False
  647. time.sleep(1)
  648. return result
  649. else:
  650. word = self.to_unicode(word)
  651. if self.send_msg_by_uid(word, uid):
  652. return True
  653. else:
  654. return False
  655. else:
  656. if self.DEBUG:
  657. print '[ERROR] This user does not exist .'
  658. return True
  659. @staticmethod
  660. def search_content(key, content, fmat='attr'):
  661. if fmat == 'attr':
  662. pm = re.search(key + '\s?=\s?"([^"<]+)"', content)
  663. if pm:
  664. return pm.group(1)
  665. elif fmat == 'xml':
  666. pm = re.search('<{0}>([^<]+)</{0}>'.format(key), content)
  667. if pm:
  668. return pm.group(1)
  669. return 'unknown'
  670. def run(self):
  671. self.get_uuid()
  672. self.gen_qr_code('qr.png')
  673. print '[INFO] Please use WeChat to scan the QR code .'
  674. result = self.wait4login()
  675. if result != SUCCESS:
  676. print '[ERROR] Web WeChat login failed. failed code=%s'%(result, )
  677. return
  678. if self.login():
  679. print '[INFO] Web WeChat login succeed .'
  680. else:
  681. print '[ERROR] Web WeChat login failed .'
  682. return
  683. if self.init():
  684. print '[INFO] Web WeChat init succeed .'
  685. else:
  686. print '[INFO] Web WeChat init failed'
  687. return
  688. self.status_notify()
  689. self.get_contact()
  690. print '[INFO] Get %d contacts' % len(self.contact_list)
  691. print '[INFO] Start to process messages .'
  692. self.proc_msg()
  693. def get_uuid(self):
  694. url = 'https://login.weixin.qq.com/jslogin'
  695. params = {
  696. 'appid': 'wx782c26e4c19acffb',
  697. 'fun': 'new',
  698. 'lang': 'zh_CN',
  699. '_': int(time.time()) * 1000 + random.randint(1, 999),
  700. }
  701. r = self.session.get(url, params=params)
  702. r.encoding = 'utf-8'
  703. data = r.text
  704. regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
  705. pm = re.search(regx, data)
  706. if pm:
  707. code = pm.group(1)
  708. self.uuid = pm.group(2)
  709. return code == '200'
  710. return False
  711. def gen_qr_code(self, qr_file_path):
  712. string = 'https://login.weixin.qq.com/l/' + self.uuid
  713. qr = pyqrcode.create(string)
  714. if self.conf['qr'] == 'png':
  715. qr.png(qr_file_path, scale=8)
  716. show_image(qr_file_path)
  717. # img = Image.open(qr_file_path)
  718. # img.show()
  719. elif self.conf['qr'] == 'tty':
  720. print(qr.terminal(quiet_zone=1))
  721. def do_request(self, url):
  722. r = self.session.get(url)
  723. r.encoding = 'utf-8'
  724. data = r.text
  725. param = re.search(r'window.code=(\d+);', data)
  726. code = param.group(1)
  727. return code, data
  728. def wait4login(self):
  729. """
  730. http comet:
  731. tip=1, 等待用户扫描二维码,
  732. 201: scaned
  733. 408: timeout
  734. tip=0, 等待用户确认登录,
  735. 200: confirmed
  736. """
  737. LOGIN_TEMPLATE = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s'
  738. tip = 1
  739. try_later_secs = 1
  740. MAX_RETRY_TIMES = 10
  741. code = UNKONWN
  742. retry_time = MAX_RETRY_TIMES
  743. while retry_time > 0:
  744. url = LOGIN_TEMPLATE % (tip, self.uuid, int(time.time()))
  745. code, data = self.do_request(url)
  746. if code == SCANED:
  747. print '[INFO] Please confirm to login .'
  748. tip = 0
  749. elif code == SUCCESS: # 确认登录成功
  750. param = re.search(r'window.redirect_uri="(\S+?)";', data)
  751. redirect_uri = param.group(1) + '&fun=new'
  752. self.redirect_uri = redirect_uri
  753. self.base_uri = redirect_uri[:redirect_uri.rfind('/')]
  754. return code
  755. elif code == TIMEOUT:
  756. print '[ERROR] WeChat login timeout. retry in %s secs later...'%(try_later_secs, )
  757. tip = 1 # 重置
  758. retry_time -= 1
  759. time.sleep(try_later_secs)
  760. else:
  761. print ('[ERROR] WeChat login exception return_code=%s. retry in %s secs later...' %
  762. (code, try_later_secs))
  763. tip = 1
  764. retry_time -= 1
  765. time.sleep(try_later_secs)
  766. return code
  767. def login(self):
  768. if len(self.redirect_uri) < 4:
  769. print '[ERROR] Login failed due to network problem, please try again.'
  770. return False
  771. r = self.session.get(self.redirect_uri)
  772. r.encoding = 'utf-8'
  773. data = r.text
  774. doc = xml.dom.minidom.parseString(data)
  775. root = doc.documentElement
  776. for node in root.childNodes:
  777. if node.nodeName == 'skey':
  778. self.skey = node.childNodes[0].data
  779. elif node.nodeName == 'wxsid':
  780. self.sid = node.childNodes[0].data
  781. elif node.nodeName == 'wxuin':
  782. self.uin = node.childNodes[0].data
  783. elif node.nodeName == 'pass_ticket':
  784. self.pass_ticket = node.childNodes[0].data
  785. if '' in (self.skey, self.sid, self.uin, self.pass_ticket):
  786. return False
  787. self.base_request = {
  788. 'Uin': self.uin,
  789. 'Sid': self.sid,
  790. 'Skey': self.skey,
  791. 'DeviceID': self.device_id,
  792. }
  793. return True
  794. def init(self):
  795. url = self.base_uri + '/webwxinit?r=%i&lang=en_US&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  796. params = {
  797. 'BaseRequest': self.base_request
  798. }
  799. r = self.session.post(url, data=json.dumps(params))
  800. r.encoding = 'utf-8'
  801. dic = json.loads(r.text)
  802. self.sync_key = dic['SyncKey']
  803. self.my_account = dic['User']
  804. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  805. for keyVal in self.sync_key['List']])
  806. return dic['BaseResponse']['Ret'] == 0
  807. def status_notify(self):
  808. url = self.base_uri + '/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % self.pass_ticket
  809. self.base_request['Uin'] = int(self.base_request['Uin'])
  810. params = {
  811. 'BaseRequest': self.base_request,
  812. "Code": 3,
  813. "FromUserName": self.my_account['UserName'],
  814. "ToUserName": self.my_account['UserName'],
  815. "ClientMsgId": int(time.time())
  816. }
  817. r = self.session.post(url, data=json.dumps(params))
  818. r.encoding = 'utf-8'
  819. dic = json.loads(r.text)
  820. return dic['BaseResponse']['Ret'] == 0
  821. def test_sync_check(self):
  822. for host in ['webpush', 'webpush2']:
  823. self.sync_host = host
  824. retcode = self.sync_check()[0]
  825. if retcode == '0':
  826. return True
  827. return False
  828. def sync_check(self):
  829. params = {
  830. 'r': int(time.time()),
  831. 'sid': self.sid,
  832. 'uin': self.uin,
  833. 'skey': self.skey,
  834. 'deviceid': self.device_id,
  835. 'synckey': self.sync_key_str,
  836. '_': int(time.time()),
  837. }
  838. url = 'https://' + self.sync_host + '.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?' + urllib.urlencode(params)
  839. try:
  840. r = self.session.get(url, timeout=60)
  841. r.encoding = 'utf-8'
  842. data = r.text
  843. pm = re.search(r'window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}', data)
  844. retcode = pm.group(1)
  845. selector = pm.group(2)
  846. return [retcode, selector]
  847. except:
  848. return [-1, -1]
  849. def sync(self):
  850. url = self.base_uri + '/webwxsync?sid=%s&skey=%s&lang=en_US&pass_ticket=%s' \
  851. % (self.sid, self.skey, self.pass_ticket)
  852. params = {
  853. 'BaseRequest': self.base_request,
  854. 'SyncKey': self.sync_key,
  855. 'rr': ~int(time.time())
  856. }
  857. try:
  858. r = self.session.post(url, data=json.dumps(params), timeout=60)
  859. r.encoding = 'utf-8'
  860. dic = json.loads(r.text)
  861. if dic['BaseResponse']['Ret'] == 0:
  862. self.sync_key = dic['SyncKey']
  863. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  864. for keyVal in self.sync_key['List']])
  865. return dic
  866. except:
  867. return None
  868. def get_icon(self, uid, gid=None):
  869. """
  870. 获取联系人或者群聊成员头像
  871. :param uid: 联系人id
  872. :param gid: 群id,如果为非None获取群中成员头像,如果为None则获取联系人头像
  873. """
  874. if gid is None:
  875. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s' % (uid, self.skey)
  876. else:
  877. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s&chatroomid=%s' % (uid, self.skey, self.encry_chat_room_id_list[gid])
  878. r = self.session.get(url)
  879. data = r.content
  880. fn = 'icon_' + uid + '.jpg'
  881. with open(fn, 'wb') as f:
  882. f.write(data)
  883. return fn
  884. def get_head_img(self, uid):
  885. """
  886. 获取群头像
  887. :param uid: 群uid
  888. """
  889. url = self.base_uri + '/webwxgetheadimg?username=%s&skey=%s' % (uid, self.skey)
  890. r = self.session.get(url)
  891. data = r.content
  892. fn = 'head_' + uid + '.jpg'
  893. with open(fn, 'wb') as f:
  894. f.write(data)
  895. return fn
  896. def get_msg_img_url(self, msgid):
  897. return self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  898. def get_msg_img(self, msgid):
  899. """
  900. 获取图片消息,下载图片到本地
  901. :param msgid: 消息id
  902. :return: 保存的本地图片文件路径
  903. """
  904. url = self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  905. r = self.session.get(url)
  906. data = r.content
  907. fn = 'img_' + msgid + '.jpg'
  908. with open(fn, 'wb') as f:
  909. f.write(data)
  910. return fn
  911. def get_voice_url(self, msgid):
  912. return self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  913. def get_voice(self, msgid):
  914. """
  915. 获取语音消息,下载语音到本地
  916. :param msgid: 语音消息id
  917. :return: 保存的本地语音文件路径
  918. """
  919. url = self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  920. r = self.session.get(url)
  921. data = r.content
  922. fn = 'voice_' + msgid + '.mp3'
  923. with open(fn, 'wb') as f:
  924. f.write(data)
  925. return fn