wxbot.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3. import os
  4. import sys
  5. import webbrowser
  6. import pyqrcode
  7. import requests
  8. import json
  9. import xml.dom.minidom
  10. import urllib
  11. import time
  12. import re
  13. import random
  14. from traceback import format_exc
  15. from requests.exceptions import ConnectionError, ReadTimeout
  16. import HTMLParser
  17. UNKONWN = 'unkonwn'
  18. SUCCESS = '200'
  19. SCANED = '201'
  20. TIMEOUT = '408'
  21. def show_image(file_path):
  22. """
  23. 跨平台显示图片文件
  24. :param file_path: 图片文件路径
  25. """
  26. if sys.version_info >= (3, 3):
  27. from shlex import quote
  28. else:
  29. from pipes import quote
  30. if sys.platform == "darwin":
  31. command = "open -a /Applications/Preview.app %s&" % quote(file_path)
  32. os.system(command)
  33. else:
  34. webbrowser.open(file_path)
  35. class SafeSession(requests.Session):
  36. def request(self, *args, **kwargs):
  37. for i in range(3):
  38. try:
  39. return super(SafeSession, self).request(*args, **kwargs)
  40. except:
  41. pass
  42. return super(SafeSession, self).request(*args, **kwargs)
  43. class WXBot:
  44. """WXBot功能类"""
  45. def __init__(self):
  46. self.DEBUG = False
  47. self.uuid = ''
  48. self.base_uri = ''
  49. self.redirect_uri = ''
  50. self.uin = ''
  51. self.sid = ''
  52. self.skey = ''
  53. self.pass_ticket = ''
  54. self.device_id = 'e' + repr(random.random())[2:17]
  55. self.base_request = {}
  56. self.sync_key_str = ''
  57. self.sync_key = []
  58. self.sync_host = ''
  59. self.session = SafeSession()
  60. self.session.headers.update({'User-Agent': 'Mozilla/5.0 (X11; Linux i686; U;) Gecko/20070322 Kazehakase/0.4.5'})
  61. self.conf = {'qr': 'png'}
  62. self.my_account = {} # 当前账户
  63. # 所有相关账号: 联系人, 公众号, 群组, 特殊账号
  64. self.member_list = []
  65. # 所有群组的成员, {'group_id1': [member1, member2, ...], ...}
  66. self.group_members = {}
  67. # 所有账户, {'group_member':{'id':{'type':'group_member', 'info':{}}, ...}, 'normal_member':{'id':{}, ...}}
  68. self.account_info = {'group_member': {}, 'normal_member': {}}
  69. self.contact_list = [] # 联系人列表
  70. self.public_list = [] # 公众账号列表
  71. self.group_list = [] # 群聊列表
  72. self.special_list = [] # 特殊账号列表
  73. self.encry_chat_room_id_list = [] # 存储群聊的EncryChatRoomId,获取群内成员头像时需要用到
  74. @staticmethod
  75. def to_unicode(string, encoding='utf-8'):
  76. """
  77. 将字符串转换为Unicode
  78. :param string: 待转换字符串
  79. :param encoding: 字符串解码方式
  80. :return: 转换后的Unicode字符串
  81. """
  82. if isinstance(string, str):
  83. return string.decode(encoding)
  84. elif isinstance(string, unicode):
  85. return string
  86. else:
  87. raise Exception('Unknown Type')
  88. def get_contact(self):
  89. """获取当前账户的所有相关账号(包括联系人、公众号、群聊、特殊账号)"""
  90. url = self.base_uri + '/webwxgetcontact?pass_ticket=%s&skey=%s&r=%s' \
  91. % (self.pass_ticket, self.skey, int(time.time()))
  92. r = self.session.post(url, data='{}')
  93. r.encoding = 'utf-8'
  94. if self.DEBUG:
  95. with open('contacts.json', 'w') as f:
  96. f.write(r.text.encode('utf-8'))
  97. dic = json.loads(r.text)
  98. self.member_list = dic['MemberList']
  99. special_users = ['newsapp', 'fmessage', 'filehelper', 'weibo', 'qqmail',
  100. 'fmessage', 'tmessage', 'qmessage', 'qqsync', 'floatbottle',
  101. 'lbsapp', 'shakeapp', 'medianote', 'qqfriend', 'readerapp',
  102. 'blogapp', 'facebookapp', 'masssendapp', 'meishiapp',
  103. 'feedsapp', 'voip', 'blogappweixin', 'weixin', 'brandsessionholder',
  104. 'weixinreminder', 'wxid_novlwrv3lqwv11', 'gh_22b87fa7cb3c',
  105. 'officialaccounts', 'notification_messages', 'wxid_novlwrv3lqwv11',
  106. 'gh_22b87fa7cb3c', 'wxitil', 'userexperience_alarm', 'notification_messages']
  107. self.contact_list = []
  108. self.public_list = []
  109. self.special_list = []
  110. self.group_list = []
  111. for contact in self.member_list:
  112. if contact['VerifyFlag'] & 8 != 0: # 公众号
  113. self.public_list.append(contact)
  114. self.account_info['normal_member'][contact['UserName']] = {'type': 'public', 'info': contact}
  115. elif contact['UserName'] in special_users: # 特殊账户
  116. self.special_list.append(contact)
  117. self.account_info['normal_member'][contact['UserName']] = {'type': 'special', 'info': contact}
  118. elif contact['UserName'].find('@@') != -1: # 群聊
  119. self.group_list.append(contact)
  120. self.account_info['normal_member'][contact['UserName']] = {'type': 'group', 'info': contact}
  121. elif contact['UserName'] == self.my_account['UserName']: # 自己
  122. self.account_info['normal_member'][contact['UserName']] = {'type': 'self', 'info': contact}
  123. else:
  124. self.contact_list.append(contact)
  125. self.account_info['normal_member'][contact['UserName']] = {'type': 'contact', 'info': contact}
  126. self.batch_get_group_members()
  127. for group in self.group_members:
  128. for member in self.group_members[group]:
  129. if member['UserName'] not in self.account_info:
  130. self.account_info['group_member'][member['UserName']] = \
  131. {'type': 'group_member', 'info': member, 'group': group}
  132. if self.DEBUG:
  133. with open('contact_list.json', 'w') as f:
  134. f.write(json.dumps(self.contact_list))
  135. with open('special_list.json', 'w') as f:
  136. f.write(json.dumps(self.special_list))
  137. with open('group_list.json', 'w') as f:
  138. f.write(json.dumps(self.group_list))
  139. with open('public_list.json', 'w') as f:
  140. f.write(json.dumps(self.public_list))
  141. with open('member_list.json', 'w') as f:
  142. f.write(json.dumps(self.member_list))
  143. with open('group_users.json', 'w') as f:
  144. f.write(json.dumps(self.group_members))
  145. with open('account_info.json', 'w') as f:
  146. f.write(json.dumps(self.account_info))
  147. return True
  148. def batch_get_group_members(self):
  149. """批量获取所有群聊成员信息"""
  150. url = self.base_uri + '/webwxbatchgetcontact?type=ex&r=%s&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  151. params = {
  152. 'BaseRequest': self.base_request,
  153. "Count": len(self.group_list),
  154. "List": [{"UserName": group['UserName'], "EncryChatRoomId": ""} for group in self.group_list]
  155. }
  156. r = self.session.post(url, data=json.dumps(params))
  157. r.encoding = 'utf-8'
  158. dic = json.loads(r.text)
  159. group_members = {}
  160. encry_chat_room_id = {}
  161. for group in dic['ContactList']:
  162. gid = group['UserName']
  163. members = group['MemberList']
  164. group_members[gid] = members
  165. encry_chat_room_id[gid] = group['EncryChatRoomId']
  166. self.group_members = group_members
  167. self.encry_chat_room_id_list = encry_chat_room_id
  168. def get_group_member_name(self, gid, uid):
  169. """
  170. 获取群聊中指定成员的名称信息
  171. :param gid: 群id
  172. :param uid: 群聊成员id
  173. :return: 名称信息,类似 {"display_name": "test_user", "nickname": "test", "remark_name": "for_test" }
  174. """
  175. if gid not in self.group_members:
  176. return None
  177. group = self.group_members[gid]
  178. for member in group:
  179. if member['UserName'] == uid:
  180. names = {}
  181. if 'RemarkName' in member and member['RemarkName']:
  182. names['remark_name'] = member['RemarkName']
  183. if 'NickName' in member and member['NickName']:
  184. names['nickname'] = member['NickName']
  185. if 'DisplayName' in member and member['DisplayName']:
  186. names['display_name'] = member['DisplayName']
  187. return names
  188. return None
  189. def get_contact_info(self, uid):
  190. if uid in self.account_info['normal_member']:
  191. return self.account_info['normal_member'][uid]
  192. else:
  193. return None
  194. def get_group_member_info(self, uid):
  195. if uid in self.account_info['group_member']:
  196. return self.account_info['group_member'][uid]
  197. else:
  198. return None
  199. def get_contact_name(self, uid):
  200. info = self.get_contact_info(uid)
  201. if info is None:
  202. return None
  203. info = info['info']
  204. name = {}
  205. if 'RemarkName' in info and info['RemarkName']:
  206. name['remark_name'] = info['RemarkName']
  207. if 'NickName' in info and info['NickName']:
  208. name['nickname'] = info['NickName']
  209. if 'DisplayName' in info and info['DisplayName']:
  210. name['display_name'] = info['DisplayName']
  211. if len(name) == 0:
  212. return None
  213. else:
  214. return name
  215. @staticmethod
  216. def get_contact_prefer_name(name):
  217. if name is None:
  218. return None
  219. if 'remark_name' in name:
  220. return name['remark_name']
  221. if 'nickname' in name:
  222. return name['nickname']
  223. if 'display_name' in name:
  224. return name['display_name']
  225. return None
  226. @staticmethod
  227. def get_group_member_prefer_name(name):
  228. if name is None:
  229. return None
  230. if 'remark_name' in name:
  231. return name['remark_name']
  232. if 'display_name' in name:
  233. return name['display_name']
  234. if 'nickname' in name:
  235. return name['nickname']
  236. return None
  237. def get_user_type(self, wx_user_id):
  238. """
  239. 获取特定账号与自己的关系
  240. :param wx_user_id: 账号id:
  241. :return: 与当前账号的关系
  242. """
  243. for account in self.contact_list:
  244. if wx_user_id == account['UserName']:
  245. return 'contact'
  246. for account in self.public_list:
  247. if wx_user_id == account['UserName']:
  248. return 'public'
  249. for account in self.special_list:
  250. if wx_user_id == account['UserName']:
  251. return 'special'
  252. for account in self.group_list:
  253. if wx_user_id == account['UserName']:
  254. return 'group'
  255. for group in self.group_members:
  256. for member in self.group_members[group]:
  257. if member['UserName'] == wx_user_id:
  258. return 'group_member'
  259. return 'unknown'
  260. def is_contact(self, uid):
  261. for account in self.contact_list:
  262. if uid == account['UserName']:
  263. return True
  264. return False
  265. def is_public(self, uid):
  266. for account in self.public_list:
  267. if uid == account['UserName']:
  268. return True
  269. return False
  270. def is_special(self, uid):
  271. for account in self.special_list:
  272. if uid == account['UserName']:
  273. return True
  274. return False
  275. def handle_msg_all(self, msg):
  276. """
  277. 处理所有消息,请子类化后覆盖此函数
  278. msg:
  279. msg_id -> 消息id
  280. msg_type_id -> 消息类型id
  281. user -> 发送消息的账号id
  282. content -> 消息内容
  283. :param msg: 收到的消息
  284. """
  285. pass
  286. @staticmethod
  287. def proc_at_info(msg):
  288. if not msg:
  289. return '', []
  290. segs = msg.split(u'\u2005')
  291. str_msg_all = ''
  292. str_msg = ''
  293. infos = []
  294. if len(segs) > 1:
  295. for i in range(0, len(segs)-1):
  296. segs[i] += u'\u2005'
  297. pm = re.search(u'@.*\u2005', segs[i]).group()
  298. if pm:
  299. name = pm[1:-1]
  300. string = segs[i].replace(pm, '')
  301. str_msg_all += string + '@' + name + ' '
  302. str_msg += string
  303. if string:
  304. infos.append({'type': 'str', 'value': string})
  305. infos.append({'type': 'at', 'value': name})
  306. else:
  307. infos.append({'type': 'str', 'value': segs[i]})
  308. str_msg_all += segs[i]
  309. str_msg += segs[i]
  310. str_msg_all += segs[-1]
  311. str_msg += segs[-1]
  312. infos.append({'type': 'str', 'value': segs[-1]})
  313. else:
  314. infos.append({'type': 'str', 'value': segs[-1]})
  315. str_msg_all = msg
  316. str_msg = msg
  317. return str_msg_all.replace(u'\u2005', ''), str_msg.replace(u'\u2005', ''), infos
  318. def extract_msg_content(self, msg_type_id, msg):
  319. """
  320. content_type_id:
  321. 0 -> Text
  322. 1 -> Location
  323. 3 -> Image
  324. 4 -> Voice
  325. 5 -> Recommend
  326. 6 -> Animation
  327. 7 -> Share
  328. 8 -> Video
  329. 9 -> VideoCall
  330. 10 -> Redraw
  331. 11 -> Empty
  332. 99 -> Unknown
  333. :param msg_type_id: 消息类型id
  334. :param msg: 消息结构体
  335. :return: 解析的消息
  336. """
  337. mtype = msg['MsgType']
  338. content = HTMLParser.HTMLParser().unescape(msg['Content'])
  339. msg_id = msg['MsgId']
  340. msg_content = {}
  341. if msg_type_id == 0:
  342. return {'type': 11, 'data': ''}
  343. elif msg_type_id == 2: # File Helper
  344. return {'type': 0, 'data': content.replace('<br/>', '\n')}
  345. elif msg_type_id == 3: # 群聊
  346. sp = content.find('<br/>')
  347. uid = content[:sp]
  348. content = content[sp:]
  349. content = content.replace('<br/>', '')
  350. uid = uid[:-1]
  351. name = self.get_contact_prefer_name(self.get_contact_name(uid))
  352. if not name:
  353. name = self.get_group_member_prefer_name(self.get_group_member_name(uid, msg['FromUserName']))
  354. if not name:
  355. name = 'unknown'
  356. msg_content['user'] = {'id': uid, 'name': name}
  357. else: # Self, Contact, Special, Public, Unknown
  358. pass
  359. msg_prefix = (msg_content['user']['name'] + ':') if 'user' in msg_content else ''
  360. if mtype == 1:
  361. if content.find('http://weixin.qq.com/cgi-bin/redirectforward?args=') != -1:
  362. r = self.session.get(content)
  363. r.encoding = 'gbk'
  364. data = r.text
  365. pos = self.search_content('title', data, 'xml')
  366. msg_content['type'] = 1
  367. msg_content['data'] = pos
  368. msg_content['detail'] = data
  369. if self.DEBUG:
  370. print ' %s[Location] %s ' % (msg_prefix, pos)
  371. else:
  372. msg_content['type'] = 0
  373. if msg_type_id == 3 or (msg_type_id == 1 and msg['ToUserName'][:2] == '@@'): # Group text message
  374. msg_infos = self.proc_at_info(content)
  375. str_msg_all = msg_infos[0]
  376. str_msg = msg_infos[1]
  377. detail = msg_infos[2]
  378. msg_content['data'] = str_msg_all
  379. msg_content['detail'] = detail
  380. msg_content['desc'] = str_msg
  381. else:
  382. msg_content['data'] = content
  383. if self.DEBUG:
  384. try:
  385. print ' %s[Text] %s' % (msg_prefix, msg_content['data'])
  386. except UnicodeEncodeError:
  387. print ' %s[Text] (illegal text).' % msg_prefix
  388. elif mtype == 3:
  389. msg_content['type'] = 3
  390. msg_content['data'] = self.get_msg_img_url(msg_id)
  391. if self.DEBUG:
  392. image = self.get_msg_img(msg_id)
  393. print ' %s[Image] %s' % (msg_prefix, image)
  394. elif mtype == 34:
  395. msg_content['type'] = 4
  396. msg_content['data'] = self.get_voice_url(msg_id)
  397. if self.DEBUG:
  398. voice = self.get_voice(msg_id)
  399. print ' %s[Voice] %s' % (msg_prefix, voice)
  400. elif mtype == 42:
  401. msg_content['type'] = 5
  402. info = msg['RecommendInfo']
  403. msg_content['data'] = {'nickname': info['NickName'],
  404. 'alias': info['Alias'],
  405. 'province': info['Province'],
  406. 'city': info['City'],
  407. 'gender': ['unknown', 'male', 'female'][info['Sex']]}
  408. if self.DEBUG:
  409. print ' %s[Recommend]' % msg_prefix
  410. print ' -----------------------------'
  411. print ' | NickName: %s' % info['NickName']
  412. print ' | Alias: %s' % info['Alias']
  413. print ' | Local: %s %s' % (info['Province'], info['City'])
  414. print ' | Gender: %s' % ['unknown', 'male', 'female'][info['Sex']]
  415. print ' -----------------------------'
  416. elif mtype == 47:
  417. msg_content['type'] = 6
  418. msg_content['data'] = self.search_content('cdnurl', content)
  419. if self.DEBUG:
  420. print ' %s[Animation] %s' % (msg_prefix, msg_content['data'])
  421. elif mtype == 49:
  422. msg_content['type'] = 7
  423. if msg['AppMsgType'] == 3:
  424. app_msg_type = 'music'
  425. elif msg['AppMsgType'] == 5:
  426. app_msg_type = 'link'
  427. elif msg['AppMsgType'] == 7:
  428. app_msg_type = 'weibo'
  429. else:
  430. app_msg_type = 'unknown'
  431. msg_content['data'] = {'type': app_msg_type,
  432. 'title': msg['FileName'],
  433. 'desc': self.search_content('des', content, 'xml'),
  434. 'url': msg['Url'],
  435. 'from': self.search_content('appname', content, 'xml')}
  436. if self.DEBUG:
  437. print ' %s[Share] %s' % (msg_prefix, app_msg_type)
  438. print ' --------------------------'
  439. print ' | title: %s' % msg['FileName']
  440. print ' | desc: %s' % self.search_content('des', content, 'xml')
  441. print ' | link: %s' % msg['Url']
  442. print ' | from: %s' % self.search_content('appname', content, 'xml')
  443. print ' --------------------------'
  444. elif mtype == 62:
  445. msg_content['type'] = 8
  446. msg_content['data'] = content
  447. if self.DEBUG:
  448. print ' %s[Video] Please check on mobiles' % msg_prefix
  449. elif mtype == 53:
  450. msg_content['type'] = 9
  451. msg_content['data'] = content
  452. if self.DEBUG:
  453. print ' %s[Video Call]' % msg_prefix
  454. elif mtype == 10002:
  455. msg_content['type'] = 10
  456. msg_content['data'] = content
  457. if self.DEBUG:
  458. print ' %s[Redraw]' % msg_prefix
  459. elif mtype == 10000: # unknown, maybe red packet, or group invite
  460. msg_content['type'] = 12
  461. msg_content['data'] = msg['Content']
  462. if self.DEBUG:
  463. print ' [Unknown]'
  464. else:
  465. msg_content['type'] = 99
  466. msg_content['data'] = content
  467. if self.DEBUG:
  468. print ' %s[Unknown]' % msg_prefix
  469. return msg_content
  470. def handle_msg(self, r):
  471. """
  472. 处理原始微信消息的内部函数
  473. msg_type_id:
  474. 0 -> Init
  475. 1 -> Self
  476. 2 -> FileHelper
  477. 3 -> Group
  478. 4 -> Contact
  479. 5 -> Public
  480. 6 -> Special
  481. 99 -> Unknown
  482. :param r: 原始微信消息
  483. """
  484. for msg in r['AddMsgList']:
  485. user = {'id': msg['FromUserName'], 'name': 'unknown'}
  486. if msg['MsgType'] == 51: # init message
  487. msg_type_id = 0
  488. user['name'] = 'system'
  489. elif msg['FromUserName'] == self.my_account['UserName']: # Self
  490. msg_type_id = 1
  491. user['name'] = 'self'
  492. elif msg['ToUserName'] == 'filehelper': # File Helper
  493. msg_type_id = 2
  494. user['name'] = 'file_helper'
  495. elif msg['FromUserName'][:2] == '@@': # Group
  496. msg_type_id = 3
  497. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  498. elif self.is_contact(msg['FromUserName']): # Contact
  499. msg_type_id = 4
  500. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  501. elif self.is_public(msg['FromUserName']): # Public
  502. msg_type_id = 5
  503. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  504. elif self.is_special(msg['FromUserName']): # Special
  505. msg_type_id = 6
  506. user['name'] = self.get_contact_prefer_name(self.get_contact_name(user['id']))
  507. else:
  508. msg_type_id = 99
  509. user['name'] = 'unknown'
  510. if not user['name']:
  511. user['name'] = 'unknown'
  512. user['name'] = HTMLParser.HTMLParser().unescape(user['name'])
  513. if self.DEBUG and msg_type_id != 0:
  514. print '[MSG] %s:' % user['name']
  515. content = self.extract_msg_content(msg_type_id, msg)
  516. message = {'msg_type_id': msg_type_id,
  517. 'msg_id': msg['MsgId'],
  518. 'content': content,
  519. 'to_user_id': msg['ToUserName'],
  520. 'user': user}
  521. self.handle_msg_all(message)
  522. def schedule(self):
  523. """
  524. 做任务型事情的函数,如果需要,可以在子类中覆盖此函数
  525. 此函数在处理消息的间隙被调用,请不要长时间阻塞此函数
  526. """
  527. pass
  528. def proc_msg(self):
  529. self.test_sync_check()
  530. while True:
  531. check_time = time.time()
  532. try:
  533. [retcode, selector] = self.sync_check()
  534. # print '[DEBUG] sync_check:', retcode, selector
  535. if retcode == '1100': # 从微信客户端上登出
  536. break
  537. elif retcode == '1101': # 从其它设备上登了网页微信
  538. break
  539. elif retcode == '0':
  540. if selector == '2': # 有新消息
  541. r = self.sync()
  542. if r is not None:
  543. self.handle_msg(r)
  544. elif selector == '3': # 未知
  545. r = self.sync()
  546. if r is not None:
  547. self.handle_msg(r)
  548. elif selector == '6': # 可能是红包
  549. r = self.sync()
  550. if r is not None:
  551. self.handle_msg(r)
  552. elif selector == '7': # 在手机上操作了微信
  553. r = self.sync()
  554. if r is not None:
  555. self.handle_msg(r)
  556. elif selector == '0': # 无事件
  557. pass
  558. else:
  559. print '[DEBUG] sync_check:', retcode, selector
  560. r = self.sync()
  561. if r is not None:
  562. self.handle_msg(r)
  563. else:
  564. print '[DEBUG] sync_check:', retcode, selector
  565. self.schedule()
  566. except:
  567. print '[ERROR] Except in proc_msg'
  568. print format_exc()
  569. check_time = time.time() - check_time
  570. if check_time < 0.8:
  571. time.sleep(1 - check_time)
  572. def send_msg_by_uid(self, word, dst='filehelper'):
  573. url = self.base_uri + '/webwxsendmsg?pass_ticket=%s' % self.pass_ticket
  574. msg_id = str(int(time.time() * 1000)) + str(random.random())[:5].replace('.', '')
  575. word = self.to_unicode(word)
  576. params = {
  577. 'BaseRequest': self.base_request,
  578. 'Msg': {
  579. "Type": 1,
  580. "Content": word,
  581. "FromUserName": self.my_account['UserName'],
  582. "ToUserName": dst,
  583. "LocalID": msg_id,
  584. "ClientMsgId": msg_id
  585. }
  586. }
  587. headers = {'content-type': 'application/json; charset=UTF-8'}
  588. data = json.dumps(params, ensure_ascii=False).encode('utf8')
  589. try:
  590. r = self.session.post(url, data=data, headers=headers)
  591. except (ConnectionError, ReadTimeout):
  592. return False
  593. dic = r.json()
  594. return dic['BaseResponse']['Ret'] == 0
  595. def get_user_id(self, name):
  596. if name == '':
  597. return None
  598. name = self.to_unicode(name)
  599. for contact in self.contact_list:
  600. if 'RemarkName' in contact and contact['RemarkName'] == name:
  601. return contact['UserName']
  602. elif 'NickName' in contact and contact['NickName'] == name:
  603. return contact['UserName']
  604. elif 'DisplayName' in contact and contact['DisplayName'] == name:
  605. return contact['UserName']
  606. for group in self.group_list:
  607. if 'RemarkName' in group and group['RemarkName'] == name:
  608. return group['UserName']
  609. if 'NickName' in group and group['NickName'] == name:
  610. return group['UserName']
  611. if 'DisplayName' in group and group['DisplayName'] == name:
  612. return group['UserName']
  613. return ''
  614. def send_msg(self, name, word, isfile=False):
  615. uid = self.get_user_id(name)
  616. if uid is not None:
  617. if isfile:
  618. with open(word, 'r') as f:
  619. result = True
  620. for line in f.readlines():
  621. line = line.replace('\n', '')
  622. print '-> ' + name + ': ' + line
  623. if self.send_msg_by_uid(line, uid):
  624. pass
  625. else:
  626. result = False
  627. time.sleep(1)
  628. return result
  629. else:
  630. word = self.to_unicode(word)
  631. if self.send_msg_by_uid(word, uid):
  632. return True
  633. else:
  634. return False
  635. else:
  636. if self.DEBUG:
  637. print '[ERROR] This user does not exist .'
  638. return True
  639. @staticmethod
  640. def search_content(key, content, fmat='attr'):
  641. if fmat == 'attr':
  642. pm = re.search(key + '\s?=\s?"([^"<]+)"', content)
  643. if pm:
  644. return pm.group(1)
  645. elif fmat == 'xml':
  646. pm = re.search('<{0}>([^<]+)</{0}>'.format(key), content)
  647. if pm:
  648. return pm.group(1)
  649. return 'unknown'
  650. def run(self):
  651. self.get_uuid()
  652. self.gen_qr_code('qr.png')
  653. print '[INFO] Please use WeChat to scan the QR code .'
  654. result = self.wait4login()
  655. if result != SUCCESS:
  656. print '[ERROR] Web WeChat login failed. failed code=%s'%(result, )
  657. return
  658. if self.login():
  659. print '[INFO] Web WeChat login succeed .'
  660. else:
  661. print '[ERROR] Web WeChat login failed .'
  662. return
  663. if self.init():
  664. print '[INFO] Web WeChat init succeed .'
  665. else:
  666. print '[INFO] Web WeChat init failed'
  667. return
  668. self.status_notify()
  669. self.get_contact()
  670. print '[INFO] Get %d contacts' % len(self.contact_list)
  671. print '[INFO] Start to process messages .'
  672. self.proc_msg()
  673. def get_uuid(self):
  674. url = 'https://login.weixin.qq.com/jslogin'
  675. params = {
  676. 'appid': 'wx782c26e4c19acffb',
  677. 'fun': 'new',
  678. 'lang': 'zh_CN',
  679. '_': int(time.time()) * 1000 + random.randint(1, 999),
  680. }
  681. r = self.session.get(url, params=params)
  682. r.encoding = 'utf-8'
  683. data = r.text
  684. regx = r'window.QRLogin.code = (\d+); window.QRLogin.uuid = "(\S+?)"'
  685. pm = re.search(regx, data)
  686. if pm:
  687. code = pm.group(1)
  688. self.uuid = pm.group(2)
  689. return code == '200'
  690. return False
  691. def gen_qr_code(self, qr_file_path):
  692. string = 'https://login.weixin.qq.com/l/' + self.uuid
  693. qr = pyqrcode.create(string)
  694. if self.conf['qr'] == 'png':
  695. qr.png(qr_file_path, scale=8)
  696. show_image(qr_file_path)
  697. # img = Image.open(qr_file_path)
  698. # img.show()
  699. elif self.conf['qr'] == 'tty':
  700. print(qr.terminal(quiet_zone=1))
  701. def do_request(self, url):
  702. r = self.session.get(url)
  703. r.encoding = 'utf-8'
  704. data = r.text
  705. param = re.search(r'window.code=(\d+);', data)
  706. code = param.group(1)
  707. return code, data
  708. def wait4login(self):
  709. """
  710. http comet:
  711. tip=1, 等待用户扫描二维码,
  712. 201: scaned
  713. 408: timeout
  714. tip=0, 等待用户确认登录,
  715. 200: confirmed
  716. """
  717. LOGIN_TEMPLATE = 'https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login?tip=%s&uuid=%s&_=%s'
  718. tip = 1
  719. try_later_secs = 1
  720. MAX_RETRY_TIMES = 10
  721. code = UNKONWN
  722. retry_time = MAX_RETRY_TIMES
  723. while retry_time > 0:
  724. url = LOGIN_TEMPLATE % (tip, self.uuid, int(time.time()))
  725. code, data = self.do_request(url)
  726. if code == SCANED:
  727. print '[INFO] Please confirm to login .'
  728. tip = 0
  729. elif code == SUCCESS: # 确认登录成功
  730. param = re.search(r'window.redirect_uri="(\S+?)";', data)
  731. redirect_uri = param.group(1) + '&fun=new'
  732. self.redirect_uri = redirect_uri
  733. self.base_uri = redirect_uri[:redirect_uri.rfind('/')]
  734. return code
  735. elif code == TIMEOUT:
  736. print '[ERROR] WeChat login timeout. retry in %s secs later...'%(try_later_secs, )
  737. tip = 1 # 重置
  738. retry_time -= 1
  739. time.sleep(try_later_secs)
  740. else:
  741. print ('[ERROR] WeChat login exception return_code=%s. retry in %s secs later...' %
  742. (code, try_later_secs))
  743. tip = 1
  744. retry_time -= 1
  745. time.sleep(try_later_secs)
  746. return code
  747. def login(self):
  748. if len(self.redirect_uri) < 4:
  749. print '[ERROR] Login failed due to network problem, please try again.'
  750. return False
  751. r = self.session.get(self.redirect_uri)
  752. r.encoding = 'utf-8'
  753. data = r.text
  754. doc = xml.dom.minidom.parseString(data)
  755. root = doc.documentElement
  756. for node in root.childNodes:
  757. if node.nodeName == 'skey':
  758. self.skey = node.childNodes[0].data
  759. elif node.nodeName == 'wxsid':
  760. self.sid = node.childNodes[0].data
  761. elif node.nodeName == 'wxuin':
  762. self.uin = node.childNodes[0].data
  763. elif node.nodeName == 'pass_ticket':
  764. self.pass_ticket = node.childNodes[0].data
  765. if '' in (self.skey, self.sid, self.uin, self.pass_ticket):
  766. return False
  767. self.base_request = {
  768. 'Uin': self.uin,
  769. 'Sid': self.sid,
  770. 'Skey': self.skey,
  771. 'DeviceID': self.device_id,
  772. }
  773. return True
  774. def init(self):
  775. url = self.base_uri + '/webwxinit?r=%i&lang=en_US&pass_ticket=%s' % (int(time.time()), self.pass_ticket)
  776. params = {
  777. 'BaseRequest': self.base_request
  778. }
  779. r = self.session.post(url, data=json.dumps(params))
  780. r.encoding = 'utf-8'
  781. dic = json.loads(r.text)
  782. self.sync_key = dic['SyncKey']
  783. self.my_account = dic['User']
  784. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  785. for keyVal in self.sync_key['List']])
  786. return dic['BaseResponse']['Ret'] == 0
  787. def status_notify(self):
  788. url = self.base_uri + '/webwxstatusnotify?lang=zh_CN&pass_ticket=%s' % self.pass_ticket
  789. self.base_request['Uin'] = int(self.base_request['Uin'])
  790. params = {
  791. 'BaseRequest': self.base_request,
  792. "Code": 3,
  793. "FromUserName": self.my_account['UserName'],
  794. "ToUserName": self.my_account['UserName'],
  795. "ClientMsgId": int(time.time())
  796. }
  797. r = self.session.post(url, data=json.dumps(params))
  798. r.encoding = 'utf-8'
  799. dic = json.loads(r.text)
  800. return dic['BaseResponse']['Ret'] == 0
  801. def test_sync_check(self):
  802. for host in ['webpush', 'webpush2']:
  803. self.sync_host = host
  804. retcode = self.sync_check()[0]
  805. if retcode == '0':
  806. return True
  807. return False
  808. def sync_check(self):
  809. params = {
  810. 'r': int(time.time()),
  811. 'sid': self.sid,
  812. 'uin': self.uin,
  813. 'skey': self.skey,
  814. 'deviceid': self.device_id,
  815. 'synckey': self.sync_key_str,
  816. '_': int(time.time()),
  817. }
  818. url = 'https://' + self.sync_host + '.weixin.qq.com/cgi-bin/mmwebwx-bin/synccheck?' + urllib.urlencode(params)
  819. try:
  820. r = self.session.get(url, timeout=60)
  821. r.encoding = 'utf-8'
  822. data = r.text
  823. pm = re.search(r'window.synccheck=\{retcode:"(\d+)",selector:"(\d+)"\}', data)
  824. retcode = pm.group(1)
  825. selector = pm.group(2)
  826. return [retcode, selector]
  827. except:
  828. return [-1, -1]
  829. def sync(self):
  830. url = self.base_uri + '/webwxsync?sid=%s&skey=%s&lang=en_US&pass_ticket=%s' \
  831. % (self.sid, self.skey, self.pass_ticket)
  832. params = {
  833. 'BaseRequest': self.base_request,
  834. 'SyncKey': self.sync_key,
  835. 'rr': ~int(time.time())
  836. }
  837. try:
  838. r = self.session.post(url, data=json.dumps(params), timeout=60)
  839. r.encoding = 'utf-8'
  840. dic = json.loads(r.text)
  841. if dic['BaseResponse']['Ret'] == 0:
  842. self.sync_key = dic['SyncKey']
  843. self.sync_key_str = '|'.join([str(keyVal['Key']) + '_' + str(keyVal['Val'])
  844. for keyVal in self.sync_key['List']])
  845. return dic
  846. except:
  847. return None
  848. def get_icon(self, uid, gid=None):
  849. """
  850. 获取联系人或者群聊成员头像
  851. :param uid: 联系人id
  852. :param gid: 群id,如果为非None获取群中成员头像,如果为None则获取联系人头像
  853. """
  854. if gid is None:
  855. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s' % (uid, self.skey)
  856. else:
  857. url = self.base_uri + '/webwxgeticon?username=%s&skey=%s&chatroomid=%s' % (uid, self.skey, self.encry_chat_room_id_list[gid])
  858. r = self.session.get(url)
  859. data = r.content
  860. fn = 'icon_' + uid + '.jpg'
  861. with open(fn, 'wb') as f:
  862. f.write(data)
  863. return fn
  864. def get_head_img(self, uid):
  865. """
  866. 获取群头像
  867. :param uid: 群uid
  868. """
  869. url = self.base_uri + '/webwxgetheadimg?username=%s&skey=%s' % (uid, self.skey)
  870. r = self.session.get(url)
  871. data = r.content
  872. fn = 'head_' + uid + '.jpg'
  873. with open(fn, 'wb') as f:
  874. f.write(data)
  875. return fn
  876. def get_msg_img_url(self, msgid):
  877. return self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  878. def get_msg_img(self, msgid):
  879. """
  880. 获取图片消息,下载图片到本地
  881. :param msgid: 消息id
  882. :return: 保存的本地图片文件路径
  883. """
  884. url = self.base_uri + '/webwxgetmsgimg?MsgID=%s&skey=%s' % (msgid, self.skey)
  885. r = self.session.get(url)
  886. data = r.content
  887. fn = 'img_' + msgid + '.jpg'
  888. with open(fn, 'wb') as f:
  889. f.write(data)
  890. return fn
  891. def get_voice_url(self, msgid):
  892. return self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  893. def get_voice(self, msgid):
  894. """
  895. 获取语音消息,下载语音到本地
  896. :param msgid: 语音消息id
  897. :return: 保存的本地语音文件路径
  898. """
  899. url = self.base_uri + '/webwxgetvoice?msgid=%s&skey=%s' % (msgid, self.skey)
  900. r = self.session.get(url)
  901. data = r.content
  902. fn = 'voice_' + msgid + '.mp3'
  903. with open(fn, 'wb') as f:
  904. f.write(data)
  905. return fn