wxbot.py 38 KB

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