- VkTools¶
- VkApi (основной класс)¶
- Usage
- vk.API
- vk.UserAPI
- vk.DirectUserAPI
- vk.CommunityAPI
- Saved searches
- Use saved searches to filter your results more quickly
- License
- python273/vk_api
- Name already in use
- Sign In Required
- Launching GitHub Desktop
- Launching GitHub Desktop
- Launching Xcode
- Launching Visual Studio Code
- Latest commit
- Git stats
- Files
- README.md
- About
VkTools¶
Использовать только если нужно загрузить все объекты в память.
Eсли вы можете обрабатывать объекты по частям, то лучше использовать get_all_iter
Например если вы записываете объекты в БД, то нет смысла загружать все данные в память
get_all_slow_iter ( method , max_count , values = None , key = ‘items’ , limit = None , stop_fn = None , negative_offset = False ) [source] ¶
Получить все элементы (без использования execute)
Работает в методах, где в ответе есть count и items или users
- method (str) – имя метода
- max_count (int) – максимальное количество элементов, которое можно получить за один запрос
- values (dict) – параметры
- key (str) – ключ элементов, которые нужно получить
- limit (int) – ограничение на количество получаемых элементов, но может прийти больше
- stop_fn (func) – функция, отвечающая за выход из цикла
- negative_offset (bool) – True если offset должен быть отрицательный
Использовать только если нужно загрузить все объекты в память.
Eсли вы можете обрабатывать объекты по частям, то лучше использовать get_all_slow_iter
Например если вы записываете объекты в БД, то нет смысла загружать все данные в память
VkApi (основной класс)¶
too_many_rps_handler ( error ) [source] ¶ Обработчик ошибки “Слишком много запросов в секунду”.
Ждет полсекунды и пробует отправить запрос заново
error – исключение
Обработчик двухфакторной аутентификации
Позволяет обращаться к методам API как к обычным классам. Например vk.wall.get(…)
method ( method , values = None , captcha_sid = None , captcha_key = None , raw = False ) [source] ¶
- method (str) – название метода
- values (dict) – параметры
- captcha_sid – id капчи
- captcha_key (str) – ответ капчи
- raw (bool) – при False возвращает response[‘response’] при True возвращает response (может понадобиться для метода execute для получения execute_errors)
Перечисление прав пользователя. Список прав получается побитовым сложением (x | y) каждого права. Подробнее в документации VK API: https://vk.com/dev/permissions
Пользователь разрешил отправлять ему уведомления (для flash/iframe-приложений). Не работает с этой библиотекой.
Доступ к аудиозаписям. При отсутствии доступа к закрытому API аудиозаписей это право позволяет только загрузку аудио.
Добавление ссылки на приложение в меню слева.
Доступ к статусу пользователя.
Доступ к заметкам пользователя.
Доступ к расширенным методам работы с сообщениями.
Доступ к обычным и расширенным методам работы со стеной.
Доступ к расширенным методам работы с рекламным API.
Доступ к API в любое время. Рекомендуется при работе с этой библиотекой.
Доступ к группам пользователя.
Доступ к оповещениям об ответах пользователю.
Доступ к статистике групп и приложений пользователя, администратором которых он является.
Доступ к email пользователя.
Usage
Several types of APIs are implemented in this module. Each of them is needed for certain purposes, but they are all united by the way of accessing the VK API. After initializing the class, you can call any method. Let’s try to figure out what’s going on here:
>>> import vk >>> api = vk.API(access_token='. ', v='5.131') >>> print(api.users.get(user_ids=1)) []
It gets user info with user id equal to 1. vk.api.APINamespace object is used to create API request and send it via original vk.session.API class object (or another), which in turn, manages access token, sends API request, gets JSON response, parses and returns it.
vk.API
The simplest VK API implementation. Can process any API method that can be called from the server
- access_token (Optional[str]) – Access token for API requests obtained by any means (see documentation ). Optional when using InteractiveMixin
- **kwargs (any) – Additional parameters, which will be passed to each request. The most useful is v — API version and lang — language of responses (see documentation )
>>> import vk >>> api = vk.API(access_token='. ', v='5.131') >>> print(api.users.get(user_ids=1)) []
vk.UserAPI
Subclass of vk.session.API . It differs only in that it can get access token using user credentials (Implicit flow authorization).
This implementation uses the web version of VK to log in and receive cookies, and then obtains an access token through Implicit flow authorization. In the future, VK may change the approach to authorization (for example, replace it with VK ID) and maintaining operability will become quite a difficult task, and most likely it will be deprecated. Use vk.session.DirectUserAPI instead
- user_login (Optional[str]) – User login, optional when using InteractiveMixin
- user_password (Optional[str]) – User password, optional when using InteractiveMixin
- client_id (Optional[int]) – ID of the application to authorize with, defaults to “VK Admin” app ID
- scope (Optional[Union[str,int]]) – Access rights you need. Can be passed comma-separated list of scopes, or bitmask sum all of them (see official documentation). Defaults to ‘offline’
- **kwargs (any) – Additional parameters, which will be passed to each request. The most useful is v — API version and lang — language of responses (see documentation )
>>> import vk >>> api = vk.UserAPI( . user_login='. ', . user_password='. ', . scope='offline,wall', . v='5.131' . ) >>> print(api.users.get(user_ids=1)) []
Callback to retrieve authentication check code (if account supports 2FA). Default behavior is to raise exception, redefine in a subclass
The authentication check code can be obtained in the sent SMS, using Google Authenticator (or another authenticator), or it can be one of ten backup codes
vk.DirectUserAPI
Subclass of vk.session.UserAPI . Can get access token using user credentials (through Direct authorization).
Necessary data (client_id and client_secret) from other official applications
- user_login (Optional[str]) – User login, optional when using InteractiveMixin
- user_password (Optional[str]) – User password, optional when using InteractiveMixin
- client_id (Optional[int]) – ID of the official application, defaults to “VK for Android” app ID
- client_secret (Optional[str]) – Client secret of the official application, defaults to client secret of “VK for Android” app
- scope (Optional[Union[str,int]]) – Access rights you need. Can be passed comma-separated list of scopes, or bitmask sum all of them (see official documentation). Defaults to ‘offline’
- **kwargs (any) – Additional parameters, which will be passed to each request. The most useful is v — API version and lang — language of responses (see documentation )
>>> import vk >>> api = vk.DirectUserAPI( . user_login='. ', . user_password='. ', . scope='offline,wall', . v='5.131' . ) >>> print(api.users.get(user_ids=1)) []
vk.CommunityAPI
Subclass of vk.session.UserAPI . Can get community access token using user credentials (Implicit flow authorization for communities). To select a community on behalf of which to make request to the API method, you can pass the group_id param (defaults to the first community from the passed list)
This implementation uses the web version of VK to log in and receive cookies, and then obtains an access tokens through Implicit flow authorization for communities. In the future, VK may change the approach to authorization (for example, replace it with VK ID) and maintaining operability will become quite a difficult task, and most likely it will be deprecated.
You can create a group token on the management page: Community -> Management -> Working with API -> Access Tokens -> Create a token (bonus — the token has no expiration date)
- user_login (Optional[str]) – User login, optional when using InteractiveMixin
- user_password (Optional[str]) – User password, optional when using InteractiveMixin
- group_ids (List[int]) – List of community IDs to be authorized
- client_id (Optional[int]) – ID of the application to authorize with, defaults to “VK Admin” app ID
- scope (Optional[Union[str,int]]) – Access rights you need. Can be passed comma-separated list of scopes, or bitmask sum all of them (see official documentation). Defaults to None . Be careful, only manage, messages, photos, docs, wall and stories are available for communities
- **kwargs (any) – Additional parameters, which will be passed to each request. The most useful is v — API version and lang — language of responses (see documentation )
>>> import vk >>> api = vk.CommunityAPI( . user_login='. ', . user_password='. ', . group_ids=[123456, 654321], . scope='messages', . v='5.131' . ) >>> print(api.users.get(user_ids=1)) [] >>> print(api.users.get(group_id=654321, user_ids=1)) []
© Copyright 2015, Dmitry Voronin. Revision c3cfe06e .
Saved searches
Use saved searches to filter your results more quickly
You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.
Модуль для создания скриптов для ВКонтакте | vk.com API wrapper
License
python273/vk_api
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Name already in use
A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
vk_api – Python модуль для создания скриптов для ВКонтакте (vk.com API wrapper)
python3 -m pip install vk_api
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!'))
About
Модуль для создания скриптов для ВКонтакте | vk.com API wrapper