wxbot.py 38 KB

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