Good day to all.
I wanted to download all my music from VKontakte to a USB flash drive, as in the good old days. Googling a little and not finding almost anything more or less acceptable, I decided to act on my own. After half an hour, we got a working script for ourselves. So, let's begin.
To work, you need to download the vk_api and request modules!
To get started, connect the necessary modules and declare some variables:
import os import pickle import vk_api import requests from vk_api import audio from time import time vk_file = "vk_config.v2.json" REQUEST_STATUS_CODE = 200 path = 'vk_music/'
Now we’ll write the authorization method to your VKontakte account:
def Auth(new=False): try: USERDATA_FILE = r"AppData/UserData.datab" # , id global my_id # , # , ? , if (os.path.exists(USERDATA_FILE) and new == False): with open(USERDATA_FILE, 'rb') as DataFile: LoadedData = pickle.load(DataFile) login = LoadedData[0] password = LoadedData[1] my_id = LoadedData[2] else: # , , if (os.path.exists(USERDATA_FILE) and new == True): os.remove(USERDATA_FILE) login = str(input(" \n> ")) password = str(input(" \n> ")) my_id = str(input(" id \n> ")) SaveUserData(login, password, my_id) SaveData = [login, password, my_id] with open(USERDATA_FILE, 'wb') as dataFile: pickle.dump(SaveData, dataFile) # vk_session = vk_api.VkApi(login=login, password=password) try: vk_session.auth() # , , . . except: vk_session = vk_api.VkApi(login=login, password=password, auth_handler=auth_handler) # auth_handler=auth_handler - , . vk_session.auth() print(' .') vk = vk_session.get_api() global vk_audio # , vk_audio = audio.VkAudio(vk_session) except KeyboardInterrupt: print(' .')
The method will check if we have already logged in earlier? If this happened, then you can continue in this account, or log in again. In this case, the old data will be erased.
Next, we write the auth_handler method, which is needed for authorization in accounts in which two-factor authentication is enabled:
def auth_handler(): code = input(" \n> ") remember_device = True # True - return code, remember_device
And so, now we can log in to VKontakte. In the Auth method, the SaveUserData () method was mentioned, it is needed to save data. Let's write it:
def SaveUserData(login, password, profile_id): USERDATA_FILE = r"AppData/UserData.datab" if (not os.path.exists("AppData")): # AppData - os.mkdir("AppData") SaveData = [login, password, profile_id] # with open(USERDATA_FILE, 'wb') as dataFile: # pickle.dump(SaveData, dataFile)
The data will be recorded in binary form, so as not to store the user login and password in clear form.
It remains to write a method for downloading audio from VKontakte, let's do this:
def main(): try: if (not os.path.exists("AppData")): os.mkdir("AppData") if not os.path.exists(path): os.makedirs(path) # , - auth_dialog = str(input(" ? yes/no\n> ")) if (auth_dialog == "yes"): Auth(new=True) elif (auth_dialog == "no"): Auth(new=False) else: print(', .') main() print(' ...') os.chdir(path) # audio = vk_audio.get(owner_id=my_id)[0] print(' :', len(vk_audio.get(owner_id=my_id)), '.') count = 0 time_start = time() print(" ...\n") # , , . for i in vk_audio.get(owner_id=my_id): try: print(': ' + i["artist"] + " - " + i["title"]) count += 1 r = requests.get(audio["url"]) if r.status_code == REQUEST_STATUS_CODE: print(' : ' + i["artist"] + " - " + i["title"]) with open(i["artist"] + ' - ' + i["title"] + '.mp3', 'wb') as output_file: output_file.write(r.content) except OSError: print("!!! №", count) time_finish = time() print("" + vk_audio.get(owner_id=my_id) + " : ", time_finish - time_start + " .") except KeyboardInterrupt: print(' .')
OK it's all over Now. Now we have a working script for downloading audio recordings from VKontakte.
This is how the whole source code looks:
import os import pickle import vk_api import requests from vk_api import audio from time import time __version__ = 'VK Music Downloader v1.0' APP_MESSAGE = ''' _ . ___ /\\ | | | \\ | | | \\ / | / /__\\ | | | \\ | | | \\ / |/ / \\ |___| |__/ | |___| \\/ |\\ ''' vk_file = "vk_config.v2.json" REQUEST_STATUS_CODE = 200 path = 'vk_music/' def auth_handler(remember_device=None): code = input(" \n> ") if (remember_device == None): remember_device = True return code, remember_device def SaveUserData(login, password, profile_id): USERDATA_FILE = r"AppData/UserData.datab" SaveData = [login, password, profile_id] with open(USERDATA_FILE, 'wb') as dataFile: pickle.dump(SaveData, dataFile) def Auth(new=False): try: USERDATA_FILE = r"AppData/UserData.datab" # , id global my_id if (os.path.exists(USERDATA_FILE) and new == False): with open(USERDATA_FILE, 'rb') as DataFile: LoadedData = pickle.load(DataFile) login = LoadedData[0] password = LoadedData[1] my_id = LoadedData[2] else: if (os.path.exists(USERDATA_FILE) and new == True): os.remove(USERDATA_FILE) login = str(input(" \n> ")) password = str(input(" \n> ")) my_id = str(input(" id \n> ")) SaveUserData(login, password, my_id) SaveData = [login, password, my_id] with open(USERDATA_FILE, 'wb') as dataFile: pickle.dump(SaveData, dataFile) vk_session = vk_api.VkApi(login=login, password=password) try: vk_session.auth() except: vk_session = vk_api.VkApi(login=login, password=password, auth_handler=auth_handler) vk_session.auth() print(' .') vk = vk_session.get_api() global vk_audio vk_audio = audio.VkAudio(vk_session) except KeyboardInterrupt: print(' .') def main(): try: if (not os.path.exists("AppData")): os.mkdir("AppData") if not os.path.exists(path): os.makedirs(path) auth_dialog = str(input(" ? yes/no\n> ")) if (auth_dialog == "yes"): Auth(new=True) elif (auth_dialog == "no"): Auth(new=False) else: print(', .') main() print(' ...') os.chdir(path) # audio = vk_audio.get(owner_id=my_id)[0] print(' :', len(vk_audio.get(owner_id=my_id)), '.') count = 0 time_start = time() # print(" ...\n") # for i in vk_audio.get(owner_id=my_id): try: print(': ' + i["artist"] + " - " + i["title"]) # count += 1 r = requests.get(audio["url"]) if r.status_code == REQUEST_STATUS_CODE: print(' : ' + i["artist"] + " - " + i["title"]) with open(i["artist"] + ' - ' + i["title"] + '.mp3', 'wb') as output_file: output_file.write(r.content) except OSError: print("!!! №", count) time_finish = time() print("" + vk_audio.get(owner_id=my_id) + " : ", time_finish - time_start + " .") except KeyboardInterrupt: print(' .') if __name__ == '__main__': print(APP_MESSAGE) print(__version__ + "\n") main()
I am just studying, so I will be glad to all the comments in the code. Thanks for your attention.