wxbot.py 27 KB

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