config.py
main.py
Python:
vk_tokens = '1234'
main.py
Python:
import vk_api
import os
import requests
from config import vk_tokens
vk_session = vk_api.VkApi(token=vk_tokens)
vk = vk_session.get_api()
dialogs = vk.messages.getConversations(count=200)['items']
supported_media_types = ['photo', 'video', 'doc', 'audio']
print("Выберите вариант скачивания:")
for i, media_type in enumerate(supported_media_types):
print(f"{i+1}. {media_type}")
print(f"{len(supported_media_types)+1}. Скачать все файлы поочередно")
choice = int(input("Введите номер: "))
if choice < 1 or choice > len(supported_media_types) + 1:
print("Некорректный выбор.")
else:
if choice != len(supported_media_types) + 1:
media_type = supported_media_types[choice - 1]
for dialog in dialogs:
dialog_info = dialog['conversation']['peer']
if dialog_info['type'] == 'user':
dialog_id = dialog_info['id']
user_info = vk.users.get(user_ids=dialog_id)[0]
first_name = user_info['first_name']
last_name = user_info['last_name']
dialog_dir = f"{first_name}_{last_name}"
if not os.path.exists(dialog_dir):
os.makedirs(dialog_dir)
response = vk.messages.getHistoryAttachments(peer_id=dialog_id, media_type=media_type, count=200)
attachments = response['items']
while 'next_from' in response:
response = vk.messages.getHistoryAttachments(
peer_id=dialog_id, media_type=media_type, count=200, start_from=response['next_from'])
attachments.extend(response['items'])
save_dir = os.path.join(dialog_dir, media_type)
if not os.path.exists(save_dir):
os.makedirs(save_dir)
for attachment in attachments:
attachment_type = attachment['attachment']['type']
media = attachment['attachment'][attachment_type]
if attachment_type == 'photo':
photo_url = media['sizes'][-1]['url']
file_name = f"{media['id']}.jpg"
file_path = os.path.join(save_dir, file_name)
response = requests.get(photo_url)
with open(file_path, 'wb') as f:
f.write(response.content)
print(f"Сохранено: {file_path}")
elif attachment_type == 'video':
video_url = media['player']
file_name = f"{media['id']}.mp4"
file_path = os.path.join(save_dir, file_name)
response = requests.get(video_url)
with open(file_path, 'wb') as f:
f.write(response.content)
print(f"Сохранено: {file_path}")
elif attachment_type == 'doc':
doc_url = media['url']
file_name = f"{media['id']}_{media['title']}"
file_path = os.path.join(save_dir, file_name)
response = requests.get(doc_url)
with open(file_path, 'wb') as f:
f.write(response.content)
print(f"Сохранено: {file_path}")
elif attachment_type == 'audio':
audio_url = media['url']
file_name = f"{media['id']}_{media['artist']} - {media['title']}.mp3"
file_path = os.path.join(save_dir, file_name)
response = requests.get(audio_url)
with open(file_path, 'wb') as f:
f.write(response.content)
print(f"Сохранено: {file_path}")