alexanderlarin / aiovk Goto Github PK
View Code? Open in Web Editor NEWvk.com API python wrapper for asyncio
License: MIT License
vk.com API python wrapper for asyncio
License: MIT License
After last update sessions aren't closed on exit.
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000020C195185F8>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000020C182A74E0>, 2362379.765)]']
connector: <aiohttp.connector.TCPConnector object at 0x0000020C19518630>
It is because in new version driver.close
method isn't called anymore in close
method of BaseSession
.
It's better to give user way to choose http backend on session create. Probably this should be oriented on requests/aiohttp api, since they are pretty common. So, the way is like user create session with proxy/optoins and pass it to the library. You can take a look at https://github.com/pohmelie/aiotelegram and json_provider
it's a bit like what you need to be independent of http libraries api.
Бот с Bots Long Poll не принимает сообщения из чатов, в которые он был приглашен. Только через упоминание (@) и сообщения сообщества. Права выданы, все настроено.
Каким образом получать сообщения? Не понятно.
При возникновении ошибки invalid keyboard. Почему то возвращается UnknownVKException вместе с Traceback вместо VkAPIError.
То, что возращает aiovk ниже.
"['Traceback (most recent call last):',
' File "/app/src/sender/mailings/vk.py", line 131, in send_api_requestn response = await super().send_api_request(*args, **kwargs)',
' File "/usr/local/lib/python3.6/site-packages/aiovk/sessions.py", line 92, in send_api_request raise VkAPIError(error, self.REQUEST_URL + method_name)',
'aiovk.exceptions.VkAPIError: ({'error_code': 911, 'error_msg': 'Keyboard format is invalid',
'request_params':
[
{'key': 'oauth', 'value': '1'},
{'key': 'method', 'value': 'messages.send'},
{'key': 'user_ids', 'value': 'some user ids,some user ids'},
{'key': 'attachment', 'value': ''},
{'key': 'random_id', 'value': '50000001'},
{'key': 'keyboard', 'value':
'{"buttons": [[{"color": "negative", "action": {"t": "text", "label": "YEAP", "payload": "{"button": "1"}"}}, {"color": "positive", "action": {"type": "text", "label": "KEK", "payload": "{"button": "2"}"}}], [{"color": "default", "action": {"type": "text", "label": "ROCHITA", "payload": "{"button": "3"}"}}, {"color": "primary", "action": {"type": "text", "label": "Blue", "payload": "{"button": "4"}"}}]], "one_time": true}'},
{'key': 'v', 'value': '5.74'}]},
'https://api.vk.com/method/messages.send')'
]
aiohttp.ClientSession.get вызванный в drivers.py:76 нарезает параметр code в лапшу по точке с запятой. в результате VK возвращет ошибку
...'error_msg': "Unable to compile code: ';' expected, '' found in line 1",...
Co следующей ошибкой:
Downloading/unpacking aiovk
Downloading aiovk-0.2.tar.gz
Running setup.py (path:/tmp/pip_build_root/aiovk/setup.py) egg_info for package aiovk
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip_build_root/aiovk/setup.py", line 5, in <module>
version=__import__('aiovk').__version__,
File "aiovk/__init__.py", line 1, in <module>
from aiovk.sessions import ImplicitSession, TokenSession, AuthorizationCodeSession
File "aiovk/sessions.py", line 21
async def json(self, url, params, timeout=None):
^
SyntaxError: invalid syntax
Complete output from command python setup.py egg_info:
Traceback (most recent call last):
File "<string>", line 17, in <module>
File "/tmp/pip_build_root/aiovk/setup.py", line 5, in <module>
version=__import__('aiovk').__version__,
File "aiovk/__init__.py", line 1, in <module>
from aiovk.sessions import ImplicitSession, TokenSession, AuthorizationCodeSession
File "aiovk/sessions.py", line 21
async def json(self, url, params, timeout=None):
^
SyntaxError: invalid syntax
Уже который день пытаюсь запустить программу и ничего не получается (на данный момент вариант взят из вопросов):
import asyncio
from aiovk import API
from aiovk import ImplicitSession
from aiovk.drivers import HttpDriver
from aiovk.mixins import LimitRateDriverMixin
class ExampleDriver(LimitRateDriverMixin, HttpDriver):
requests_per_period = 3
period = 1 # seconds
async def main():
session = ImplicitSession("**Login**", "**Pwd**", Id, driver=ExampleDriver())
api = API(session)
a = await api.users.get(user_ids=1)
await session.close()
print(a)
return a
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
Всегда выбрасывает такую или подобную ошибку:
"C:\Program Files (x86)\Python37-32\python.exe" C:/Users/v8902/YandexDisk/Projects/VK-ESchool/__main__.py
Traceback (most recent call last):
File "C:/Users/v8902/YandexDisk/Projects/VK-ESchool/__main__.py", line 23, in <module>
loop.run_until_complete(main())
File "C:\Program Files (x86)\Python37-32\lib\asyncio\base_events.py", line 568, in run_until_complete
return future.result()
File "C:/Users/v8902/YandexDisk/Projects/VK-ESchool/__main__.py", line 17, in main
a = await api.users.get(user_ids=1)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiovk\api.py", line 31, in __call__
timeout,
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiovk\sessions.py", line 72, in send_api_request
response = await self.driver.json(self.REQUEST_URL + method_name, params, timeout)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiovk\utils.py", line 28, in wrapper
return await func(self, *args, **kwargs)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiovk\mixins.py", line 14, in json
return await super().json(*args, **kwargs)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiovk\drivers.py", line 79, in json
async with self.session.get(url, params=params, timeout=timeout or self.timeout) as response:
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiohttp\client.py", line 932, in __aenter__
self._resp = await self._coro
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiohttp\client.py", line 424, in _request
await resp.start(conn)
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiovk\drivers.py", line 21, in start
await super().start(connection, read_until_eof)
TypeError: start() takes 2 positional arguments but 3 were given
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x045550B0>
Task exception was never retrieved
future: <Task finished coro=<ClientRequest.write_bytes() done, defined at C:\Program Files (x86)\Python37-32\lib\site-packages\aiohttp\client_reqrep.py:515> exception=AssertionError()>
Traceback (most recent call last):
File "C:\Program Files (x86)\Python37-32\lib\site-packages\aiohttp\client_reqrep.py", line 524, in write_bytes
assert protocol is not None
AssertionError
Process finished with exit code 1
Что я делаю не так?
Версия Python 3.7
aiovk.exceptions.VkAPIError: ({'error_code': 8, 'error_msg': 'Invalid request: versions below 5.81 are deprecated. Version param should be passed as "v". "version" param is invalid and not supported. For more information go to https://vk.com/dev/constant_version_updates', 'request_params': [{'key': 'method', 'value': 'groups.getLongPollServer'}, {'key': 'oauth', 'value': '1'}, {'key': 'group_id', 'value': '206184278'}, {'key': 'v', 'value': '5.74'}]}, 'https://api.vk.com/method/groups.getLongPollServer')
Возникает при вызове longpoll.wait()
https://vk.com/dev/service_token
В aiovk уже есть этот функционал? Если нет, можно ли его добавить?
Traceback (most recent call last):
File "/usr/lib/python3.5/asyncio/tasks.py", line 239, in _step
result = coro.send(None)
File "/home/tiber/LOLBot/vkplus.py", line 85, in dispatcher
r = await coro
File "/usr/local/lib/python3.5/dist-packages/aiovk-0.3.3-py3.5.egg/aiovk/api.py", line 9, in call
return await getattr(self, method_name)(**method_kwargs)
File "/usr/local/lib/python3.5/dist-packages/aiovk-0.3.3-py3.5.egg/aiovk/api.py", line 25, in call
return await self._api._session.make_request(self, timeout)
File "/usr/local/lib/python3.5/dist-packages/aiovk-0.3.3-py3.5.egg/aiovk/sessions.py", line 24, in make_request
return await self.send_api_request(method_request._method_name, params, timeout)
File "/usr/local/lib/python3.5/dist-packages/aiovk-0.3.3-py3.5.egg/aiovk/sessions.py", line 52, in send_api_request
return response['response']
KeyError: 'response'
Параметры, с которыми вызывалась функция:
METHOD messages.get
PARAMS {'access_token': '608a2afedc7e06346***84b3ec9bc5c719eb961961133804a9404526084903aaaea1300c29fcacb574051', 'filters': 0, 'last_message_id': 0, 'time_offset': 60, 'out': 0, 'v': '5.52', 'offset': 0, 'count': 20, 'preview_length': 0}
В response было {'items': [], 'count': 28205}
Hello,
I'm getting an error while sending a message:
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html'
This happens when I try to send a long complex message with either escaped or non escaped symbols.
Seems to me it is related to aiohttp warning about mimetype, as stated in some similar issues on stackoverflow https://stackoverflow.com/questions/48840378/python-attempt-to-decode-json-with-unexpected-mimetype
Could be nice if you could suggest some workaround on this issue.
Thanks,
Ivan
As read_until_eof
was removed in this commit nothing works with latest aiohttp
because of https://github.com/Fahreeve/aiovk/blob/master/aiovk/drivers.py#L21
await super().start(connection, read_until_eof)
TypeError: start() takes 2 positional arguments but 3 were given
Library simply doesn't work with login and password.. A lot of exceptions, but the main thing:
https://github.com/Fahreeve/aiovk/blob/master/aiovk/sessions.py#L80
Look at this broken code
authorise should be authorize, for example
Приветствую!
А есть поддержка Bots Long Poll API?
Заранее спасибо!
https://pastebin.com/kwhuKzbJ
this is my keyboard
https://pastebin.com/mfCEcLte
this is traceback
I am trying to pass this keyboard to user but i get this error.
Also I tried to pass content-type = None in the file aiovk/drivers.py on line 52 to the json method, but this did not solve the problem.
Trying to send keyboard, there is an error 'vk_api.exceptions.ApiError: [100] One of the parameters specified was missing or invalid: keyboard contains incorrect JSON' even if I send empty one.
I found nothing about this error in the internet and documentation. Also I tried, to send keyboard from examples, the same error.
https://vk.com/dev/using_longpoll может помочь при получении новых событий (добавили в друзья, написали в ЛС). Можно ли как-то реализовать это с помощью aiovk?
Hi! Thank you for this package !
But when i try send simple message like this
.api.messages.send(
user_ids=uids,
message=message_text,
attachment=attachments,
random_id=some_random_id)
Message send OK.
But when i try send with keyboard(keyboard in vk api) like this
.api.messages.send(
user_ids=uids,
message=message_text,
attachment=attachments,
random_id=some_random_id,
keyboard=keyboard_from_api_example)
#type of keyboard_from_api_example is str
message did't send or show previous keyboard.
I try send similar request over postman. All done ok.
Can you help me ?
Hi!
Something strange happen when ImplicitSession tried to re-authorize
I used phone/password credentials and auth url is empty in this case
The stack is:
Traceback (most recent call last):
File "/home/user/bot/bot.py", line 197, in watch_update_posts
await walk_wall_posts(api, store, owner_id, max_posts_offset=30)
File "/home/user/bot/vk.py", line 41, in walk_wall_posts
items, count = await get_wall_posts(api, owner_id=owner_id, offset=offset, limit=posts_per_request_limit)
File "/home/user/venv/lib/python3.7/site-packages/backoff/_async.py", line 131, in retry
ret = await target(*args, **kwargs)
File "/home/user/bot/vk.py", line 29, in get_wall_posts
response = await api.wall.get(owner_id=owner_id, offset=offset, count=limit, extended=0, filter='all')
File "/home/user/venv/lib/python3.7/site-packages/aiovk/api.py", line 31, in call
timeout,
File "/home/user/venv/lib/python3.7/site-packages/aiovk/sessions.py", line 90, in send_api_request
await self.authorize()
File "/home/user/venv/lib/python3.7/site-packages/aiovk/sessions.py", line 154, in authorize
url, html = await self._process_auth_form(html)
File "/home/user/venv/lib/python3.7/site-packages/aiovk/sessions.py", line 224, in _process_auth_form
url, html = await self.driver.post_text(form_url, form_data)
File "/home/user/venv/lib/python3.7/site-packages/aiovk/drivers.py", line 69, in post_text
async with self.session.post(url, data=data, timeout=timeout or self.timeout) as response:
File "/home/user/venv/lib/python3.7/site-packages/aiohttp/client.py", line 1005, in aenter
self._resp = await self._coro
File "/home/user/venv/lib/python3.7/site-packages/aiohttp/client.py", line 466, in _request
ssl=ssl, proxy_headers=proxy_headers, traces=traces)
File "/home/user/venv/lib/python3.7/site-packages/aiohttp/client_reqrep.py", line 286, in init
self.update_host(url)
File "/home/user/venv/lib/python3.7/site-packages/aiohttp/client_reqrep.py", line 340, in update_host
raise InvalidURL(url)
aiohttp.client_exceptions.InvalidURL
If we send api request, we can catch strange error:
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html', url='*long url*'
I found out, it was caused by an http error 414 Request-URI Too Long
. There already was issue about this error (#41), but I think proper solution is to raise VkAPIError somewhere. I don't really know where to put it, that's why I can't just create PR. Any help?
AsyncVkExecuteRequestPool wall.get method with extended=1 adds 'groups' elements from previous call to the next.
Code:
import aiovk
from aiovk.pools import AsyncVkExecuteRequestPool
async def f():
pool = AsyncVkExecuteRequestPool()
resp = pool.add_call('wall.get', token, {'owner_id': -29534144, 'count': 1, 'extended': 1, 'v': '5.130'})
resp1 = pool.add_call('wall.get', token, {'owner_id': -125004421, 'count': 1, 'extended': 1, 'v': '5.130'})
await pool.execute()
print(resp.result['groups'])
print(resp1.result['groups'])
if __name__ == '__main__':
asyncio.run(f())
Output: https://pastebin.com/RP9A4d42
The output from https://vk.com/dev/wall.get for the second owner_id:
Whereas if I switch calls' places:
import asyncio
import aiovk
from aiovk.pools import AsyncVkExecuteRequestPool
async def f():
pool = AsyncVkExecuteRequestPool()
resp1 = pool.add_call('wall.get', token, {'owner_id': -125004421, 'count': 1, 'extended': 1, 'v': '5.130'})
resp = pool.add_call('wall.get', token, {'owner_id': -29534144, 'count': 1, 'extended': 1, 'v': '5.130'})
await pool.execute()
print(resp1.result['groups'])
print(resp.result['groups'])
if __name__ == '__main__':
asyncio.run(f())
the output would be https://pastebin.com/772TRsUX
But using the https://vk.com/dev/wall.get
or is it supposed to work that way..?
Привет! Боюсь показаться глупым, но у меня ничего не получается уже весь день :(
Беру код из примера. Он же работал у меня пару месяцев назад
async def func():
session = aiovk.ImplicitSession(vk_login, vk_pass, APP_ID, 'video,offline')
await session.authorize()
print(session.access_token)
session.close()
loop = asyncio.get_event_loop()
loop.run_until_complete(func())
и получаю кучу ошибок и не знаю что с этим делать
На строку с session.close()
ругается "RuntimeWarning: coroutine 'BaseSession.close' was never awaited
"
Зачем-то написал await session.close()
(потому что session.close is now awaitable) - не помогло.
Причем токен-то выводит принтом
Еще я узнаю что я:
session.close() ERROR:asyncio:Unclosed client session client_session: <aiohttp.client.ClientSession object at 0x066E62F0> ERROR:asyncio:Unclosed connector connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x069CCEF0>, 228423.625)]', '[(<aiohttp.client_proto.ResponseHandler object at 0x05A0CB70>, 228423.64)]'] connector: <aiohttp.connector.TCPConnector object at 0x066E6310>
Попробовал еще сделать async with aiovk.TokenSession(access_token=token) as ses:
но он вообще говорит, что не ожидал увидеть тут async
.
Заранее прошу прощения за глупые вопросы и ваше потраченное время, я только учусь
driver = aiovk.drivers.Socks5Driver('94.177.240.24', 1189)
Выдаёт мне ошибку
File "test.py", line 18, in <module> loop.run_until_complete(login()) File "/usr/local/Cellar/python3/3.6.1/Frameworks/Python.framework/Versions/3.6/lib/python3.6/asyncio/base_events.py", line 466, in run_until_complete return future.result() File "test.py", line 8, in login driver = aiovk.drivers.Socks5Driver('94.240.24', 1189) File "/usr/local/lib/python3.6/site-packages/aiovk/drivers.py", line 110, in __init__ conn = self.connector(proxy=addr, proxy_auth=auth, loop=loop) TypeError: __init__() got an unexpected keyword argument 'proxy'
Дело в том, что установочный скрипт импортирует aiovk для того, чтобы узнать версию, но aiovk, в свою очередь, импортирует aiohttp до его установки, и установка не проходит
Нужно добавить ограничение на кол-во запросов в секунду (~3 запроса).
Так будет проще делать сложные боты для VK
После каждого запроса получаю:
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f705e376390>
Как можно закрыть aiohttp сессию?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.