wxbot.py 37 KB

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