wxbot.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. import pyqrcode
  4. import requests
  5. import json
  6. import xml.dom.minidom
  7. import urllib
  8. import time
  9. import re
  10. import random
  11. from requests.exceptions import *
  12. import os,subprocess,sys
  13. class WXBot:
  14. """WXBot, a framework to process WeChat messages"""
  15. def __init__(self):
  16. self.DEBUG = False
  17. self.uuid = ''
  18. self.base_uri = ''
  19. self.redirect_uri = ''
  20. self.uin = ''
  21. self.sid = ''
  22. self.skey = ''
  23. self.pass_ticket = ''
  24. self.device_id = 'e' + repr(random.random())[2:17]
  25. self.base_request = {}
  26. self.sync_key_str = ''
  27. self.sync_key = []
  28. self.user = {}
  29. self.account_info = {}
  30. self.member_list = [] # all kind of accounts: contacts, public accounts, groups, special accounts
  31. self.contact_list = [] # contact list
  32. self.public_list = [] # public account list
  33. self.group_list = [] # group chat list
  34. self.special_list = [] # special list account
  35. self.group_members = {} # members of all groups
  36. self.sync_host = ''
  37. self.session = requests.Session()
  38. self.session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5'})
  39. self.conf = {'qr': 'png'}
  40. def get_contact(self):
  41. """Get information of all contacts of current account."""
  42. url = self.base_uri + '/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s' \
  43. % (self.pass_ticket, self.skey, int(time.time()))
  44. r = self.session.post(url, data='{}')
  45. r.encoding = 'utf-8'
  46. if self.DEBUG:
  47. with open('contacts.json', 'w') as f:
  48. f.write(r.text.encode('utf-8'))
  49. dic = json.loads(r.text)
  50. self.member_list = dic['MemberList']
  51. special_users = ['newsapp', 'fmessage', 'filehelper', 'weibo', 'qqmail',
  52. 'fmessage', 'tmessage', 'qmessage', 'qqsync', 'floatbottle',
  53. 'lbsapp', 'shakeapp', 'medianote', 'qqfriend', 'readerapp',
  54. 'blogapp', 'facebookapp', 'masssendapp', 'meishiapp',
  55. 'feedsapp', 'voip', 'blogappweixin', 'weixin', 'brandsessionholder',
  56. 'weixinreminder', 'wxid_novlwrv3lqwv11', 'gh_22b87fa7cb3c',
  57. 'officialaccounts', 'notification_messages', 'wxid_novlwrv3lqwv11',
  58. 'gh_22b87fa7cb3c', 'wxitil', 'userexperience_alarm', 'notification_messages']
  59. self.contact_list = []
  60. self.public_list = []
  61. self.special_list = []
  62. self.group_list = []
  63. for contact in self.member_list:
  64. if contact['VerifyFlag'] & 8 != 0: # public account
  65. self.public_list.append(contact)
  66. self.account_info[contact['UserName']] = {'type': 'public', 'info': contact}
  67. elif contact['UserName'] in special_users: # special account
  68. self.special_list.append(contact)
  69. self.account_info[contact['UserName']] = {'type': 'special', 'info': contact}
  70. elif contact['UserName'].find('@@') != -1: # group
  71. self.group_list.append(contact)
  72. self.account_info[contact['UserName']] = {'type': 'group', 'info': contact}
  73. elif contact['UserName'] == self.user['UserName']: # self
  74. self.account_info[contact['UserName']] = {'type': 'self', 'info': contact}
  75. pass
  76. else:
  77. self.contact_list.append(contact)
  78. self.group_members = self.batch_get_group_members()
  79. for group in self.group_members:
  80. for member in self.group_members[group]:
  81. if member['UserName'] not in self.account_info:
  82. self.account_info[member['UserName']] = {'type': 'group_member', 'info': member, 'group': group}
  83. if self.DEBUG:
  84. with open('contact_list.json', 'w') as f:
  85. f.write(json.dumps(self.contact_list))
  86. with open('special_list.json', 'w') as f:
  87. f.write(json.dumps(self.special_list))
  88. with open('group_list.json', 'w') as f:
  89. f.write(json.dumps(self.group_list))
  90. with open('public_list.json', 'w') as f:
  91. f.write(json.dumps(self.public_list))
  92. with open('member_list.json', 'w') as f:
  93. f.write(json.dumps(self.member_list))
  94. with open('group_users.json', 'w') as f:
  95. f.write(json.dumps(self.group_members))
  96. with open('account_info.json', 'w') as f:
  97. f.write(json.dumps(self.account_info))
  98. return True
  99. def batch_get_group_members(self):
  100. """Get information of accounts in all groups at once."""
  101. url = self.base_uri + '/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  102. params = {
  103. 'BaseRequest': self.base_request,
  104. "Count": len(self.group_list),
  105. "List": [{"UserName": group['UserName'], "EncryChatRoomId": ""} for group in self.group_list]
  106. }
  107. r = self.session.post(url, data=json.dumps(params))
  108. r.encoding = 'utf-8'
  109. dic = json.loads(r.text)
  110. group_members = {}
  111. for group in dic['ContactList']:
  112. gid = group['UserName']
  113. members = group['MemberList']
  114. group_members[gid] = members
  115. return group_members
  116. def get_group_member_name(self, gid, uid):
  117. """
  118. Get name of a member in a group.
  119. :param gid: group id
  120. :param uid: group member id
  121. :return: names like {"display_name": "test_user", "nickname": "test", "remark_name": "for_test" }
  122. """
  123. if gid not in self.group_members:
  124. return None
  125. group = self.group_members[gid]
  126. for member in group:
  127. if member['UserName'] == uid:
  128. names = {}
  129. if 'RemarkName' in member:
  130. names['remark_name'] = member['RemarkName']
  131. if 'NickName' in member:
  132. names['nickname'] = member['NickName']
  133. if 'DisplayName' in member:
  134. names['display_name'] = member['DisplayName']
  135. return names
  136. return None
  137. def get_account_info(self, uid):
  138. if uid in self.account_info:
  139. return self.account_info[uid]
  140. else:
  141. return None
  142. def get_account_name(self, uid):
  143. info = self.get_account_info(uid)
  144. if info is None:
  145. return 'unknown'
  146. info = info['info']
  147. name = {}
  148. if 'RemarkName' in info and info['RemarkName']:
  149. name['remark_name'] = info['RemarkName']
  150. if 'NickName' in info and info['NickName']:
  151. name['nickname'] = info['NickName']
  152. if 'DisplayName' in info and info['DisplayName']:
  153. name['display_name'] = info['DisplayName']
  154. return name
  155. @staticmethod
  156. def get_prefer_name(name):
  157. if 'remark_name' in name:
  158. return name['remark_name']
  159. if 'display_name' in name:
  160. return name['display_name']
  161. if 'nickname' in name:
  162. return name['nickname']
  163. return 'unknown'
  164. def get_user_type(self, wx_user_id):
  165. """
  166. Get the relationship of a account and current user.
  167. :param wx_user_id:
  168. :return: The type of the account.
  169. """
  170. for account in self.contact_list:
  171. if wx_user_id == account['UserName']:
  172. return 'contact'
  173. for account in self.public_list:
  174. if wx_user_id == account['UserName']:
  175. return 'public'
  176. for account in self.special_list:
  177. if wx_user_id == account['UserName']:
  178. return 'special'
  179. for account in self.group_list:
  180. if wx_user_id == account['UserName']:
  181. return 'group'
  182. for group in self.group_members:
  183. for member in self.group_members[group]:
  184. if member['UserName'] == wx_user_id:
  185. return 'group_member'
  186. return 'unknown'
  187. def is_contact(self, uid):
  188. for account in self.contact_list:
  189. if uid == account['UserName']:
  190. return True
  191. return False
  192. def is_public(self, uid):
  193. for account in self.public_list:
  194. if uid == account['UserName']:
  195. return True
  196. return False
  197. def is_special(self, uid):
  198. for account in self.special_list:
  199. if uid == account['UserName']:
  200. return True
  201. return False
  202. def handle_msg_all(self, msg):
  203. """
  204. The function to process all WeChat messages, please override this function.
  205. msg:
  206. msg_id -> id of the received WeChat message
  207. msg_type_id -> the type of the message
  208. user -> the account that the message if sent from
  209. content -> content of the message
  210. :param msg: The received message.
  211. :return: None
  212. """
  213. pass
  214. def extract_msg_content(self, msg_type_id, msg):
  215. """
  216. content_type_id:
  217. 0 -> Text
  218. 1 -> Location
  219. 3 -> Image
  220. 4 -> Voice
  221. 5 -> Recommend
  222. 6 -> Animation
  223. 7 -> Share
  224. 8 -> Video
  225. 9 -> VideoCall
  226. 10 -> Redraw
  227. 11 -> Empty
  228. 99 -> Unknown
  229. :param msg_type_id: The type of the received message.
  230. :param msg: The received message.
  231. :return: The extracted content of the message.
  232. """
  233. mtype = msg['MsgType']
  234. content = msg['Content'].replace('&lt;', '<').replace('&gt;', '>')
  235. msg_id = msg['MsgId']
  236. msg_content = {}
  237. if msg_type_id == 0:
  238. return {'type': 11, 'data': ''}
  239. elif msg_type_id == 2: # File Helper
  240. return {'type': 0, 'data': content.replace('<br/>', '\n')}
  241. elif msg_type_id == 3: # Group
  242. sp = content.find('<br/>')
  243. uid = content[:sp]
  244. content = content[sp:]
  245. content = content.replace('<br/>', '')
  246. uid = uid[:-1]
  247. msg_content['user'] = {'id': uid, 'name': self.get_prefer_name(self.get_account_name(uid))}
  248. else: # Self, Contact, Special, Public, Unknown
  249. pass
  250. msg_prefix = (msg_content['user']['name'] + ':') if 'user' in msg_content else ''
  251. if mtype == 1:
  252. if content.find('http://weixin.qq.com/cgi-bin/redirectforward?args=') != -1:
  253. r = self.session.get(content)
  254. r.encoding = 'gbk'
  255. data = r.text
  256. pos = self.search_content('title', data, 'xml')
  257. msg_content['type'] = 1
  258. msg_content['data'] = pos
  259. msg_content['detail'] = data
  260. if self.DEBUG:
  261. print ' %s[Location] %s ' % (msg_prefix, pos)
  262. else:
  263. msg_content['type'] = 0
  264. msg_content['data'] = content.replace(u'\u2005', '')
  265. if self.DEBUG:
  266. print ' %s[Text] %s' % (msg_prefix, msg_content['data'])
  267. elif mtype == 3:
  268. msg_content['type'] = 3
  269. msg_content['data'] = self.get_msg_img_url(msg_id)
  270. if self.DEBUG:
  271. image = self.get_msg_img(msg_id)
  272. print ' %s[Image] %s' % (msg_prefix, image)
  273. elif mtype == 34:
  274. msg_content['type'] = 4
  275. msg_content['data'] = self.get_voice_url(msg_id)
  276. if self.DEBUG:
  277. voice = self.get_voice(msg_id)
  278. print ' %s[Voice] %s' % (msg_prefix, voice)
  279. elif mtype == 42:
  280. msg_content['type'] = 5
  281. info = msg['RecommendInfo']
  282. msg_content['data'] = {'nickname': info['NickName'],
  283. 'alias': info['Alias'],
  284. 'province': info['Province'],
  285. 'city': info['City'],
  286. 'gender': ['unknown', 'male', 'female'][info['Sex']]}
  287. if self.DEBUG:
  288. print ' %s[Recommend]' % msg_prefix
  289. print ' -----------------------------'
  290. print ' | NickName: %s' % info['NickName']
  291. print ' | Alias: %s' % info['Alias']
  292. print ' | Local: %s %s' % (info['Province'], info['City'])
  293. print ' | Gender: %s' % ['unknown', 'male', 'female'][info['Sex']]
  294. print ' -----------------------------'
  295. elif mtype == 47:
  296. msg_content['type'] = 6
  297. msg_content['data'] = self.search_content('cdnurl', content)
  298. if self.DEBUG:
  299. print ' %s[Animation] %s' % (msg_prefix, msg_content['data'])
  300. elif mtype == 49:
  301. msg_content['type'] = 7
  302. app_msg_type = ''
  303. if msg['AppMsgType'] == 3:
  304. app_msg_type = 'music'
  305. elif msg['AppMsgType'] == 5:
  306. app_msg_type = 'link'
  307. elif msg['AppMsgType'] == 7:
  308. app_msg_type = 'weibo'
  309. else:
  310. app_msg_type = 'unknown'
  311. msg_content['data'] = {'type': app_msg_type,
  312. 'title': msg['FileName'],
  313. 'desc': self.search_content('des', content, 'xml'),
  314. 'url': msg['Url'],
  315. 'from': self.search_content('appname', content, 'xml')}
  316. if self.DEBUG:
  317. print ' %s[Share] %s' % (msg_prefix, app_msg_type)
  318. print ' --------------------------'
  319. print ' | title: %s' % msg['FileName']
  320. print ' | desc: %s' % self.search_content('des', content, 'xml')
  321. print ' | link: %s' % msg['Url']
  322. print ' | from: %s' % self.search_content('appname', content, 'xml')
  323. print ' --------------------------'
  324. elif mtype == 62:
  325. msg_content['type'] = 8
  326. msg_content['data'] = content
  327. if self.DEBUG:
  328. print ' %s[Video] Please check on mobiles' % msg_prefix
  329. elif mtype == 53:
  330. msg_content['type'] = 9
  331. msg_content['data'] = content
  332. if self.DEBUG:
  333. print ' %s[Video Call]' % msg_prefix
  334. elif mtype == 10002:
  335. msg_content['type'] = 10
  336. msg_content['data'] = content
  337. if self.DEBUG:
  338. print ' %s[Redraw]' % msg_prefix
  339. elif mtype == 10000:
  340. msg_content['type'] = 12
  341. msg_content['data'] = msg['Content']
  342. if self.DEBUG:
  343. print ' [Red Packet]'
  344. else:
  345. msg_content['type'] = 99
  346. msg_content['data'] = content
  347. if self.DEBUG:
  348. print ' %s[Unknown]' % msg_prefix
  349. return msg_content
  350. def handle_msg(self, r):
  351. """
  352. The inner function that processes raw WeChat messages.
  353. msg_type_id:
  354. 0 -> Init
  355. 1 -> Self
  356. 2 -> FileHelper
  357. 3 -> Group
  358. 4 -> Contact
  359. 5 -> Public
  360. 6 -> Special
  361. 99 -> Unknown
  362. :param r: The raw data of the messages.
  363. :return: None
  364. """
  365. for msg in r['AddMsgList']:
  366. msg_type_id = 99
  367. user = {'id': msg['FromUserName']}
  368. if msg['MsgType'] == 51: # init message
  369. msg_type_id = 0
  370. elif msg['FromUserName'] == self.user['UserName']: # Self
  371. msg_type_id = 1
  372. user['name'] = 'self'
  373. elif msg['ToUserName'] == 'filehelper': # File Helper
  374. msg_type_id = 2
  375. user['name'] = 'file_helper'
  376. elif msg['FromUserName'][:2] == '@@': # Group
  377. msg_type_id = 3
  378. user['name'] = self.get_prefer_name(self.get_account_name(user['id']))
  379. elif self.is_contact(msg['FromUserName']): # Contact
  380. msg_type_id = 4
  381. user['name'] = self.get_prefer_name(self.get_account_name(user['id']))
  382. elif self.is_public(msg['FromUserName']): # Public
  383. msg_type_id = 5
  384. user['name'] = self.get_prefer_name(self.get_account_name(user['id']))
  385. elif self.is_special(msg['FromUserName']): # Special
  386. msg_type_id = 6
  387. user['name'] = self.get_prefer_name(self.get_account_name(user['id']))
  388. if self.DEBUG and msg_type_id != 0:
  389. print '[MSG] %s:' % user['name']
  390. content = self.extract_msg_content(msg_type_id, msg)
  391. message = {'msg_type_id': msg_type_id,
  392. 'msg_id': msg['MsgId'],
  393. 'content': content,
  394. 'user': user}
  395. self.handle_msg_all(message)
  396. def schedule(self):
  397. """
  398. The function to do schedule works.
  399. This function will be called a lot of times.
  400. Please override this if needed.
  401. :return: None
  402. """
  403. pass
  404. def proc_msg(self):
  405. self.test_sync_check()
  406. while True:
  407. check_time = time.time()
  408. [retcode, selector] = self.sync_check()
  409. if retcode == '1100': # logout from mobile
  410. break
  411. elif retcode == '1101': # login web WeChat from other devide
  412. break
  413. elif retcode == '0':
  414. if selector == '2': # new message
  415. r = self.sync()
  416. if r is not None:
  417. self.handle_msg(r)
  418. elif selector == '7': # Play WeChat on mobile
  419. r = self.sync()
  420. if r is not None:
  421. self.handle_msg(r)
  422. elif selector == '0': # nothing
  423. pass
  424. else:
  425. pass
  426. self.schedule()
  427. check_time = time.time() - check_time
  428. if check_time < 0.5:
  429. time.sleep(0.5 - check_time)
  430. def send_msg_by_uid(self, word, dst='filehelper'):
  431. url = self.base_uri + '/webwxsendmsg?pass_ticket=%s' % self.pass_ticket
  432. msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
  433. if type(word) == 'str':
  434. word = word.decode('utf-8')
  435. params = {
  436. 'BaseRequest': self.base_request,
  437. 'Msg': {
  438. "Type": 1,
  439. "Content": word,
  440. "FromUserName": self.user['UserName'],
  441. "ToUserName": dst,
  442. "LocalID": msg_id,
  443. "ClientMsgId": msg_id
  444. }
  445. }
  446. headers = {'content-type': 'application/json; charset=UTF-8'}
  447. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  448. try:
  449. r = self.session.post(url, data=data, headers=headers)
  450. except (ConnectionError, ReadTimeout):
  451. return False
  452. dic = r.json()
  453. return dic['BaseResponse']['Ret'] == 0
  454. def send_msg(self, name, word, isfile=False):
  455. uid = self.get_user_id(name)
  456. if uid:
  457. if isfile:
  458. with open(word, 'r') as f:
  459. result = True
  460. for line in f.readlines():
  461. line = line.replace('\n', '')
  462. print '-> ' + name + ': ' + line
  463. if self.send_msg_by_uid(line, uid):
  464. pass
  465. else:
  466. result = False
  467. time.sleep(1)
  468. return result
  469. else:
  470. if self.send_msg_by_uid(word, uid):
  471. return True
  472. else:
  473. return False
  474. else:
  475. if self.DEBUG:
  476. print '[ERROR] This user does not exist .'
  477. return True
  478. @staticmethod
  479. def search_content(key, content, fmat='attr'):
  480. if fmat == 'attr':
  481. pm = re.search(key + '\s?=\s?"([^"<]+)"', content)
  482. if pm:
  483. return pm.group(1)
  484. elif fmat == 'xml':
  485. pm = re.search('<{0}>([^<]+)</{0}>'.format(key), content)
  486. if pm:
  487. return pm.group(1)
  488. return 'unknown'
  489. def run(self):
  490. self.get_uuid()
  491. self.gen_qr_code('qr.png')
  492. print '[INFO] Please use WeCaht to scan the QR code .'
  493. self.wait4login(1)
  494. print '[INFO] Please confirm to login .'
  495. self.wait4login(0)
  496. if self.login():
  497. print '[INFO] Web WeChat login succeed .'
  498. else:
  499. print '[ERROR] Web WeChat login failed .'
  500. return
  501. if self.init():
  502. print '[INFO] Web WeChat init succeed .'
  503. else:
  504. print '[INFO] Web WeChat init failed'
  505. return
  506. self.status_notify()
  507. self.get_contact()
  508. print '[INFO] Get %d contacts' % len(self.contact_list)
  509. print '[INFO] Start to process messages .'
  510. self.proc_msg()
  511. def get_uuid(self):
  512. url = 'https://login.weixin.qq.com/jslogin'
  513. params = {
  514. 'appid': 'wx782c26e4c19acffb',
  515. 'fun': 'new',
  516. 'lang': 'zh_CN',
  517. '_': int(time.time()) * 1000 + random.randint(1, 999),
  518. }
  519. r = self.session.get(url, params=params)
  520. r.encoding = 'utf-8'
  521. data = r.text
  522. regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
  523. pm = re.search(regx, data)
  524. if pm:
  525. code = pm.group(1)
  526. self.uuid = pm.group(2)
  527. return code == '200'
  528. return False
  529. def gen_qr_code(self, qr_file_path):
  530. string = 'https://login.weixin.qq.com/l/' + self.uuid
  531. qr = pyqrcode.create(string)
  532. if self.conf['qr'] == 'png':
  533. qr.png(qr_file_path)
  534. if sys.platform.find('darwin') >= 0:
  535. subprocess.call(['open', qr_file_path])
  536. elif sys.platform.find('linux') >= 0:
  537. subprocess.call(['xdg-open', qr_file_path])
  538. else:
  539. os.startfile(qr_file_path)
  540. elif self.conf['qr'] == 'tty':
  541. print(qr.terminal(quiet_zone=1))
  542. def wait4login(self, tip):
  543. time.sleep(tip)
  544. url = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s' \
  545. % (tip, self.uuid, int(time.time()))
  546. r = self.session.get(url)
  547. r.encoding = 'utf-8'
  548. data = r.text
  549. param = re.search(r'window.code=(\d+);', data)
  550. code = param.group(1)
  551. if code == '201':
  552. return True
  553. elif code == '200':
  554. param = re.search(r'window.redirect_uri="(\S+?)";', data)
  555. redirect_uri = param.group(1) + '&fun=new'
  556. self.redirect_uri = redirect_uri
  557. self.base_uri = redirect_uri[:redirect_uri.rfind('/')]
  558. return True
  559. elif code == '408':
  560. print '[ERROR] WeChat login timeout .'
  561. else:
  562. print '[ERROR] WeChat login exception .'
  563. return False
  564. def login(self):
  565. r = self.session.get(self.redirect_uri)
  566. r.encoding = 'utf-8'
  567. data = r.text
  568. doc = xml.dom.minidom.parseString(data)
  569. root = doc.documentElement
  570. for node in root.childNodes:
  571. if node.nodeName == 'skey':
  572. self.skey = node.childNodes[0].data
  573. elif node.nodeName == 'wxsid':
  574. self.sid = node.childNodes[0].data
  575. elif node.nodeName == 'wxuin':
  576. self.uin = node.childNodes[0].data
  577. elif node.nodeName == 'pass_ticket':
  578. self.pass_ticket = node.childNodes[0].data
  579. if '' in (self.skey, self.sid, self.uin, self.pass_ticket):
  580. return False
  581. self.base_request = {
  582. 'Uin': self.uin,
  583. 'Sid': self.sid,
  584. 'Skey': self.skey,
  585. 'DeviceID': self.device_id,
  586. }
  587. return True
  588. def init(self):
  589. url = self.base_uri + '/webwxinit?r=%i&lang=en_US&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  590. params = {
  591. 'BaseRequest': self.base_request
  592. }
  593. r = self.session.post(url, data=json.dumps(params))
  594. r.encoding = 'utf-8'
  595. dic = json.loads(r.text)
  596. self.sync_key = dic['SyncKey']
  597. self.user = dic['User']
  598. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  599. for keyVal in self.sync_key['List']])
  600. return dic['BaseResponse']['Ret'] == 0
  601. def status_notify(self):
  602. url = self.base_uri + '/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % self.pass_ticket
  603. self.base_request['Uin'] = int(self.base_request['Uin'])
  604. params = {
  605. 'BaseRequest': self.base_request,
  606. "Code": 3,
  607. "FromUserName": self.user['UserName'],
  608. "ToUserName": self.user['UserName'],
  609. "ClientMsgId": int(time.time())
  610. }
  611. r = self.session.post(url, data=json.dumps(params))
  612. r.encoding = 'utf-8'
  613. dic = json.loads(r.text)
  614. return dic['BaseResponse']['Ret'] == 0
  615. def test_sync_check(self):
  616. for host in ['webpush', 'webpush2']:
  617. self.sync_host = host
  618. retcode = self.sync_check()[0]
  619. if retcode == '0':
  620. return True
  621. return False
  622. def sync_check(self):
  623. params = {
  624. 'r': int(time.time()),
  625. 'sid': self.sid,
  626. 'uin': self.uin,
  627. 'skey': self.skey,
  628. 'deviceid': self.device_id,
  629. 'synckey': self.sync_key_str,
  630. '_': int(time.time()),
  631. }
  632. url = 'https://' + self.sync_host + '.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?' + urllib.urlencode(params)
  633. try:
  634. r = self.session.get(url)
  635. except (ConnectionError, ReadTimeout):
  636. return [-1, -1]
  637. r.encoding = 'utf-8'
  638. data = r.text
  639. pm = re.search(r'window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}', data)
  640. retcode = pm.group(1)
  641. selector = pm.group(2)
  642. return [retcode, selector]
  643. def sync(self):
  644. url = self.base_uri + '/webwxsync?sid=%s&skey=%s&lang=en_US&pass_ticket=%s' \
  645. % (self.sid, self.skey, self.pass_ticket)
  646. params = {
  647. 'BaseRequest': self.base_request,
  648. 'SyncKey': self.sync_key,
  649. 'rr': ~int(time.time())
  650. }
  651. try:
  652. r = self.session.post(url, data=json.dumps(params))
  653. except (ConnectionError, ReadTimeout):
  654. return None
  655. r.encoding = 'utf-8'
  656. dic = json.loads(r.text)
  657. if dic['BaseResponse']['Ret'] == 0:
  658. self.sync_key = dic['SyncKey']
  659. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  660. for keyVal in self.sync_key['List']])
  661. return dic
  662. def get_icon(self, uid):
  663. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s' % (uid, self.skey)
  664. r = self.session.get(url)
  665. data = r.content
  666. fn = 'img_' + uid + '.jpg'
  667. with open(fn, 'wb') as f:
  668. f.write(data)
  669. return fn
  670. def get_head_img(self, uid):
  671. url = self.base_uri + '/webwxgetheadimg?username=%s&skey=%s' % (uid, self.skey)
  672. r = self.session.get(url)
  673. data = r.content
  674. fn = 'img_' + uid + '.jpg'
  675. with open(fn, 'wb') as f:
  676. f.write(data)
  677. return fn
  678. def get_msg_img_url(self, msgid):
  679. return self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  680. def get_msg_img(self, msgid):
  681. url = self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  682. r = self.session.get(url)
  683. data = r.content
  684. fn = 'img_' + msgid + '.jpg'
  685. with open(fn, 'wb') as f:
  686. f.write(data)
  687. return fn
  688. def get_voice_url(self, msgid):
  689. return self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  690. def get_voice(self, msgid):
  691. url = self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  692. r = self.session.get(url)
  693. data = r.content
  694. fn = 'voice_' + msgid + '.mp3'
  695. with open(fn, 'wb') as f:
  696. f.write(data)
  697. return fn