kylmakalle / tgvkbot Goto Github PK
View Code? Open in Web Editor NEWОбщайтесь в VK через Telegram бота
Home Page: https://akentev.com/tgvkbot
License: Other
Общайтесь в VK через Telegram бота
Home Page: https://akentev.com/tgvkbot
License: Other
Еще бы помимо текста отправлять бы вложения, вообще было бы супер)
Для обработки сообщений из VK используется vk_messages.py, где реализован запрос к messages.getLongPollHistory с таймаутом в 3 секунды. Это влечёт за собой создание такого вот exception
{"ts":1820350874,"updates":[[4,1619489,561,123456,1464958914," ... ","hello" ....
придётся парсить и раскидывать по словарям, которые возвращает messages.getLongPollHistory
class VkMessage:
def __init__(self, token):
self.session = get_session(token)
self.ts, self.pts, self.server, self.key = get_tses(self.session)
def get_new_messages(self):
api = vk.API(self.session)
session = requests.Session()
new = session.get('https://{}?act=a_check&key={}&ts={}&wait=25&mode=32&version=2'.format(
self.server, self.key, self.ts))
self.ts = new.json()['ts']
def get_session(token):
return vk.Session(access_token=token)
def get_tses(session):
api = vk.API(session)
ts = api.messages.getLongPollServer(need_pts=1)
return ts['ts'], ts['pts'], ts['server'], ts['key']
Использовать альтернативную библиотеку для LongPolling. Некоторые элементы возвращаемых JSON-словарей не соответствуют тем, что есть от messages.getLongPollHistory
Использовать альтернативную библиотеку взаимодействия с VK для ВСЕГО проекта.
Было бы здорово, если вы использовали функциональность гитхаба Release - удобно подписываться на анонсы релизов в одном месте через кнопку watch.
https://docs.github.com/en/repositories/releasing-projects-on-github/about-releases
В какой-то момент бот перестаёт отправлять сообщения из Телеграмм в ВК в групповом чате куда он добавлен. В логах повторяющееся сообщение:
WARNING:vk_messages:Longpoll id 1: {'ts': 1723203814, 'updates': []}
Встречал такое "залипание" уже несколько раз, меняется ID сообщения но и всё. Полистал лог назад, время возникновения ошибки непонятно, повторяющиеся сообщения как выше начинаются с:
DEBUG:aiogram:Make request: 'getUpdates' with data: {'timeout': 20, 'offset': 704602229} and files {} DEBUG:aiogram:Response for getUpdates: [200] {"ok":true,"result":[]} DEBUG:aiogram:Make request: 'getUpdates' with data: {'timeout': 20, 'offset': 704602229} and files {} WARNING:vk_messages:Longpoll id 1: {'ts': 1679087997, 'updates': []} DEBUG:aiogram:Response for getUpdates: [200] {"ok":true,"result":[]} DEBUG:aiogram:Make request: 'getUpdates' with data: {'timeout': 20, 'offset': 704602229} and files {} WARNING:vk_messages:Longpoll id 1: {'ts': 1679087997, 'updates': []} DEBUG:aiogram:Response for getUpdates: [502] {"ok":false,"error_code":502,"description":"Bad Gateway"} WARNING:aiogram.dispatcher:Polling is stopped. ERROR:asyncio:Task exception was never retrieved future: <Task finished coro=<Dispatcher.start_polling() done, defined at /root/.local/lib/python3.6/site-packages/aiogram/dispatcher/__init__.py:214> exception=TelegramAPIError('Bad Gateway',)> Traceback (most recent call last): File "/root/.local/lib/python3.6/site-packages/aiogram/dispatcher/__init__.py", line 243, in start_polling updates = await self.bot.get_updates(limit=limit, offset=offset, timeout=timeout) File "/root/.local/lib/python3.6/site-packages/aiogram/bot/bot.py", line 83, in get_updates result = await self.request(api.Methods.GET_UPDATES, payload) File "/root/.local/lib/python3.6/site-packages/aiogram/bot/base.py", line 136, in request proxy=self.proxy, proxy_auth=self.proxy_auth) File "/root/.local/lib/python3.6/site-packages/aiogram/bot/api.py", line 195, in request return await _check_result(method, response) File "/root/.local/lib/python3.6/site-packages/aiogram/bot/api.py", line 119, in _check_result raise exceptions.TelegramAPIError(description) aiogram.utils.exceptions.TelegramAPIError: Bad Gateway WARNING:vk_messages:Longpoll id 1: {'ts': 1679087997, 'updates': []} WARNING:vk_messages:Longpoll id 1: {'ts': 1679087997, 'updates': []} WARNING:vk_messages:Longpoll id 1: {'ts': 1679087997, 'updates': []}
Я так понимаю 200 это ок а вот после получения 502 начинаются проблемы. Я видел что недавно был коммит на обновление:
tgvkbot#37 Bump pillow from 5.1.0 to 9.0.1 (https://github.com/Kylmakalle/tgvkbot/pull/37#issuecomment-1322934680)
но у меня Докер установка и хотя в описании бота указано что
на всякий случай фиксируются версии каждого коммита
образ Докер последний раз обновлялся 4 месяца назад.
Проблема с кодировкой
SyntaxError: Non-ASCII character '\xe2' in file bot.py on line 39, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details
Как исправить?
Есть инструкция, как запустить в windows?
Чтобы проверить работу бота после кастомизации
В инете не могу что-то найти..
Единственное что надо это вставить ссылку с токеном в чат с ботом. Можно считать что бот универсальный! Проверьте, пожалуйста. И простите за мой русский, не родной)
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.