wxbot.py 29 KB

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