wxbot.py 29 KB

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