wxbot.py 28 KB

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