wxbot.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  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. else:
  339. msg_content['type'] = 99
  340. msg_content['data'] = content
  341. if self.DEBUG:
  342. print ' %s[Unknown]' % msg_prefix
  343. return msg_content
  344. def handle_msg(self, r):
  345. """
  346. The inner function that processes raw WeChat messages.
  347. msg_type_id:
  348. 0 -> Init
  349. 1 -> Self
  350. 2 -> FileHelper
  351. 3 -> Group
  352. 4 -> Contact
  353. 5 -> Public
  354. 6 -> Special
  355. 99 -> Unknown
  356. :param r: The raw data of the messages.
  357. :return: None
  358. """
  359. for msg in r['AddMsgList']:
  360. msg_type_id = 99
  361. user = {'id': msg['FromUserName']}
  362. if msg['MsgType'] == 51: # init message
  363. msg_type_id = 0
  364. elif msg['FromUserName'] == self.user['UserName']: # Self
  365. msg_type_id = 1
  366. user['name'] = 'self'
  367. elif msg['ToUserName'] == 'filehelper': # File Helper
  368. msg_type_id = 2
  369. user['name'] = 'file_helper'
  370. elif msg['FromUserName'][:2] == '@@': # Group
  371. msg_type_id = 3
  372. user['name'] = self.get_prefer_name(self.get_account_name(user['id']))
  373. elif self.is_contact(msg['FromUserName']): # Contact
  374. msg_type_id = 4
  375. user['name'] = self.get_prefer_name(self.get_account_name(user['id']))
  376. elif self.is_public(msg['FromUserName']): # Public
  377. msg_type_id = 5
  378. user['name'] = self.get_prefer_name(self.get_account_name(user['id']))
  379. elif self.is_special(msg['FromUserName']): # Special
  380. msg_type_id = 6
  381. user['name'] = self.get_prefer_name(self.get_account_name(user['id']))
  382. if self.DEBUG and msg_type_id != 0:
  383. print '[MSG] %s:' % user['name']
  384. content = self.extract_msg_content(msg_type_id, msg)
  385. message = {'msg_type_id': msg_type_id,
  386. 'msg_id': msg['MsgId'],
  387. 'content': content,
  388. 'user': user}
  389. self.handle_msg_all(message)
  390. def schedule(self):
  391. """
  392. The function to do schedule works.
  393. This function will be called a lot of times.
  394. Please override this if needed.
  395. :return: None
  396. """
  397. pass
  398. def proc_msg(self):
  399. self.test_sync_check()
  400. while True:
  401. check_time = time.time()
  402. [retcode, selector] = self.sync_check()
  403. if retcode == '1100': # logout from mobile
  404. break
  405. elif retcode == '1101': # login web WeChat from other devide
  406. break
  407. elif retcode == '0':
  408. if selector == '2': # new message
  409. r = self.sync()
  410. if r is not None:
  411. self.handle_msg(r)
  412. elif selector == '7': # Play WeChat on mobile
  413. r = self.sync()
  414. if r is not None:
  415. self.handle_msg(r)
  416. elif selector == '0': # nothing
  417. pass
  418. else:
  419. pass
  420. self.schedule()
  421. check_time = time.time() - check_time
  422. if check_time < 0.5:
  423. time.sleep(0.5 - check_time)
  424. def send_msg_by_uid(self, word, dst='filehelper'):
  425. url = self.base_uri + '/webwxsendmsg?pass_ticket=%s' % self.pass_ticket
  426. msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
  427. if type(word) == 'str':
  428. word = word.decode('utf-8')
  429. params = {
  430. 'BaseRequest': self.base_request,
  431. 'Msg': {
  432. "Type": 1,
  433. "Content": word,
  434. "FromUserName": self.user['UserName'],
  435. "ToUserName": dst,
  436. "LocalID": msg_id,
  437. "ClientMsgId": msg_id
  438. }
  439. }
  440. headers = {'content-type': 'application/json; charset=UTF-8'}
  441. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  442. try:
  443. r = self.session.post(url, data=data, headers=headers)
  444. except (ConnectionError, ReadTimeout):
  445. return False
  446. dic = r.json()
  447. return dic['BaseResponse']['Ret'] == 0
  448. def send_msg(self, name, word, isfile=False):
  449. uid = self.get_user_id(name)
  450. if uid:
  451. if isfile:
  452. with open(word, 'r') as f:
  453. result = True
  454. for line in f.readlines():
  455. line = line.replace('\n', '')
  456. print '-> ' + name + ': ' + line
  457. if self.send_msg_by_uid(line, uid):
  458. pass
  459. else:
  460. result = False
  461. time.sleep(1)
  462. return result
  463. else:
  464. if self.send_msg_by_uid(word, uid):
  465. return True
  466. else:
  467. return False
  468. else:
  469. if self.DEBUG:
  470. print '[ERROR] This user does not exist .'
  471. return True
  472. @staticmethod
  473. def search_content(key, content, fmat='attr'):
  474. if fmat == 'attr':
  475. pm = re.search(key + '\s?=\s?"([^"<]+)"', content)
  476. if pm:
  477. return pm.group(1)
  478. elif fmat == 'xml':
  479. pm = re.search('<{0}>([^<]+)</{0}>'.format(key), content)
  480. if pm:
  481. return pm.group(1)
  482. return 'unknown'
  483. def run(self):
  484. self.get_uuid()
  485. self.gen_qr_code('qr.png')
  486. print '[INFO] Please use WeCaht to scan the QR code .'
  487. self.wait4login(1)
  488. print '[INFO] Please confirm to login .'
  489. self.wait4login(0)
  490. if self.login():
  491. print '[INFO] Web WeChat login succeed .'
  492. else:
  493. print '[ERROR] Web WeChat login failed .'
  494. return
  495. if self.init():
  496. print '[INFO] Web WeChat init succeed .'
  497. else:
  498. print '[INFO] Web WeChat init failed'
  499. return
  500. self.status_notify()
  501. self.get_contact()
  502. print '[INFO] Get %d contacts' % len(self.contact_list)
  503. print '[INFO] Start to process messages .'
  504. self.proc_msg()
  505. def get_uuid(self):
  506. url = 'https://login.weixin.qq.com/jslogin'
  507. params = {
  508. 'appid': 'wx782c26e4c19acffb',
  509. 'fun': 'new',
  510. 'lang': 'zh_CN',
  511. '_': int(time.time()) * 1000 + random.randint(1, 999),
  512. }
  513. r = self.session.get(url, params=params)
  514. r.encoding = 'utf-8'
  515. data = r.text
  516. regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
  517. pm = re.search(regx, data)
  518. if pm:
  519. code = pm.group(1)
  520. self.uuid = pm.group(2)
  521. return code == '200'
  522. return False
  523. def gen_qr_code(self, qr_file_path):
  524. string = 'https://login.weixin.qq.com/l/' + self.uuid
  525. qr = pyqrcode.create(string)
  526. if self.conf['qr'] == 'png':
  527. qr.png(qr_file_path)
  528. elif self.conf['qr'] == 'tty':
  529. print(qr.terminal(quiet_zone=1))
  530. def wait4login(self, tip):
  531. time.sleep(tip)
  532. url = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s' \
  533. % (tip, self.uuid, int(time.time()))
  534. r = self.session.get(url)
  535. r.encoding = 'utf-8'
  536. data = r.text
  537. param = re.search(r'window.code=(\d+);', data)
  538. code = param.group(1)
  539. if code == '201':
  540. return True
  541. elif code == '200':
  542. param = re.search(r'window.redirect_uri="(\S+?)";', data)
  543. redirect_uri = param.group(1) + '&fun=new'
  544. self.redirect_uri = redirect_uri
  545. self.base_uri = redirect_uri[:redirect_uri.rfind('/')]
  546. return True
  547. elif code == '408':
  548. print '[ERROR] WeChat login timeout .'
  549. else:
  550. print '[ERROR] WeChat login exception .'
  551. return False
  552. def login(self):
  553. r = self.session.get(self.redirect_uri)
  554. r.encoding = 'utf-8'
  555. data = r.text
  556. doc = xml.dom.minidom.parseString(data)
  557. root = doc.documentElement
  558. for node in root.childNodes:
  559. if node.nodeName == 'skey':
  560. self.skey = node.childNodes[0].data
  561. elif node.nodeName == 'wxsid':
  562. self.sid = node.childNodes[0].data
  563. elif node.nodeName == 'wxuin':
  564. self.uin = node.childNodes[0].data
  565. elif node.nodeName == 'pass_ticket':
  566. self.pass_ticket = node.childNodes[0].data
  567. if '' in (self.skey, self.sid, self.uin, self.pass_ticket):
  568. return False
  569. self.base_request = {
  570. 'Uin': self.uin,
  571. 'Sid': self.sid,
  572. 'Skey': self.skey,
  573. 'DeviceID': self.device_id,
  574. }
  575. return True
  576. def init(self):
  577. url = self.base_uri + '/webwxinit?r=%i&lang=en_US&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  578. params = {
  579. 'BaseRequest': self.base_request
  580. }
  581. r = self.session.post(url, data=json.dumps(params))
  582. r.encoding = 'utf-8'
  583. dic = json.loads(r.text)
  584. self.sync_key = dic['SyncKey']
  585. self.user = dic['User']
  586. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  587. for keyVal in self.sync_key['List']])
  588. return dic['BaseResponse']['Ret'] == 0
  589. def status_notify(self):
  590. url = self.base_uri + '/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % self.pass_ticket
  591. self.base_request['Uin'] = int(self.base_request['Uin'])
  592. params = {
  593. 'BaseRequest': self.base_request,
  594. "Code": 3,
  595. "FromUserName": self.user['UserName'],
  596. "ToUserName": self.user['UserName'],
  597. "ClientMsgId": int(time.time())
  598. }
  599. r = self.session.post(url, data=json.dumps(params))
  600. r.encoding = 'utf-8'
  601. dic = json.loads(r.text)
  602. return dic['BaseResponse']['Ret'] == 0
  603. def test_sync_check(self):
  604. for host in ['webpush', 'webpush2']:
  605. self.sync_host = host
  606. retcode = self.sync_check()[0]
  607. if retcode == '0':
  608. return True
  609. return False
  610. def sync_check(self):
  611. params = {
  612. 'r': int(time.time()),
  613. 'sid': self.sid,
  614. 'uin': self.uin,
  615. 'skey': self.skey,
  616. 'deviceid': self.device_id,
  617. 'synckey': self.sync_key_str,
  618. '_': int(time.time()),
  619. }
  620. url = 'https://' + self.sync_host + '.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?' + urllib.urlencode(params)
  621. try:
  622. r = self.session.get(url)
  623. except (ConnectionError, ReadTimeout):
  624. return [-1, -1]
  625. r.encoding = 'utf-8'
  626. data = r.text
  627. pm = re.search(r'window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}', data)
  628. retcode = pm.group(1)
  629. selector = pm.group(2)
  630. return [retcode, selector]
  631. def sync(self):
  632. url = self.base_uri + '/webwxsync?sid=%s&skey=%s&lang=en_US&pass_ticket=%s' \
  633. % (self.sid, self.skey, self.pass_ticket)
  634. params = {
  635. 'BaseRequest': self.base_request,
  636. 'SyncKey': self.sync_key,
  637. 'rr': ~int(time.time())
  638. }
  639. try:
  640. r = self.session.post(url, data=json.dumps(params))
  641. except (ConnectionError, ReadTimeout):
  642. return None
  643. r.encoding = 'utf-8'
  644. dic = json.loads(r.text)
  645. if dic['BaseResponse']['Ret'] == 0:
  646. self.sync_key = dic['SyncKey']
  647. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  648. for keyVal in self.sync_key['List']])
  649. return dic
  650. def get_icon(self, uid):
  651. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s' % (uid, self.skey)
  652. r = self.session.get(url)
  653. data = r.content
  654. fn = 'img_' + uid + '.jpg'
  655. with open(fn, 'wb') as f:
  656. f.write(data)
  657. return fn
  658. def get_head_img(self, uid):
  659. url = self.base_uri + '/webwxgetheadimg?username=%s&skey=%s' % (uid, self.skey)
  660. r = self.session.get(url)
  661. data = r.content
  662. fn = 'img_' + uid + '.jpg'
  663. with open(fn, 'wb') as f:
  664. f.write(data)
  665. return fn
  666. def get_msg_img_url(self, msgid):
  667. return self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  668. def get_msg_img(self, msgid):
  669. url = self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  670. r = self.session.get(url)
  671. data = r.content
  672. fn = 'img_' + msgid + '.jpg'
  673. with open(fn, 'wb') as f:
  674. f.write(data)
  675. return fn
  676. def get_voice_url(self, msgid):
  677. return self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  678. def get_voice(self, msgid):
  679. url = self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  680. r = self.session.get(url)
  681. data = r.content
  682. fn = 'voice_' + msgid + '.mp3'
  683. with open(fn, 'wb') as f:
  684. f.write(data)
  685. return fn