Package: aiovk2
vk.com API python wrapper for asyncioThis is a fork ofhttps://github.com/Fahreeve/aiovkpackage which looks currently outdated and unmaintainedfor old version of python you can usehttps://github.com/dimka665/vkFeaturesasynchronoussupport python 3.5+ versionshave only one dependency -aiohttp 3+support two-factor authenticationsupport socks proxy withaiohttp-sockssupport rate limit of requestssupport Long Poll connectionTODOneed refactoring tests forAsyncVkExecuteRequestPoolInstallpipinstallaiovk2ExamplesAnnotationIn all the examples below, I will give only the{code}asyncdeffunc():{code}loop=asyncio.get_event_loop()loop.run_until_complete(func())AuthorizationTokenSession- if you already have token or you use requests which don’t require tokensession=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)>>>awaitsession.authorize()>>>session.access_tokenasdfa2321afsdf12eadasf123...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 friendsAlso you can useSimpleImplicitSessionMixinfor entering confirmation code
or captcha keyAuthorizationCodeSession- authorization for server apps or Open APISeehttps://vk.com/dev/authcode_flow_userfor getting the CODE>>>session=AuthorizationCodeSession(APP_ID,APP_SECRET,REDIRECT_URI,CODE)>>>awaitsession.authorize()>>>session.access_tokenasdfa2321afsdf12eadasf123...Or:>>>session=AuthorizationCodeSession(APP_ID,APP_SECRET,REDIRECT_URI)>>>awaitsession.authorize(CODE)>>>session.access_tokenasdfa2321afsdf12eadasf123...Authorization using context manager- you won’t need to use session.close() after workasyncwithaiovk2.TokenSession(access_token=YOUR_VK_TOKEN)asses: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 authorizationDriversHttpDriver- default driver for usingaiohttp>>>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 ProxyDriverHow 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>>>classExampleDriver(LimitRateDriverMixin,HttpDriver):...requests_per_period=3...period=1#secondsVK APIFirst variant:>>>session=TokenSession()>>>api=API(session)>>>awaitapi.users.get(user_ids=1)[{'first_name':'Pavel','last_name':'Durov','id':1}]Second variant:>>>session=TokenSession()>>>api=API(session)>>>awaitapi('users.get',user_ids=1)[{'first_name':'Pavel','last_name':'Durov','id':1}]Also you can addtimeoutargument for each request or define it in the sessionSeehttps://vk.com/dev/methodsfor detailed API guide.Lazy VK APIIt is useful when a bot has a large message flow>>>session=TokenSession()>>>api=LazyAPI(session)>>>message=api.users.get(user_ids=1)>>>awaitmessage()[{'first_name':'Pavel','last_name':'Durov','id':1}]Supports both variants like API objectUser Long PollFor documentation, see:https://vk.com/dev/using_longpollUse exist API object>>>api=API(session)>>>lp=UserLongPoll(api,mode=2)# default wait=25>>>awaitlp.wait(){"ts":1820350345,"updates":[...]}>>>awaitlp.wait(){"ts":1820351011,"updates":[...]}Use Session object>>>lp=UserLongPoll(session,mode=2)# default wait=25>>>awaitlp.wait(){"ts":1820350345,"updates":[...]}>>>awaitlp.get_pts()# return pts191231223>>>awaitlp.get_pts(need_ts=True)# return pts, ts191231223,1820350345You can iterate over events>>>asyncforeventinlp.iter():...print(event){"type":...,"object":{...}}Notice thatwaitvalue only for long pool connection.Real pause could be morewaittime because of need time
for authorization (if needed), reconnect and etc.Bots Long PollFor documentation, see:https://vk.com/dev/bots_longpollUse exist API object>>>api=API(session)>>>lp=BotsLongPoll(api,group_id=1)# default wait=25>>>awaitlp.wait(){"ts":345,"updates":[...]}>>>awaitlp.wait(){"ts":346,"updates":[...]}Use Session object>>>lp=BotsLongPoll(session,group_id=1)# default wait=25>>>awaitlp.wait(){"ts":78455,"updates":[...]}>>>awaitlp.get_pts()# return pts191231223>>>awaitlp.get_pts(need_ts=True)# return pts, ts191231223,1820350345BotsLongPoll supports iterating too>>>asyncforeventinlp.iter():...print(event){"type":...,"object":{...}}Notice thatwaitvalue only for long pool connection.Real pause could be morewaittime because of need time
for authorization (if needed), reconnect and etc.Async execute request poolFor documentation, see:https://vk.com/dev/executefromaiovk2.poolsimportAsyncVkExecuteRequestPoolasyncwithAsyncVkExecuteRequestPool()aspool: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'}orfromaiovk2.poolsimportAsyncVkExecuteRequestPoolpool=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})awaitpool.execute()...