wxbot.py 50 KB

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