wxbot.py 38 KB

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