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