### Install vk_api using pip Source: https://vk-api.readthedocs.io/en/latest/_sources/index.rst.txt Use this command to install the vk_api library via pip. Ensure you are using pip3 for Python 3. ```shell # pip3 install vk_api ``` -------------------------------- ### Basic vk_api Authentication and Wall Post Source: https://vk-api.readthedocs.io/en/latest/_sources/index.rst.txt This example demonstrates how to authenticate with vk_api using a phone number and password, and then post a message to the wall. Ensure you have imported the vk_api library. ```python import vk_api vk_session = vk_api.VkApi('+71234567890', 'mypassword') vk_session.auth() vk = vk_session.get_api() print(vk.wall.post(message='Hello world!')) ``` -------------------------------- ### Get Keyboard JSON Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/keyboard.html Returns the keyboard configuration as a JSON string. This is the format required for sending to the VK API. ```python def get_keyboard(self): """ Получить json клавиатуры """ return sjson_dumps(self.keyboard) ``` -------------------------------- ### Get Audio from Post Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Fetches a list of audio tracks embedded within a specific VK post. It parses the post's HTML to find audio elements. ```APIDOC ## GET /api/wall/{owner_id}/{post_id}/audios ### Description Retrieves a list of audio tracks from a specified VK post. ### Method GET ### Endpoint `/api/wall/{owner_id}/{post_id}/audios` ### Parameters #### Path Parameters - **owner_id** (string) - Required - The ID of the post owner (negative values for groups). - **post_id** (string) - Required - The ID of the post. ### Response #### Success Response (200) - **audio_list** (array) - An array of audio track objects. #### Response Example ```json { "audio_list": [ { "artist": "Artist Name 1", "title": "Track Title 1", "url": "http://example.com/track1.mp3" }, { "artist": "Artist Name 2", "title": "Track Title 2", "url": "http://example.com/track2.mp3" } ] } ``` ``` -------------------------------- ### Get All Items (Python) Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/tools.html Use this method only if you need to load all objects into memory. If you can process objects in parts, it is better to use get_all_slow_iter. For example, if you are writing objects to a database, there is no point in loading all the data into memory. ```python def get_all_slow(self, method, max_count, values=None, key='items', limit=None, stop_fn=None, negative_offset=False): """ Использовать только если нужно загрузить все объекты в память. Eсли вы можете обрабатывать объекты по частям, то лучше использовать get_all_slow_iter Например если вы записываете объекты в БД, то нет смысла загружать все данные в память """ items = list( self.get_all_slow_iter( method, max_count, values, key, limit, stop_fn, negative_offset ) ) return {'count': len(items), key: items} ``` -------------------------------- ### GET /audio?act=audio_playlists Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Retrieves a list of audio albums for a specific user or group. ```APIDOC ## GET https://m.vk.com/audio?act=audio_playlists ### Description Retrieves a list of audio albums for a given owner. ### Method GET ### Endpoint https://m.vk.com/audio?act=audio_playlists ### Parameters #### Query Parameters - **owner_id** (int) - Optional - ID of the owner (negative values for groups) - **offset** (int) - Optional - Offset for pagination ``` -------------------------------- ### Get All Audio Tracks Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Retrieves all audio tracks for a user or album by converting the iterative getter to a list. This is a convenience method for fetching all tracks at once. ```python return list(self.get_iter(owner_id, album_id, access_hash)) ``` -------------------------------- ### Get Audio Tracks Iteratively Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Retrieves audio tracks for a user or album iteratively. Handles pagination by loading sections of tracks. Raises `AccessDenied` if permissions are insufficient. Requires `scrap_ids` and `scrap_tracks` helper functions. ```python response = self._vk.http.post( 'https://m.vk.com/audio', data={ 'act': 'load_section', 'owner_id': owner_id, 'playlist_id': album_id if album_id else -1, 'offset': offset, 'type': 'playlist', 'access_hash': access_hash, 'is_loading_all': 1 }, allow_redirects=False ).json() ``` ```python ids = scrap_ids( response['data'][0]['list'] ) if not ids: break yield from scrap_tracks( ids, self.user_id, self._vk.http, convert_m3u8_links=self.convert_m3u8_links, ) ``` -------------------------------- ### Get User Albums Iteratively Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Retrieves a list of user albums iteratively. Handles pagination by incrementing the offset. This method is used to fetch albums in chunks. ```python offset = 0 while True: ``` -------------------------------- ### Get Audio from Post Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Extracts audio tracks from a specific VK post. It scrapes the audio list from the post's HTML content. Ensure the `owner_id` and `post_id` are correct. ```python def get_post_audio(self, owner_id, post_id): """ Получить список аудиозаписей из поста пользователя или группы :param owner_id: ID владельца (отрицательные значения для групп) :param post_id: ID поста """ response = self._vk.http.get(f'https://m.vk.com/wall{owner_id}_{post_id}') ids = scrap_ids_from_html( response.text, filter_root_el={'class': 'audios_list'} ) return scrap_tracks( ids, self.user_id, http=self._vk.http, convert_m3u8_links=self.convert_m3u8_links, ) ``` -------------------------------- ### Initialize VkKeyboard Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/keyboard.html Constructor for VkKeyboard. Set `one_time` to True if the keyboard should disappear after use, and `inline` to True for inline keyboards. ```python class VkKeyboard(object): """ Класс для создания клавиатуры для бота (https://vk.com/dev/bots_docs_3) :param one_time: Если True, клавиатура исчезнет после нажатия на кнопку :type one_time: bool """ __slots__ = ('one_time', 'lines', 'keyboard', 'inline') def __init__(self, one_time=False, inline=False): self.one_time = one_time self.inline = inline self.lines = [[]] self.keyboard = { 'one_time': self.one_time, 'inline': self.inline, 'buttons': self.lines } ``` -------------------------------- ### Initialize VkAudio Module Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Initializes the VkAudio module with a VkApi object. It sets default cookies and loads the main VK page to establish session cookies. The `convert_m3u8_links` parameter controls whether M3U8 links are converted to MP3. ```python set_cookies_from_list(self._vk.http.cookies, self.DEFAULT_COOKIES) self._vk.http.get('https://m.vk.com/') # load cookies ``` -------------------------------- ### Captcha Exception Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/exceptions.html Handles CAPTCHA challenges, providing methods to get the image and submit an answer. ```python class Captcha(VkApiError): def __init__(self, vk, captcha_sid, func, args=None, kwargs=None, url=None): super(Captcha, self).__init__() self.vk = vk self.sid = captcha_sid self.func = func self.args = args or () self.kwargs = kwargs or {} self.code = CAPTCHA_ERROR_CODE self.key = None self.url = url self.image = None def get_url(self): """ Получить ссылку на изображение капчи """ if not self.url: self.url = f'https://api.vk.com/captcha.php?sid={self.sid}' return self.url def get_image(self): """ Получить изображение капчи (jpg) """ if not self.image: self.image = self.vk.http.get(self.get_url()).content return self.image def try_again(self, key=None): """ Отправить запрос заново с ответом капчи :param key: ответ капчи """ if key: self.key = key self.kwargs.update({ 'captcha_sid': self.sid, 'captcha_key': self.key }) return self.func(*self.args, **self.kwargs) def __str__(self): return 'Captcha needed' ``` -------------------------------- ### File Handling in VkUpload Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/upload.html This snippet demonstrates how to handle file uploads, differentiating between file-like objects and file paths. It prepares files for upload by creating tuples of filenames and file objects, ensuring proper handling of file extensions and binary read mode. ```python if hasattr(file, 'read'): f = file filename = file.name if hasattr(file, 'name') else '.jpg' else: filename = file f = open(filename, 'rb') self.opened_files.append(f) ext = filename.split('.')[-1] files.append((self.key_format.format(x), (f'file{x}.{ext}', f))) ``` ```python def close_files(self): for f in self.opened_files: f.close() self.opened_files = [] ``` -------------------------------- ### POST /al_audio.php (Upload Audio) Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Uploads a new audio file to the user or group library. ```APIDOC ## POST https://vk.com/al_audio.php ### Description Initiates and completes the upload process for an audio file. ### Method POST ### Endpoint https://vk.com/al_audio.php ### Parameters #### Request Body - **act** (string) - Required - Set to 'new_audio' or 'done_add' - **gid** (int) - Optional - Group ID (0 for user) ``` -------------------------------- ### Follow User Source: https://vk-api.readthedocs.io/en/latest/_modules/vk_api/audio.html Initiates a follow action for a specified user. This function first scrapes a necessary hash from the user's audio page and then sends a POST request to the VK API. Access to the user's audio page is required. ```python def follow_user(self, user_id): data = self._vk.http.get(f"https://vk.com/audios{user_id}") user_hash = RE_USER_AUDIO_HASH.search(data.text) if user_hash is None: raise AccessDenied(f"You don't have permissions to browse {user_id}'s audio") user_hash = user_hash.groups()[1] response = self._vk.http.post( 'https://vk.com/al_audio.php', data={ 'al': 1, 'act': 'follow_owner', 'owner_id': user_id, 'hash': user_hash, } ) return json.loads(response.text.replace('