wxbot.py 50 KB

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