wxbot.py 38 KB

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