### Install VKpyMusic from source Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md Install the VKpyMusic library directly from its GitHub repository. Requires git to be installed. ```bash pip install git+https://github.com/issamansur/vkpymusic.git ``` -------------------------------- ### Full Example: Token Retrieval, Service Initialization, and Song Saving Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md A comprehensive example demonstrating the entire workflow: obtaining a token, initializing the service, searching for a song, and saving it locally. ```python from vkpymusic import Service, TokenReceiver login = input(" Enter login: ") password = input("Enter password: ") tokenReceiver = TokenReceiver(login, password) if tokenReceiver.auth(): print(tokenReceiver.get_token()) tokenReceiver.save_to_config() service = Service.parse_config() tracks = service.search_songs_by_text('Radiohead no surprises') Service.save_music(tracks[0]) ``` -------------------------------- ### Install VKpyMusic using pip Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md Install the VKpyMusic library using pip. This is the recommended installation method. ```bash pip install vkpymusic ``` -------------------------------- ### Client Model Example Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/types.md Demonstrates using pre-configured clients and creating a custom Client instance for API requests. ```python from vkpymusic import VkMobileClient, KateMobileClient, Client # Use pre-configured client receiver = TokenReceiver("user@example.com", "password", client=VkMobileClient) # Or create custom client custom = Client( user_agent="MyApp/1.0 (Custom)", client_id="12345", client_secret="secret123" ) ``` -------------------------------- ### Song Model Example Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/types.md Demonstrates how to create and use a Song object. Includes conversion to a dictionary. ```python from vkpymusic import Song song = Song( title="Imaginary Friends", artist="NIKI", duration=214, track_id="456", owner_id="789", url="https://example.com/song.mp3" ) print(f"{song.title} - {song.artist}") # "Imaginary Friends - NIKI" song_dict = song.to_dict() ``` -------------------------------- ### Verify vkpymusic Installation Source: https://github.com/issamansur/vkpymusic/blob/main/docs/installation.md Confirm that vkpymusic has been installed correctly by checking its version. ```bash vkpymusic --version ``` -------------------------------- ### Authentication and Setup Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/README.md Demonstrates how to authenticate with VK using TokenReceiver and set up the Service class from configuration. Ensure you have your VK login and password. ```Python from vkpymusic import TokenReceiver, Service # Step 1: Get access token receiver = TokenReceiver(login="user@example.com", password="password") if receiver.auth(): receiver.save_to_config() # Step 2: Create service from config service = Service.parse_config() ``` -------------------------------- ### Playlist Model Example Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/types.md Shows how to instantiate and use a Playlist object, printing its title and song count. ```python from vkpymusic import Playlist playlist = Playlist( title="Summer Hits", description="Best songs of summer", photo="https://example.com/cover.jpg", count=100, followers=5000, owner_id=123456, playlist_id=1, access_key="xyz789" ) print(f"{playlist.title} ({playlist.count} songs)") # "Summer Hits (100 songs)" ``` -------------------------------- ### Check Python Version Source: https://github.com/issamansur/vkpymusic/blob/main/docs/installation.md Verify that Python 3.6 or later is installed before proceeding with the installation. ```bash python --version ``` -------------------------------- ### Asynchronous Authentication Example Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/token-receiver.md Demonstrates how to perform asynchronous authentication using TokenReceiver. Requires an async context to run. ```python import asyncio async def async_example(): receiver = TokenReceiver("user@example.com", "password123") if await receiver.auth_async(): token = receiver.get_token() receiver.save_to_config() asyncio.run(async_example()) ``` -------------------------------- ### Complete Workflow: Authentication, Download, and Error Handling Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/README.md A comprehensive example demonstrating the typical workflow: authenticating with TokenReceiver, initializing the Service, searching for songs, downloading them, and handling potential exceptions during the process. ```python from vkpymusic import Service, TokenReceiver # Step 1: Authenticate (one-time setup) receiver = TokenReceiver("user@example.com", "password") if receiver.auth(): receiver.save_to_config() else: print("Authentication failed") exit(1) # Step 2: Create service from config service = Service.parse_config() if not service: print("Config not found") exit(1) # Step 3: Search and download try: songs = service.search_songs_by_text("Imagine Dragons", count=5) print(f"Found {len(songs)} songs") for song in songs: print(f"Downloading: {song.title} - {song.artist}") path = Service.save_music(song, overwrite=False) if path: print(f" Saved to: {path}") else: print(f" Download failed") except Exception as e: print(f"Error: {e}") import traceback traceback.print_exc() ``` -------------------------------- ### UserInfo Model Example Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/types.md Illustrates creating a UserInfo object and accessing its fields like first and last name. ```python from vkpymusic import UserInfo user = UserInfo( userid=123456789, first_name="Jane", last_name="Smith", photo="https://example.com/photo.jpg", phone="+1234567890" ) print(f"{user.first_name} {user.last_name}") # "Jane Smith" ``` -------------------------------- ### Get Song Recommendations (Synchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Gets song recommendations, either personalized for a user or similar to a given song. The count parameter is limited to 300. ```python # Get recommendations for a user recommendations = service.get_recommendations(user_id=123456789, count=10) # Get similar songs similar = service.get_recommendations(song_id=789, count=10) ``` -------------------------------- ### Pre-configured Clients Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/client.md Provides access to pre-configured client instances for common VK applications, simplifying setup for standard use cases. ```APIDOC ## Pre-configured Clients ### KateMobileClient Kate Mobile client configuration for VK API. ```python from vkpymusic import KateMobileClient KateMobileClient.user_agent # "KateMobileAndroid/56 lite-460 (Android 4.4.2; ...)" KateMobileClient.client_id # "2685278" KateMobileClient.client_secret # "lxhD8OD7dMsqtXIm5IUY" ``` ### VkMobileClient VK Mobile official client configuration for VK API. ```python from vkpymusic import VkMobileClient VkMobileClient.user_agent # "VKAndroidApp/4.13.1-1206 (Android 4.4.3; ...)" VkMobileClient.client_id # "2274003" VkMobileClient.client_secret # "hHbZxrka2uZ6jB1inYsH" ``` ``` -------------------------------- ### Create Service from Config File Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Creates a Service instance by parsing a configuration file. If no filename is provided, it defaults to 'config_vk.ini'. The example shows how to use the parsed service to search for songs. ```python service = Service.parse_config() if service: songs = service.search_songs_by_text("Imagine Dragons") ``` -------------------------------- ### build_req_get_recommendations Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Builds a request to get audio recommendations for a user or based on a specific song. ```APIDOC ## build_req_get_recommendations(user_id, song_id, count, offset) ### Description Builds a request to get audio recommendations. This can be personalized for a user or based on a similar song. ### Method classmethod ### Parameters #### Path Parameters - **user_id** (int) - Optional - User ID for personalized recommendations - **song_id** (int) - Optional - Song ID for similar song recommendations - **count** (int) - Optional - Number of recommendations (max 300). Default: 100 - **offset** (int) - Optional - Pagination offset. Default: 0 ### Returns VkApiRequest ``` -------------------------------- ### Load Service from Custom Configuration Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Load the Service object by parsing a custom configuration file. This allows using different configuration files for different setups. ```python from vkpymusic import Service # Load from custom config file service = Service.parse_config("my_config.ini") if service: songs = service.search_songs_by_text("Radiohead") ``` -------------------------------- ### Type Hinting for Song Search Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/README.md Illustrates the use of type hints for improved code clarity and IDE support when searching for songs. This example assumes the Service has been configured. ```python from vkpymusic import Service from typing import List service: Service = Service.parse_config() songs: List[Song] = service.search_songs_by_text("query") ``` -------------------------------- ### get_recommendations_async Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Gets song recommendations asynchronously. This method is the asynchronous counterpart to `get_recommendations`. ```APIDOC ## get_recommendations_async(user_id, song_id, count, offset) ### Description Gets recommendations (asynchronous). ### Parameters #### Path Parameters - **user_id** (int | None) - Optional - None - User ID for personalized recommendations - **song_id** (int | None) - Optional - None - Song ID for similar songs - **count** (int) - Optional - 50 - Number of results (max 300) - **offset** (int) - Optional - 0 - Pagination offset ### Returns List[Song] ``` -------------------------------- ### INI Configuration File Format Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Example of the INI file format used for storing VK API credentials. This format includes sections like [VK] with keys for user_agent and token_for_audio. ```ini [VK] user_agent=VKAndroidApp/4.13.1-1206 (Android 4.4.3; SDK 19; armeabi; ; ru) token_for_audio=YOUR_ACCESS_TOKEN_HERE ``` -------------------------------- ### Get Playlists by User ID (Synchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Retrieves playlists created by a user. The count parameter is limited to 100. ```python playlists = service.get_playlists_by_userid(123456789, count=10) for playlist in playlists: print(f"{playlist.title} ({playlist.count} songs)") ``` -------------------------------- ### Build Get Profile Info Request Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Constructs a request to fetch the current user's profile information. This method does not require any parameters. ```python request = VkApiRequestBuilder.build_req_get_profile_info() ``` -------------------------------- ### Build Get Audio by IDs Request Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Constructs a request to fetch audio tracks using their unique IDs. The IDs must be in the format '[owner_id]_[audio_id]'. ```python request = VkApiRequestBuilder.build_req_get_by_id(audios_ids=['owner1_audio1', 'owner2_audio2']) ``` -------------------------------- ### Build Get Audio Request (User/Playlist) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Builds a request to retrieve audio tracks, either from a user's library or a specific playlist. Supports specifying the number of tracks, offset, and access key for private playlists. ```python # Get user's audio request = VkApiRequestBuilder.build_req_get(userid=123456789, count=50) ``` ```python # Get audio from specific playlist request = VkApiRequestBuilder.build_req_get( userid=123456789, playlist_id=1, access_key="abc123" ) ``` -------------------------------- ### Handle Access Denied (Error Code 201) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/errors.md This example demonstrates catching a VkApiException with error code 201, which signifies access denial to a user's private audio library or deleted content. It advises handling this by informing the user. ```python from vkpymusic import Service from vkpymusic.vk_api import VkApiException service = Service.parse_config() try: songs = service.get_songs_by_userid(123456789) except VkApiException as e: if e.error_code == 201: print("Access denied to user's audio library") # Handle restricted access gracefully ``` -------------------------------- ### Custom Captcha Solutions with External Services Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/utils.md Provides an example of how to integrate with external captcha solving services like 2captcha by sending the captcha image and polling for the result. ```APIDOC ### Custom Captcha Solutions ```python def solve_with_external_service(url: str) -> str: """Use 2captcha or similar service""" import requests # 1. Get captcha page response = requests.get(url) # 2. Extract captcha data if needed # 3. Send to solving service solve = requests.post( "https://2captcha.com/api/upload", files={"captchafile": response.content}, data={"key": "YOUR_API_KEY"} ) captcha_id = solve.json()["captcha"] # 4. Poll for result while True: result = requests.get( f"https://2captcha.com/api/res?key=YOUR_KEY&captcha={captcha_id}" ) if result.text != "CAPCHA_NOT_READY": return result.text receiver = TokenReceiver("user@example.com", "password") success = receiver.auth(on_captcha=solve_with_external_service) ``` -------------------------------- ### Build Get Audio Count Request Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Builds a request to retrieve the total number of audio tracks for a specified user. Requires the user's VK ID. ```python request = VkApiRequestBuilder.build_req_get_count(userid=123456789) ``` -------------------------------- ### Get Songs by User ID (Synchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Retrieves songs from a user's library. Requires a VK user ID. The count parameter is limited to 100, and offset can be used for pagination. ```python user_songs = service.get_songs_by_userid(123456789, count=50) ``` -------------------------------- ### Build Get Popular Audio Request Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Builds a request to retrieve a list of popular audio tracks. Supports specifying the number of tracks and pagination offset, with a maximum of 500 tracks. ```python request = VkApiRequestBuilder.build_req_get_popular(count=100) ``` -------------------------------- ### Build Get User Playlists Request Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Builds a request to retrieve a list of playlists belonging to a specific VK user. Specify the user ID and optionally the number of playlists and offset for pagination. ```python VkApiRequestBuilder.build_req_get_playlists(userid=123, count=50, offset=0) ``` -------------------------------- ### Get String Representation of Song Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/song.md Call this method to get a formatted string of the song's title and artist. Useful for display purposes. ```python song = Song("No Surprises", "Radiohead", 218, "789", "123456") print(song) # Output: "No Surprises - Radiohead" ``` -------------------------------- ### Initialize Service Instance Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Initializes a Service instance using user agent and access token. Ensure you replace 'your_access_token_here' with a valid token. ```python from vkpymusic import Service service = Service( user_agent="VKAndroidApp/4.13.1-1206 (Android 4.4.3; SDK 19)", token="your_access_token_here" ) ``` -------------------------------- ### Get Song Count by User ID (Synchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Gets the total number of songs in a user's library. Returns -1 if access is denied. ```python count = service.get_count_by_user_id(123456789) if count > 0: print(f"User has {count} songs") elif count == -1: print("Access denied to user's library") ``` -------------------------------- ### Initialize Service with Configuration Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md Initialize the Service class by parsing configuration from a file. This is typically done after saving the token using TokenReceiver. ```python from vkpymusic import Service service = Service.parse_config() ``` -------------------------------- ### Initialize Service with Constructor Parameters Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Initialize the Service object directly using constructor parameters for user_agent and token. This method is an alternative to loading from a configuration file. ```python from vkpymusic import Service service = Service( user_agent="VKAndroidApp/4.13.1-1206 (Android 4.4.3; SDK 19)", token="your_token_here" ) ``` -------------------------------- ### Initialize UserInfo Object Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/userinfo.md Use this to create a UserInfo object with all available details. Ensure all required parameters are provided. ```python from vkpymusic import UserInfo user = UserInfo( userid=123456789, first_name="John", last_name="Doe", photo="https://example.com/photo.jpg", phone="+1234567890" ) ``` -------------------------------- ### get_count_by_user_id_async Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Gets the song count for a user asynchronously. This method is the asynchronous counterpart to `get_count_by_user_id`. ```APIDOC ## get_count_by_user_id_async(user_id) ### Description Gets song count (asynchronous). ### Parameters #### Path Parameters - **user_id** (str | int) - Required - VK user ID ### Returns int ``` -------------------------------- ### get_count_by_user_id Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Gets the count of songs in a user's library synchronously. Requires a user ID. ```APIDOC ## get_count_by_user_id(user_id) ### Description Gets the count of songs in a user's library (synchronous). ### Parameters #### Path Parameters - **user_id** (str | int) - Required - VK user ID ### Returns int — Song count, or -1 if access denied ### Example ```python count = service.get_count_by_user_id(123456789) if count > 0: print(f"User has {count} songs") elif count == -1: print("Access denied to user's library") ``` ``` -------------------------------- ### Initialize Playlist Object Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/playlist.md Instantiate a Playlist object with all required attributes. Ensure all parameters are provided as specified. ```python from vkpymusic import Playlist playlist = Playlist( title="Rock Classics", description="Best rock songs", photo="https://example.com/cover.jpg", count=50, followers=1000, owner_id=123456, playlist_id=1, access_key="abc123def456" ) ``` -------------------------------- ### Get Popular Tracks Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md Retrieve a list of popular tracks, with options to specify the count and offset for pagination. ```python songs = service.get_popular(count=50, offset=0) ``` -------------------------------- ### Initialize Custom Client Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/client.md Use this snippet to create a custom Client instance with your specific VK API credentials. Ensure you have your user agent, client ID, and client secret. ```python from vkpymusic import Client # Create a custom client custom_client = Client( user_agent="MyApp/1.0 (Android 10)", client_id="2685278", client_secret="lxhD8OD7dMsqtXIm5IUY" ) ``` -------------------------------- ### Initialize Song Object Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/song.md Use this to create a Song object with all its metadata. Ensure all required parameters are provided. ```python from vkpymusic import Song song = Song( title="No Surprises", artist="Radiohead", duration=218, track_id="789", owner_id="123456", url="https://example.com/song.mp3" ) ``` -------------------------------- ### Initialize Service with Custom Token Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md Initialize the Service class by providing a custom client ID and access token. Use this if you have your own credentials. ```python service = Service("", "") ``` -------------------------------- ### Get Authentication Token Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/token-receiver.md Retrieve the access token after a successful authentication. Returns None if authentication has not been performed or failed. ```python if receiver.auth(): token = receiver.get_token() print(f"Token: {token}") ``` -------------------------------- ### Service Constructor Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Initializes a Service instance with VK API credentials. Requires a user agent and an access token. ```APIDOC ## Service Constructor ### `__init__(user_agent, token)` Initializes a Service instance with VK API credentials. #### Parameters - **user_agent** (str) - Required - User agent string for HTTP requests - **token** (str) - Required - VK API access token for authentication #### Returns None #### Example ```python from vkpymusic import Service service = Service( user_agent="VKAndroidApp/4.13.1-1206 (Android 4.4.3; SDK 19)", token="your_access_token_here" ) ``` ``` -------------------------------- ### Create and Use Custom Logger Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/utils.md Demonstrates how to create a custom logger with console and file output and set it for the Service class. This allows for customized logging behavior within the vkpymusic service. ```python from vkpymusic.utils import create_logger from vkpymusic import Service # Create custom logger logger = create_logger("my_app", console=True, file=True) # Set it for Service class Service.set_logger(logger) # Now use service with custom logging service = Service.parse_config() songs = service.search_songs_by_text("Radiohead") ``` -------------------------------- ### build_req_2fa_code Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Builds a request to get 2FA code options. This is used when a two-factor authentication code is required during the login process. ```APIDOC ## build_req_2fa_code ### Description Builds a request to get 2FA code options. ### Method `staticmethod` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | client | Client | Yes | — | Client with user agent | | sid | str \| int | Yes | — | Session ID from auth challenge | ### Returns VkApiRequest ``` -------------------------------- ### Get Songs by IDs Asynchronously Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Retrieves songs by their IDs asynchronously. Returns a list of Song objects. Raises VkApiException on error. ```python # Example usage for async song retrieval would typically be within an async function # async def get_songs_async(service_instance, ids): # return await service_instance.get_songs_by_id_async(ids) pass ``` -------------------------------- ### Load Service from Default Configuration Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Load the Service object by parsing the default configuration file 'config_vk.ini'. This is useful for initializing the service with previously saved credentials. ```python from vkpymusic import Service # Load from default config_vk.ini service = Service.parse_config() if service: songs = service.search_songs_by_text("Radiohead") ``` -------------------------------- ### Playlist String Representation Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/playlist.md Get a string representation of the playlist in the format 'title (count tracks)'. This is useful for quick display or logging. ```python playlist = Playlist("Rock Classics", "Best rock", "url", 50, 1000, 123456, 1, "key") print(playlist) # Output: "Rock Classics (50 tracks)" ``` -------------------------------- ### Initialize TokenReceiver Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/token-receiver.md Instantiate TokenReceiver with login and password. This is the first step before performing authentication. ```python from vkpymusic import TokenReceiver receiver = TokenReceiver( login="user@example.com", password="password123" ) # Perform authentication if receiver.auth(): token = receiver.get_token() receiver.save_to_config() ``` -------------------------------- ### Pre-configured Client Instances Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/types.md Provides pre-configured Client instances for common VK clients like KateMobile and VkMobile. ```python KateMobileClient = Client( user_agent="KateMobileAndroid/56 lite-460 (Android 4.4.2; SDK 19; x86; unknown Android SDK built for x86; en)", client_id="2685278", client_secret="lxhD8OD7dMsqtXIm5IUY" ) VkMobileClient = Client( user_agent="VKAndroidApp/4.13.1-1206 (Android 4.4.3; SDK 19; armeabi; ; ru)", client_id="2274003", client_secret="hHbZxrka2uZ6jB1inYsH" ) ``` -------------------------------- ### Perform Async Song Recommendations Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/README.md Shows how to fetch song recommendations asynchronously using the vk-music library. Ensure you have configured the service correctly before calling this function. ```python import asyncio async def fetch_recommendations(): service = Service.parse_config() songs = await service.get_recommendations_async(user_id=123456789) return songs asyncio.run(fetch_recommendations()) ``` -------------------------------- ### get_recommendations Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Gets song recommendations synchronously. Can be personalized for a user or based on a specific song ID. Allows specifying the number of results and pagination offset. ```APIDOC ## get_recommendations(user_id, song_id, count, offset) ### Description Gets song recommendations (synchronous). ### Parameters #### Path Parameters - **user_id** (int | None) - Optional - None - User ID for personalized recommendations - **song_id** (int | None) - Optional - None - Song ID for similar songs - **count** (int) - Optional - 50 - Number of results (max 300) - **offset** (int) - Optional - 0 - Pagination offset ### Returns List[Song] ### Example ```python # Get recommendations for a user recommendations = service.get_recommendations(user_id=123456789, count=10) # Get similar songs similar = service.get_recommendations(song_id=789, count=10) ``` ``` -------------------------------- ### Get Popular Songs (Synchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Retrieves a list of popular songs. The count parameter is limited to 500. Note that the number of results may be fewer than requested. ```python popular = service.get_popular(count=20) for song in popular: print(f"{song.title} - {song.artist}") ``` -------------------------------- ### build_req_get_count Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Builds a request to get the total count of a user's audio tracks. This method helps in understanding the number of songs associated with a VK user. ```APIDOC ## build_req_get_count ### Description Builds a request to get the count of a user's audio tracks. ### Method `classmethod` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters Table | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | userid | int | Yes | — | VK user ID | ### Returns VkApiRequest ``` -------------------------------- ### Playlist Constructor Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/playlist.md Initializes a Playlist object with detailed playlist information. ```APIDOC ## Playlist Constructor ### `__init__(title, description, photo, count, followers, owner_id, playlist_id, access_key)` Initializes a Playlist object. #### Parameters - **title** (str) - Required - Playlist title - **description** (str) - Required - Playlist description - **photo** (str) - Required - URL to playlist cover image - **count** (int) - Required - Number of songs in playlist - **followers** (int) - Required - Number of followers - **owner_id** (int) - Required - VK user ID of playlist owner - **playlist_id** (int) - Required - Unique playlist ID - **access_key** (str) - Required - Access key for restricted playlists #### Request Example ```python from vkpymusic import Playlist playlist = Playlist( title="Rock Classics", description="Best rock songs", photo="https://example.com/cover.jpg", count=50, followers=1000, owner_id=123456, playlist_id=1, access_key="abc123def456" ) ``` ``` -------------------------------- ### Client Initialization Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/client.md Initializes a Client object with VK authentication credentials. This allows for custom configuration of user agent, client ID, and client secret for API requests. ```APIDOC ## Client ### Description Class that stores the user agent string, client ID, and client secret for VK API authentication. ### Constructor #### `__init__(user_agent, client_id, client_secret)` Initializes a Client object with VK authentication credentials. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | user_agent | str | Yes | — | User agent string identifying the client application | | client_id | str | Yes | — | VK application client ID | | client_secret | str | Yes | — | VK application client secret | **Returns:** None **Example:** ```python from vkpymusic import Client # Create a custom client custom_client = Client( user_agent="MyApp/1.0 (Android 10)", client_id="2685278", client_secret="lxhD8OD7dMsqtXIm5IUY" ) ``` ### Attributes | Attribute | Type | Description | |-----------|------|-------------| | user_agent | str | User agent string for HTTP requests | | client_id | str | VK application client ID | | client_secret | str | VK application client secret | ``` -------------------------------- ### Get Songs by Playlist ID (Synchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Retrieves songs from a playlist using user ID, playlist ID, and access key. The count parameter is limited to 100. ```python # Example usage for get_songs_by_playlist_id would go here, but is not provided in the source. ``` -------------------------------- ### UserInfo Constructor Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/userinfo.md Initializes a UserInfo object with essential user details and optional photo and phone information. ```APIDOC ## UserInfo Constructor ### `__init__(userid, first_name, last_name, photo, phone)` Initializes a UserInfo object. #### Parameters - **userid** (int) - Required - VK user ID - **first_name** (str) - Required - User's first name - **last_name** (str) - Required - User's last name - **photo** (str) - Optional - URL to user's profile photo (200px), defaults to "" - **phone** (str) - Optional - User's phone number (if available), defaults to "" #### Request Example ```python from vkpymusic import UserInfo user = UserInfo( userid=123456789, first_name="John", last_name="Doe", photo="https://example.com/photo.jpg", phone="+1234567890" ) ``` ``` -------------------------------- ### Song Constructor Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/song.md Initializes a Song object with essential track metadata and an optional download URL. ```APIDOC ## Song Constructor ### `__init__(title, artist, duration, track_id, owner_id, url)` Initializes a Song object. #### Parameters - **title** (str) - Required - Song title - **artist** (str) - Required - Artist name - **duration** (int) - Required - Duration in seconds - **track_id** (str) - Required - Song ID in VK system - **owner_id** (str) - Required - ID of song owner in VK - **url** (str) - Optional - Download URL for the song #### Returns None #### Example ```python from vkpymusic import Song song = Song( title="No Surprises", artist="Radiohead", duration=218, track_id="789", owner_id="123456", url="https://example.com/song.mp3" ) ``` ``` -------------------------------- ### Save Music with Overwrite Option Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Demonstrates how to save a song, with an option to overwrite existing files. The default behavior is not to overwrite. ```python from vkpymusic import Service service = Service.parse_config() songs = service.search_songs_by_text("Radiohead", count=1) # Don't overwrite if exists (default) Service.save_music(songs[0]) # Overwrite if exists Service.save_music(songs[0], overwrite=True) ``` -------------------------------- ### Get Songs by IDs Synchronously Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Retrieves a list of songs based on their unique IDs. IDs should be in the format '[owner_id]_[audio_id]'. Iterates through the results and prints song title and artist. ```python songs = service.get_songs_by_id(["123456_789", "987654_321"]) for song in songs: print(f"{song.title} - {song.artist}") ``` -------------------------------- ### Build Audio Recommendations Request Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Constructs a request to fetch audio recommendations for a user or based on a specific song. Use this to personalize music suggestions or find similar tracks. ```python VkApiRequestBuilder.build_req_get_recommendations(user_id=123, song_id=456, count=10, offset=0) ``` -------------------------------- ### Playlist Operations Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/README.md Demonstrates how to search for playlists by text and retrieve songs from a specific playlist. Requires an authenticated Service instance. ```Python # Search playlists playlists = service.search_playlists_by_text("rock", count=5) # Get songs from playlist if playlists: songs = service.get_songs_by_playlist(playlists[0], count=20) ``` -------------------------------- ### Search and Download Songs Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/README.md Shows how to search for songs by text and download the first result. Requires an authenticated Service instance. ```Python # Search for songs songs = service.search_songs_by_text("Radiohead", count=5) # Download first result if songs: Service.save_music(songs[0]) ``` -------------------------------- ### Get Songs by Playlist Object (Synchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Retrieves songs from a Playlist object. Ensure the playlist object is valid and obtained from a previous call like get_playlists_by_userid. The count parameter is limited to 100. ```python playlists = service.get_playlists_by_userid(123456789) if playlists: songs = service.get_songs_by_playlist(playlists[0], count=20) ``` -------------------------------- ### Configure Logging for vk-music Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/README.md Sets up a logger for the vk-music library, enabling both console and file logging. This helps in debugging and monitoring library operations. ```python from vkpymusic.utils import create_logger from vkpymusic import Service logger = create_logger(__name__, console=True, file=True) Service.set_logger(logger) ``` -------------------------------- ### Initialize TokenReceiver with Constructor Parameters Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Initialize the TokenReceiver object directly using constructor parameters for login, password, client, and logger. This allows for programmatic control over authentication. ```python from vkpymusic import TokenReceiver, KateMobileClient receiver = TokenReceiver( login="user@example.com", password="password123", client=KateMobileClient ) ``` -------------------------------- ### Service Factory Methods Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Provides class methods for creating and managing Service instances, including loading from configuration and setting up logging. ```APIDOC ## Factory Methods ### `parse_config(filename)` (classmethod) Creates a Service instance from a configuration file created by TokenReceiver. #### Parameters - **filename** (str) - Optional - Configuration file name (defaults to "config_vk.ini") #### Returns Service | None — Service instance if config found and valid, None otherwise #### Example ```python service = Service.parse_config() if service: songs = service.search_songs_by_text("Imagine Dragons") ``` ### `del_config(filename)` (classmethod) Deletes the configuration file. #### Parameters - **filename** (str) - Optional - Configuration file name (defaults to "config_vk.ini") #### Returns None #### Example ```python Service.del_config() ``` ### `set_logger(logger)` (classmethod) Sets the logger for the Service class. #### Parameters - **logger** (logging.Logger) - Required - Logger instance #### Returns None ``` -------------------------------- ### Custom Synchronous Critical Error Handler Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/utils.md Shows how to use a custom synchronous handler for critical or unexpected errors. The provided example logs the error to the console, demonstrating how to process error responses or exceptions. ```python from vkpymusic.utils import on_critical_error_handler from vkpymusic import TokenReceiver def custom_error_handler(error): print(f"Critical error: {error}") receiver = TokenReceiver("user@example.com", "password") success = receiver.auth(on_critical_error=custom_error_handler) ``` -------------------------------- ### Download Music (Synchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Downloads and saves a song to the local file system. Overwrites existing files if specified. Requires a Song object. ```python songs = service.search_songs_by_text("Imagine Dragons", count=1) if songs: file_path = Service.save_music(songs[0]) if file_path: print(f"Downloaded to: {file_path}") ``` -------------------------------- ### Get User Songs by User ID Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md Retrieve a specified number of songs for a given user ID. Note that only the user ID (numeric) is accepted. Access denied exceptions may occur if the user's audios are private. ```python user_songs = service.get_songs_by_userid(123456789, 10) ``` -------------------------------- ### Use KateMobileClient with TokenReceiver Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Initialize TokenReceiver using the KateMobileClient for authentication. This client uses Kate Mobile app credentials as an alternative. ```python from vkpymusic import TokenReceiver, KateMobileClient receiver = TokenReceiver("user@example.com", "password", client=KateMobileClient) ``` -------------------------------- ### Create and Save Configuration File Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Use TokenReceiver to authenticate and save VK API credentials to a configuration file. The file can be saved with the default name 'config_vk.ini' or a custom name. ```python from vkpymusic import TokenReceiver receiver = TokenReceiver(login="user@example.com", password="password123") if receiver.auth(): receiver.save_to_config() # Saves to config_vk.ini # or with custom name receiver.save_to_config("my_config.ini") ``` -------------------------------- ### Built-in Selenium Captcha Solver Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/utils.md Utilize the library's default synchronous captcha handler which uses Selenium to open a browser, wait for user interaction, and extract the token from the redirect URL. Ensure Selenium WebDriver and a compatible browser are installed. ```python from vkpymusic.utils import handle_captcha_selenium # This function is called by default on_captcha_handler token = handle_captcha_selenium("https://captcha.vk.com/...") ``` -------------------------------- ### Playlist Methods Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/playlist.md Provides methods for string representation, dictionary conversion, and creation from JSON. ```APIDOC ## Playlist Methods ### `__str__() -> str` Returns a string representation in format "title (count tracks)". #### Response Example ```python playlist = Playlist("Rock Classics", "Best rock", "url", 50, 1000, 123456, 1, "key") print(playlist) # Output: "Rock Classics (50 tracks)" ``` ### `to_dict() -> dict` Converts the playlist to a dictionary with all attributes. #### Response Example ```python playlist_dict = playlist.to_dict() print(playlist_dict) # Output: { # 'title': 'Rock Classics', # 'description': 'Best rock songs', # 'photo': 'https://...', # 'count': 50, # 'followers': 1000, # 'owner_id': 123456, # 'playlist_id': 1, # 'access_key': 'abc123def456' # } ``` ### `from_json(item) -> Playlist` (classmethod) Creates a Playlist instance from a VK API JSON response. #### Parameters - **item** (dict) - Required - JSON object from VK API with playlist data #### Response Example ```python api_response = { "id": 1, "title": "Rock Classics", "description": "Best rock", "count": 50, "followers": 1000, "owner_id": 123456, "access_key": "abc123", "photo": { "photo_1200": "https://example.com/cover.jpg" } } playlist = Playlist.from_json(api_response) ``` ``` -------------------------------- ### TokenReceiver Constructor Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/token-receiver.md Initializes a TokenReceiver instance for VK authentication. It requires the user's login and password, and optionally accepts a custom client and logger. ```APIDOC ## TokenReceiver Constructor ### `__init__(login, password, client, logger)` Initializes a TokenReceiver instance for VK authentication. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | login | str | Yes | — | VK account login (email or phone) | | password | str | Yes | — | VK account password | | client | Client | No | VkMobileClient | Client credentials for authentication | | logger | logging.Logger | No | create_logger() | Logger instance for logging messages | **Returns:** None **Example:** ```python from vkpymusic import TokenReceiver receiver = TokenReceiver( login="user@example.com", password="password123" ) # Perform authentication if receiver.auth(): token = receiver.get_token() receiver.save_to_config() ``` ``` -------------------------------- ### Save Authentication Details to Config Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/token-receiver.md Saves the obtained token and user agent to a configuration file. Allows specifying a custom file path. ```python if receiver.auth(): receiver.save_to_config() # Saves to config_vk.ini # or receiver.save_to_config("custom_config.ini") ``` -------------------------------- ### Create Default Logger Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Create a logger instance with default configuration using the create_logger utility function. This logger is suitable for general use with default console and file logging enabled. ```python from vkpymusic.utils import create_logger logger = create_logger(__name__) ``` -------------------------------- ### Use VkMobileClient with TokenReceiver Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/configuration.md Initialize TokenReceiver using the recommended VkMobileClient for authentication. This client uses official VK Mobile app credentials. ```python from vkpymusic import TokenReceiver, VkMobileClient # Use VkMobileClient receiver = TokenReceiver("user@example.com", "password", client=VkMobileClient) ``` -------------------------------- ### Download Music (Asynchronous) Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/service.md Asynchronously downloads and saves a song. Handles file overwriting and returns the file path. Requires a Song object. ```python import asyncio async def download_songs(): service = Service.parse_config() songs = await service.search_songs_by_text_async("Imagine Dragons", count=5) for song in songs: path = await Service.save_music_async(song) if path: print(f"Downloaded: {path}") asyncio.run(download_songs()) ``` -------------------------------- ### save_to_config() Method Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/token-receiver.md Saves the obtained access token and user agent data to a configuration file. The file path can be specified, defaulting to 'config_vk.ini'. ```APIDOC ## `save_to_config(file_path)` Saves token and user agent data to a configuration file. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | file_path | str | No | "config_vk.ini" | Path to configuration file (relative to vkpymusic module) | **Returns:** None **Example:** ```python if receiver.auth(): receiver.save_to_config() # Saves to config_vk.ini # or receiver.save_to_config("custom_config.ini") ``` ``` -------------------------------- ### Alternative Access Denied Handling with get_count_by_user_id Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/errors.md Shows an alternative method for detecting access denial when retrieving song counts. The `get_count_by_user_id` method returns -1 if access is denied. ```python count = service.get_count_by_user_id(123456789) if count == -1: print("Cannot access this user's library") ``` -------------------------------- ### create_path() Static Method Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/token-receiver.md A static method that converts a relative file path into an absolute path within the vkpymusic module directory. Useful for managing configuration files. ```APIDOC ## `create_path(file_path) -> str` (static) Converts a relative file path to an absolute path within the vkpymusic module directory. | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | file_path | str | Yes | — | Relative file path | **Returns:** str — Absolute path to the file **Example:** ```python abs_path = TokenReceiver.create_path("config_vk.ini") print(abs_path) # /path/to/vkpymusic/config_vk.ini ``` ``` -------------------------------- ### on_2fa_handler Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/utils.md Default synchronous 2FA handler. Prompts user via console input. ```APIDOC ## on_2fa_handler() ### Description Default synchronous 2FA handler. Prompts user via console input. ### Returns str - Code from VK/SMS ### Example ```python from vkpymusic.utils import on_2fa_handler from vkpymusic import TokenReceiver receiver = TokenReceiver("user@example.com", "password") success = receiver.auth(on_2fa=on_2fa_handler) ``` ``` -------------------------------- ### Build Search Audio Request Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Constructs a request to search for audio tracks based on a query. Allows specifying the number of results and pagination offset. ```python request = VkApiRequestBuilder.build_req_search("Radiohead", count=20) ``` -------------------------------- ### Build Authentication Request Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/vk-api-request-builder.md Constructs a request to authenticate with VK and obtain an access token. Requires login, password, and client details. Optional parameters include 2FA code and captcha solution. ```python from vkpymusic.vk_api import VkApiRequestBuilder from vkpymusic import VkMobileClient request = VkApiRequestBuilder.build_req_auth( login="user@example.com", password="password123", client=VkMobileClient ) ``` -------------------------------- ### Retrieve VK Access Token and User Agent Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md Use the TokenReceiver class to authenticate with VK using login and password. Handles CAPTCHA and 2FA. The token and user agent can be saved to a configuration file. ```python from vkpymusic import TokenReceiver login = input(" Enter login: ") password = input("Enter password: ") tokenReceiver = TokenReceiver(login, password) if tokenReceiver.auth(): print(tokenReceiver.get_token()) tokenReceiver.save_to_config() ``` -------------------------------- ### UserInfo.from_json() Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/userinfo.md A class method to create a UserInfo instance directly from a VK API JSON response dictionary. ```APIDOC ## UserInfo.from_json() ### `from_json(item) -> UserInfo` (classmethod) Creates a UserInfo instance from a VK API JSON response. #### Parameters - **item** (dict) - Required - JSON object from VK API with user data #### Notes: - Extracts photo from `photo_200` field if available - Handles optional phone field gracefully #### Request Example ```python api_response = { "id": 123456789, "first_name": "John", "last_name": "Doe", "photo_200": "https://example.com/photo.jpg", "phone": "+1234567890" } user = UserInfo.from_json(api_response) ``` ``` -------------------------------- ### String Representation of UserInfo Source: https://github.com/issamansur/vkpymusic/blob/main/_autodocs/api-reference/userinfo.md This method provides a simple string format of the user's ID and name. Useful for quick display or logging. ```python user = UserInfo(123456789, "John", "Doe") print(user) # Output: "123456789 John Doe" ``` -------------------------------- ### Save Track Locally Source: https://github.com/issamansur/vkpymusic/blob/main/README_EN.md Save a music track locally. This can be done using either the static method Service.save_music or an instance of the Service class. ```python songs = service.search_songs_by_text("Radiohead no surprises", 5) Service.save_music(songs[0]) # or service.save_music(songs[0]) ```