wxbot.py 49 KB

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