vk-api Python Wrapper
vk-api is a Python module designed for creating scripts and interacting with the VK (Vkontakte) social network's API. It provides a convenient wrapper around the VK API, simplifying authentication and method calls. The library is actively maintained, with frequent releases primarily addressing authentication stability and minor bug fixes.
Warnings
- gotcha Direct authentication with phone number and password (`vk_api.VkApi(login, password).auth()`) is prone to frequent issues due to VK's evolving security measures, including 2FA, CAPTCHAs, and non-Latin password handling. It's often unstable across minor versions.
- breaking Dependencies `six` and `enum34` were removed. If your project implicitly relied on `vk-api` to pull these in, you might encounter `ModuleNotFoundError` if they are not otherwise present in your environment.
- gotcha Using phone number and password directly in your code (especially in production environments or public repositories) is a security risk. It exposes sensitive user credentials.
- gotcha There is another Python library for VK API interaction named 'vk' (lowercase). Using `import vk` will import that library, which has a different API and documentation, leading to confusion and `AttributeError`s if you expect `vk-api`'s functionality.
Install
-
pip install vk_api
Imports
- VkApi
from vk_api import VkApi
- VkLongPoll
from vk_api.longpoll import VkLongPoll
- VkEventType
from vk_api.longpoll import VkEventType
- vk_api
import vk_api
Quickstart
import os
import vk_api
login = os.environ.get('VK_LOGIN', '+71234567890') # Use environment variables for sensitive data
password = os.environ.get('VK_PASSWORD', 'your_password')
try:
vk_session = vk_api.VkApi(login, password)
vk_session.auth() # Authenticate with VK
vk = vk_session.get_api() # Get the API object
# Example: Post a message to the wall
# In a real application, ensure the user_id is correct and permissions are granted.
response = vk.wall.post(message='Hello from vk-api!')
print(f"Post successful! Post ID: {response['post_id']}")
except vk_api.AuthError as error_msg:
print(f"Authentication failed: {error_msg}")
except Exception as e:
print(f"An error occurred: {e}")