def delete_docs(): """Удалить документы""" vk_session = get_session() try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vk_tools = vk_api.VkTools(vk_session) owner = vk_session.method('users.get')[0] print_owner_info(owner) docs = vk_tools.get_all('docs.get', 2000) cnt = docs["count"] if cnt == 0: print("У Вас нет документов") return else: print(f"У Вас {cnt:d} " f"{pluralize(cnt, 'документ', 'документа', 'документов')}") sure = are_you_sure() if not sure: return for doc in docs['items']: print('Удаляем %s...' % doc['title']) vk_session.method('docs.delete', values={ 'owner_id': owner['id'], 'doc_id': doc['id'] })
def dump_albums(): """Выгрузить альбомы""" vk_session = get_session() try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return tools = vk_api.VkTools(vk_session) owner = vk_session.method('users.get')[0] print_owner_info(owner) path = os.path.join(get_user_dump_dir(owner), 'albums') os.makedirs(path, exist_ok=True) albums = tools.get_all('photos.getAlbums', 1000) with open(os.path.join(path, 'albums.json'), 'w', encoding='utf-8') as f: json.dump(albums, f, separators=(',', ':'), ensure_ascii=False) albums['items'] += [ {'title': 'Сохранённые фотографии', 'id': 'saved'}, {'title': 'Фотографии со стены', 'id': 'wall'}, {'title': 'Фотографии профиля', 'id': 'profile'} ] for album in albums['items']: print('Скачиваем альбом ' + album["title"]) album_photos = tools.get_all('photos.get', 1000, values={ 'album_id': album['id'] }) time.sleep(1) album_path = os.path.join(path, f'{escape(album["title"])} [{album["id"]}]'.strip()) os.makedirs(album_path, exist_ok=True) with open(os.path.join(album_path, 'album.json'), 'w', encoding='utf-8') as f: json.dump(album_photos, f, separators=(',', ':'), ensure_ascii=False) download_all_photos(album_path, album_photos, 'альбома') print('Получаем комменты для ' + escape(album["title"])) album_comments = {} for photo in album_photos['items']: comments = tools.get_all('photos.getComments', 100, values={ 'photo_id': photo['id'], 'need_likes': 1, 'extended': 1 }) time.sleep(1) album_comments[photo['id']] = comments with open(os.path.join(album_path, 'comments.json'), 'w', encoding='utf-8') as f: json.dump(album_comments, f, separators=(',', ':'), ensure_ascii=False)
def dump_docs(): """Выгрузить документы""" vk_session = get_session() try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return tools = VkToolsWithRetry(vk_session) owner = vk_session.method('users.get')[0] print_owner_info(owner) path = os.path.join(get_user_dump_dir(owner), 'docs') os.makedirs(path, exist_ok=True) url_to_docpath = dict() for doc_type in list(DocType): doc_name = doc_type.name.lower() doc_idx = doc_type.value print(f'Получаем документы типа {doc_name}') docs = tools.get_all('docs.get', 2000, { 'type': doc_idx, 'owner_id': owner['id'] }) print(f'Всего {docs["count"]:d} документов') with open(os.path.join(path, doc_name + '.json'), 'w', encoding='utf-8') as f: json.dump(docs, f, separators=(',', ':'), ensure_ascii=False) doc_path = os.path.join(path, doc_name) filename_url = dict() for doc in docs['items']: filename = doc['title'] filename_appeared = filename in filename_url filename = escape(filename, with_hash=filename_appeared) if filename.split('.')[-1] != doc['ext']: filename += '.' + doc['ext'] filename_url[filename] = doc['url'] url_list = [(url, filename, '') for filename, url in filename_url.items()] url_to_docpath.update(download_docs(url_list, doc_path, doc_name))
def dump_wall(): """Выгрузить стену""" vk_session = get_session() try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return tools = VkToolsWithRetry(vk_session) """ VkTools.get_all позволяет получить все объекты со всех страниц. Соответственно get_all используется только если метод принимает параметры: count и offset. Например может использоваться для получения всех постов стены, всех диалогов, всех сообщений, etc. При использовании get_all сокращается количество запросов к API за счет метода execute в 25 раз. Например за раз со стены можно получить 100 * 25 = 2500, где 100 - максимальное количество постов, которое можно получить за один запрос (обычно написано на странице с описанием метода) """ owner = vk_session.method('users.get')[0] my_id = owner['id'] print_owner_info(owner) path = os.path.join(get_user_dump_dir(owner), 'wall') os.makedirs(path, exist_ok=True) print('Получаем стену...') wall = tools.get_all('wall.get', 100, {'owner_id': my_id}) print('Всего записей: ', wall['count']) # if wall['count']: # print('First post:') # pprint(wall['items'][0]) # # if wall['count'] > 1: # print('\nLast post:') # pprint(wall['items'][-1]) wall_path = os.path.join(path, 'wall.json') with open(wall_path, 'w', encoding='utf-8') as f: json.dump(wall, f, separators=(',', ':'), ensure_ascii=False) download_all_photos(path, wall, 'записей на стене')
def delete_albums(): """Удалить альбомы""" vk_session = get_session() try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vk_tools = vk_api.VkTools(vk_session) owner = vk_session.method('users.get')[0] print_owner_info(owner) albums = vk_tools.get_all('photos.getAlbums', 1000) if albums['count'] == 0: print("Нет альбомов") else: n = albums['count'] print(f'Всего {n:d} {pluralize(n, "альбом", "альбома", "альбомов")}') sure = are_you_sure() if not sure: return for album in albums['items']: print('Удаляем ' + album['title']) vk_session.method('photos.deleteAlbum', values={'album_id': album['id']}) time.sleep(1) print('Теперь удалим сохранённые, фото со стены, фото профиля') sure = are_you_sure() if not sure: return for special_id in ['saved', 'wall', 'profile']: album_photos = vk_tools.get_all('photos.get', 1000, values={ 'album_id': special_id }) time.sleep(1) for photo in album_photos['items']: print('Deleting ' + str(special_id) + '_' + str(photo['id'])) vk_session.method('photos.delete', values={'photo_id': photo['id']}) time.sleep(1)
def delete_wall(): """Удалить стену""" vk_session = get_session() try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vk_tools = VkToolsWithRetry(vk_session) owner = vk_session.method('users.get')[0] print_owner_info(owner) print('Получаем стену...') wall = vk_tools.get_all('wall.get', 100, {'owner_id': owner['id']}) cnt = wall['count'] print(f'Всего {cnt:d} {pluralize(cnt, "запись", "записи", "записей")}') if cnt == 0: print("На стене нет записей!") return sure = are_you_sure() if not sure: return for wall_post in wall['items']: values = { 'owner_id': wall_post['owner_id'], 'post_id': wall_post['id'] } print('Удаляем %s...' % values) try: vk_session.method('wall.delete', values=values) except vk_api.AccessDenied: # Happens when trying to delete one post two times (dunno why) pass
def dump_videos(): """Выгрузить видеозаписи *только описания, ссылки""" vk_session = get_session() try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return tools = vk_api.VkTools(vk_session) owner = vk_session.method('users.get')[0] print_owner_info(owner) path = os.path.join(get_user_dump_dir(owner), 'videos') os.makedirs(path, exist_ok=True) print('Получаем альбомы...') albums = tools.get_all('video.getAlbums', 100) album_count = albums['count'] print(f'Всего {album_count:d} ' + f'{pluralize(album_count, "альбом", "альбома", "альбомов")}') with open(os.path.join(path, 'albums.json'), 'w', encoding='utf-8') as f: json.dump(albums, f, separators=(',', ':'), ensure_ascii=False) videos = {"count": 0, "items": []} print('Получаем информацию о видеозаписях...') video_ids = set() for album in albums['items']: album_videos = tools.get_all('video.get', 200, values={'album_id': album['id']}) for album_video in album_videos['items']: if album_video['id'] in video_ids: continue videos["count"] += 1 videos["items"].append(album_video) video_ids.add(album_video['id']) time.sleep(1) videos_other = tools.get_all('video.get', 200) for video_other in videos_other['items']: if video_other['id'] in video_ids: continue videos["count"] += 1 videos["items"].append(video_other) video_ids.add(video_other['id']) with open(os.path.join(path, 'videos.json'), 'w', encoding='utf-8') as f: json.dump(videos, f, separators=(',', ':'), ensure_ascii=False) print(f'Всего {videos["count"]} видеозаписей') download_all_photos(path, videos, 'видеозаписей') video_comments = {} for video in videos['items']: print('Получаем комменты для', video["title"]) comments = tools.get_all('video.getComments', 100, values={ 'owner_id': video['owner_id'], 'video_id': video['id'], 'need_likes': 1, 'extended': 1 }) time.sleep(1) video_comments[video['id']] = comments with open(os.path.join(path, 'comments.json'), 'w', encoding='utf-8') as f: json.dump(video_comments, f, separators=(',', ':'), ensure_ascii=False)
def delete_fave(): """Удалить закладки (лайки)""" vk_session = get_session() try: vk_session.auth() except vk_api.AuthError as error_msg: print(error_msg) return vk_tools = vk_api.VkTools(vk_session) owner = vk_session.method('users.get')[0] print_owner_info(owner) for fave_type in FAVE_TYPES: print('Получаем закладки %s...' % fave_type) fave = vk_tools.get_all('fave.get' + fave_type, 100) cnt = fave['count'] print(f'Всего {cnt:d} {fave_type}') if cnt == 0: print("У Вас нет " + fave_type) continue sure = are_you_sure() if not sure: continue mode = input( 'При удалении лайков часто выскакивает капча. Выберите режим:\n' '[+] агрессивный (1 лайк в ' + str(TIMEOUT_FOR_UNLIKE) + ' сек, капча каждые 14-18 объектов)\n' '[-] аккуратный (капча каждые 45-50 объектов)') aggressive = mode == '+' for item in fave['items']: if fave_type in ['Photos', 'Posts', 'Videos']: values = { 'type': fave_type.lower()[:-1], 'owner_id': item['owner_id'], 'item_id': item['id'] } print('Удаляем %s...' % values) vk_session.method('likes.delete', values=values) elif fave_type == 'Links': print(f'Удаляем {item["title"]}') vk_session.method('fave.removeLink', values={'link_id': item['id']}) elif fave_type == 'Users': print(f'Удаляем {item["first_name"]} {item["last_name"]}') vk_session.method('fave.removeUser', values={'user_id': item['id']}) else: print( f'Ещё не готово. Удалите {fave_type} вручную, пожалуйста') continue timeout = TIMEOUT_FOR_UNLIKE if not aggressive: timeout += random.random() * TIMEOUT_DELTA time.sleep(timeout) print('API вконтакте не позволяет удалять лайки с объектов удалённых ' 'групп или пользователей. Пожалуйста, просмотрите вручную закладки ' 'и снимите лайки.')