T
T
toha_man2019-02-09 20:51:17
Python
toha_man, 2019-02-09 20:51:17

How to make a permanent connection to LongPoll VK when it breaks?

I wrote a simple script for personal needs in python using api from VK - LongPoll.
It works as it should, but the problem is that after a while the contact cuts it off.
I listen to new events like this:

for event in longpoll.listen():
       далее код

After some time, I get an exit from the script and a message:
requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'Удаленный хост принудительно разорвал существующее подключение', None, 10054, None))

I connect like this:
session = requests.Session()
login, password = ####

vk_session = vk_api.VkApi(login, password)
try:
  vk_session.auth(token_only=True)
  print('auth successful... proceed')
except vk_api.AuthError as error_msg:
  print(error_msg)

What construction should be used to organize the code so that it works forever))))?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Dmitry Shitskov, 2019-02-09
@toha_man

It seems to me something like this:

for event in longpoll.listen():
  try:
    далее код
  except requests.exceptions.ConnectionResetError:
    тут вызов функции для попытки повторного подключения

Y
Yar Rick, 2019-02-09
@Yar_Rick

It is a mistake to think that Long Poll is an "eternal connection", it is not. The server keeps the connection for some time, for example 30 seconds, and if no events have happened during this period, it resets it. If the event happened, then the connection is closed with a response. Therefore, you must try to connect again - either after receiving the event, or after the timeout has expired. This moment is described in the VK documentation, and you can also specify a timeout using the parameter. They recommend 25 seconds as most proxies drop the connection after 30 seconds. More details here - https://vk.com/dev/bots_longpoll

Z
Zacher, 2021-05-13
@Zacher

for event in longpoll.listen():
when you set wait 25, the list of events is empty, as a result, the for loop is not started, and the longpoll is restarted
. This happens until a new event appears, for example, a new message, but why does a ban arrive after it I don't understand either. Do you have a solution for this problem? I have the same...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question