Skip to main content

vk.com API python wrapper for asyncio

for old version of python you can use https://github.com/dimka665/vk

Features

  • asynchronous

  • support python 3.5+ versions

  • have only one dependency - aiohttp 3+

  • support two-factor authentication

  • support socks proxy with aiohttp-socks

  • support rate limit of requests

  • support Long Poll connection

TODO

  • need refactoring tests for AsyncVkExecuteRequestPool

Install

pip install aiovk

Examples

Annotation

In all the examples below, I will give only the {code}

async def func():
    {code}

loop = asyncio.get_event_loop()
loop.run_until_complete(func())

Authorization

TokenSession - if you already have token or you use requests which don’t require token

session = TokenSession()
session = TokenSession(access_token='asdf123..')

ImplicitSession - client authorization in js apps and standalone (desktop and mobile) apps

>>> session = ImplicitSession(USER_LOGIN, USER_PASSWORD, APP_ID)
>>> await session.authorize()
>>> session.access_token
asdfa2321afsdf12eadasf123...

With scopes:

ImplicitSession(USER_LOGIN, USER_PASSWORD, APP_ID, 'notify')
ImplicitSession(USER_LOGIN, USER_PASSWORD, APP_ID, 'notify,friends')
ImplicitSession(USER_LOGIN, USER_PASSWORD, APP_ID, ['notify', 'friends'])
ImplicitSession(USER_LOGIN, USER_PASSWORD, APP_ID, 3)  # notify and friends

Also you can use SimpleImplicitSessionMixin for entering confirmation code or captcha key

AuthorizationCodeSession - authorization for server apps or Open API

See https://vk.com/dev/authcode_flow_user for getting the CODE

>>> session = AuthorizationCodeSession(APP_ID, APP_SECRET, REDIRECT_URI, CODE)
>>> await session.authorize()
>>> session.access_token
asdfa2321afsdf12eadasf123...

Or:

>>> session = AuthorizationCodeSession(APP_ID, APP_SECRET, REDIRECT_URI)
>>> await session.authorize(CODE)
>>> session.access_token
asdfa2321afsdf12eadasf123...

Authorization using context manager - you won’t need to use session.close() after work

async with aiovk.TokenSession(access_token=YOUR_VK_TOKEN) as ses:
    api = API(ses)...

And your session will be closed after all done or code fail(similar to simple “with” usage) Works with all types of authorization

Drivers

HttpDriver - default driver for using aiohttp

>>> driver = HttpDriver()
>>> driver = HttpDriver(timeout=10)  # default timeout for all requests
>>> driver = ProxyDriver(PROXY_ADDRESS, PORT)  # 1234 is port
>>> driver = ProxyDriver(PROXY_ADDRESS, PORT, timeout=10)
>>> driver = ProxyDriver(PROXY_ADDRESS, PORT, PROXY_LOGIN, PROXY_PASSWORD, timeout=10)

How to use custom driver with session:

>>> session = TokenSession(..., driver=HttpDriver())

How to use driver with own loop:

>>> loop = asyncio.get_event_loop()
>>> asyncio.set_event_loop(None)
>>> session = TokenSession(driver=HttpDriver(loop=loop))  # or ProxyDriver

How to use driver with custom http session object:

Solve next problem: https://stackoverflow.com/questions/29827642/asynchronous-aiohttp-requests-fails-but-synchronous-requests-succeed

>>> connector = aiohttp.TCPConnector(verify_ssl=False)
>>> session = aiohttp.ClientSession(connector=connector)
>>> driver = HttpDriver(loop=loop, session=session)

LimitRateDriverMixin - mixin class what allow you create new drivers with speed rate limits

>>> class ExampleDriver(LimitRateDriverMixin, HttpDriver):
...     requests_per_period = 3
...     period = 1  #seconds

VK API

First variant:

>>> session = TokenSession()
>>> api = API(session)
>>> await api.users.get(user_ids=1)
[{'first_name': 'Pavel', 'last_name': 'Durov', 'id': 1}]

Second variant:

>>> session = TokenSession()
>>> api = API(session)
>>> await api('users.get', user_ids=1)
[{'first_name': 'Pavel', 'last_name': 'Durov', 'id': 1}]

Also you can add timeout argument for each request or define it in the session

See https://vk.com/dev/methods for detailed API guide.

Lazy VK API

It is useful when a bot has a large message flow

>>> session = TokenSession()
>>> api = LazyAPI(session)
>>> message = api.users.get(user_ids=1)
>>> await message()
[{'first_name': 'Pavel', 'last_name': 'Durov', 'id': 1}]

Supports both variants like API object

User Long Poll

For documentation, see: https://vk.com/dev/using_longpoll

Use exist API object

>>> api = API(session)
>>> lp = UserLongPoll(api, mode=2)  # default wait=25
>>> await lp.wait()
{"ts":1820350345,"updates":[...]}
>>> await lp.wait()
{"ts":1820351011,"updates":[...]}

Use Session object

>>> lp = UserLongPoll(session, mode=2)  # default wait=25
>>> await lp.wait()
{"ts":1820350345,"updates":[...]}
>>> await lp.get_pts()  # return pts
191231223
>>> await lp.get_pts(need_ts=True)  # return pts, ts
191231223, 1820350345

You can iterate over events

>>> async for event in lp.iter():
...     print(event)
{"type":..., "object": {...}}

Notice that wait value only for long pool connection.

Real pause could be more wait time because of need time for authorization (if needed), reconnect and etc.

Bots Long Poll

For documentation, see: https://vk.com/dev/bots_longpoll

Use exist API object

>>> api = API(session)
>>> lp = BotsLongPoll(api, group_id=1)  # default wait=25
>>> await lp.wait()
{"ts":345,"updates":[...]}
>>> await lp.wait()
{"ts":346,"updates":[...]}

Use Session object

>>> lp = BotsLongPoll(session, group_id=1)  # default wait=25
>>> await lp.wait()
{"ts":78455,"updates":[...]}
>>> await lp.get_pts()  # return pts
191231223
>>> await lp.get_pts(need_ts=True)  # return pts, ts
191231223, 1820350345

BotsLongPoll supports iterating too

>>> async for event in lp.iter():
...     print(event)
{"type":..., "object": {...}}

Notice that wait value only for long pool connection.

Real pause could be more wait time because of need time for authorization (if needed), reconnect and etc.

Async execute request pool

For documentation, see: https://vk.com/dev/execute

from aiovk.pools import AsyncVkExecuteRequestPool

async with AsyncVkExecuteRequestPool() as pool:
    response = pool.add_call('users.get', 'YOUR_TOKEN', {'user_ids': 1})
    response2 = pool.add_call('users.get', 'YOUR_TOKEN', {'user_ids': 2})
    response3 = pool.add_call('users.get', 'ANOTHER_TOKEN', {'user_ids': 1})
    response4 = pool.add_call('users.get', 'ANOTHER_TOKEN', {'user_ids': -1})

>>> print(response.ok)
True
>>> print(response.result)
[{'id': 1, 'first_name': 'Павел', 'last_name': 'Дуров'}]
>>> print(response2.result)
[{'id': 2, 'first_name': 'Александра', 'last_name': 'Владимирова'}]
>>> print(response3.result)
[{'id': 1, 'first_name': 'Павел', 'last_name': 'Дуров'}]
>>> print(response4.ok)
False
>>> print(response4.error)
{'method': 'users.get', 'error_code': 113, 'error_msg': 'Invalid user id'}

or

from aiovk.pools import AsyncVkExecuteRequestPool

pool = AsyncVkExecuteRequestPool()
response = pool.add_call('users.get', 'YOUR_TOKEN', {'user_ids': 1})
response2 = pool.add_call('users.get', 'YOUR_TOKEN', {'user_ids': 2})
response3 = pool.add_call('users.get', 'ANOTHER_TOKEN', {'user_ids': 1})
response4 = pool.add_call('users.get', 'ANOTHER_TOKEN', {'user_ids': -1})
await pool.execute()
...

Release files for aiovk 4.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for aiovk 4.1.0
File Size Uploaded
aiovk-4.1.0.tar.gz 25.0 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for aiovk 4.1.0
File Interpreter ABI Platform
aiovk-4.1.0-py3-none-any.whl Python 3 none any Details

Total release size: 48.6 kB

Release files / aiovk-4.1.0.tar.gz

Download URL aiovk-4.1.0.tar.gz
Size 25.0 kB
Tags Source
SHA-256 checksum
How to use checksums
713365a0054b30b42cd47dcd54d21af75a50e561e05f39b1bb1f88e0f4f67939
BLAKE2b-256 checksum
How to use checksums
70a29ca19811b16e0d3e71326595afd5f3f7206419abdbab7e00b012b10bad3c
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.7

Release files / aiovk-4.1.0-py3-none-any.whl

Download URL aiovk-4.1.0-py3-none-any.whl
Size 23.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
21a8a405bfc075866e3a8744d143d7421ae758dcd4185e3abfe0e2ad4b7a9a0e
BLAKE2b-256 checksum
How to use checksums
b7861ca6bd9c49f9f63164008e67f405ba1a75c8a9b81d58e98e060fbf27f35d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.9.7

Release history Release notifications | RSS feed

This release

4.1.0 This release

2 release files

4.0.0

2 release files

3.0.0

2 release files

2.2.1

1 release file

2.1.1

1 release file

2.1.0

1 release file

2.0.0

1 release file

1.3.1

1 release file

1.3.0

1 release file

1.2.2

1 release file

1.2.1

1 release file

1.2.0

1 release file

1.1.1

1 release file

1.1.0

1 release file

1.0.0

1 release file

0.5.1

1 release file

0.5.0

1 release file

0.4.0

1 release file

0.3.3

1 release file

0.3.2

1 release file

0.3.1

1 release file

0.3

1 release file

0.2

1 release file

0.1

1 release file

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page