wxbot.py 39 KB

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