wxbot.py 43 KB

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