wxbot.py 42 KB

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