wxbot.py 37 KB

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