Bot polling telebot ошибка

Делал большой проект на Python3, Телеграмм бот с множеством функций, из-за скудности багажа знаний и (как я понял это необходимо) кошелька на сервера использовал bot.polling() (Использую pyTelegramBotAPI) и буквально через пол часа бот падает. написал обычного бота для теста отклика через время, думая что перегрузил проект, но нет, в самом деле падает, код:

import telebot
import extras


bot = telebot.TeleBot(extras.token)


@bot.message_handler(content_types="text")
def handler_text(message):
    bot.send_message(message.from_user.id, 'Все ещё в деле')

bot.polling(none_stop=True)

Ошибка в консоли:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagestelebotutil.py", line 58, in run
    task(*args, **kwargs)
  File "D:/Python/test.py", line 10, in handler_text
    bot.send_message(message.from_user.id, 'Все ещё в деле')
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagestelebot__init__.py", line 439, in send_message
    reply_markup, parse_mode, disable_notification))
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagestelebotapihelper.py", line 135, in send_message
    return _make_request(token, method_url, params=payload, method='post')
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagestelebotapihelper.py", line 54, in _make_request
    timeout=(connect_timeout, read_timeout), proxies=proxy)
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagesrequestssessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagesrequestssessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagesrequestsadapters.py", line 490, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected(
'Remote end closed connection without response',))

Что то подобное
Что делать? На систему вебхуков переходить не хочу, не умею, может есть починка полинга?

I tried it, and with infinity_polling. When switching networks, the process survived, but did not respond to events. Eventually, the following exception occurred:

2021-07-09 23:28:15,356 (__init__.py:586 MainThread) ERROR - TeleBot: "Infinity polling exception: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=30)"
2021-07-09 23:28:15,356 (__init__.py:588 MainThread) ERROR - TeleBot: "Exception traceback:
Traceback (most recent call last):
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/urllib3/connectionpool.py", line 445, in _make_request
    six.raise_from(e, None)
  File "<string>", line 3, in raise_from
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/urllib3/connectionpool.py", line 440, in _make_request
    httplib_response = conn.getresponse()
  File "/usr/lib/python3.9/http/client.py", line 1349, in getresponse
    response.begin()
  File "/usr/lib/python3.9/http/client.py", line 316, in begin
    version, status, reason = self._read_status()
  File "/usr/lib/python3.9/http/client.py", line 277, in _read_status
    line = str(self.fp.readline(_MAXLINE + 1), "iso-8859-1")
  File "/usr/lib/python3.9/socket.py", line 704, in readinto
    return self._sock.recv_into(b)
  File "/usr/lib/python3.9/ssl.py", line 1241, in recv_into
    return self.read(nbytes, buffer)
  File "/usr/lib/python3.9/ssl.py", line 1099, in read
    return self._sslobj.read(len, buffer)
socket.timeout: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/requests/adapters.py", line 439, in send
    resp = conn.urlopen(
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/urllib3/connectionpool.py", line 755, in urlopen
    retries = retries.increment(
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/urllib3/util/retry.py", line 532, in increment
    raise six.reraise(type(error), error, _stacktrace)
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/urllib3/packages/six.py", line 770, in reraise
    raise value
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/urllib3/connectionpool.py", line 699, in urlopen
    httplib_response = self._make_request(
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/urllib3/connectionpool.py", line 447, in _make_request
    self._raise_timeout(err=e, url=url, timeout_value=read_timeout)
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/urllib3/connectionpool.py", line 336, in _raise_timeout
    raise ReadTimeoutError(
urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=30)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/__init__.py", line 582, in infinity_polling
    self.polling(none_stop=True, timeout=timeout, long_polling_timeout=long_polling_timeout,
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/__init__.py", line 620, in polling
    self.__threaded_polling(none_stop, interval, timeout, long_polling_timeout, allowed_updates)
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/__init__.py", line 679, in __threaded_polling
    raise e
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/__init__.py", line 642, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/util.py", line 130, in raise_exceptions
    raise self.exception_info
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/util.py", line 82, in run
    task(*args, **kwargs)
  File "/home/andy/Code/codepic/app/./colorcodebot.py", line 164, in wrapper
    resp = original(*args, **kwargs)
  File "/home/andy/Code/codepic/app/./colorcodebot.py", line 278, in welcome
    self.bot.reply_to(
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/__init__.py", line 2152, in reply_to
    return self.send_message(message.chat.id, text, reply_to_message_id=message.message_id, **kwargs)
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/__init__.py", line 925, in send_message
    apihelper.send_message(
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/apihelper.py", line 257, in send_message
    return _make_request(token, method_url, params=payload, method='post')
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/telebot/apihelper.py", line 139, in _make_request
    result = _get_req_session().request(
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/requests/sessions.py", line 542, in request
    resp = self.send(prep, **send_kwargs)
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/requests/sessions.py", line 655, in send
    r = adapter.send(request, **kwargs)
  File "/home/andy/.local/share/venvs/0dda4f1e0a6c3d4825183a79e394ca41/venv/lib/python3.9/site-packages/requests/adapters.py", line 529, in send
    raise ReadTimeout(e, request=request)
requests.exceptions.ReadTimeout: HTTPSConnectionPool(host='api.telegram.org', port=443): Read timed out. (read timeout=30)
"

At this point the bot became responsive to any new events, but never «caught up» on the ones missed in the meantime.

Cheetah7

0 / 0 / 0

Регистрация: 10.06.2016

Сообщений: 21

1

08.07.2019, 23:37. Показов 23323. Ответов 6

Метки bot, bot telegram, pycharm, python 3.7, python 3.x (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте!

При запуске кода для связи с чат-ботом в Telegram, возникла следующая проблема, которую не получается решить:
‘Connection to api.telegram.org timed out. (connect timeout=3.5)’

Падает чат-бот. Проблема с bot.polling()

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import telebot
import const
 
bot = telebot.TeleBot(const.API_TOKEN)
 
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Привет! Я Бот!")
 
@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message, message.text)
 
bot.polling()

Проблема в строчке bot.polling(). Пробовала зациклить.

Python
1
2
3
4
5
6
while True:
    try:
        bot.polling(none_stop=True)
    except Exception as e:
        print(e)
        time.sleep(150)

Ошибка не пропала.
Очень нужна помощь!!! Заранее спасибо!



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

08.07.2019, 23:37

Ответы с готовыми решениями:

Чат-бот. Chat-Bot
Вот у меня есть чат-бот(вопрос — ответ)
У меня возникли 2 вопроса:

1. Что дописать что бы,…

Telegram Bot: Бот не реагирует на сообщения
Приветствую.

Создаю бота через библиотеку — Telegram.Bot.

Бот не реагирует на сообщения. …

Падает бот
import telebot
from telebot import types…

Чат-бот
Здравствуйте, хочу сделать сайт с чат-ботом. Механизм такой: Создаю таблицу dicitonary с полями:…

6

Cheetah7

0 / 0 / 0

Регистрация: 10.06.2016

Сообщений: 21

08.07.2019, 23:44

 [ТС]

2

Внесла изменения в код. Бот не падает, но и не отвечает(( В чём проблема?

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import telebot
import const
import time
 
bot = telebot.TeleBot(const.API_TOKEN, threaded=False)
 
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Привет! Я Бот!")
 
@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message, message.text)
 
bot.infinity_polling(True)

Падает чат-бот. Проблема с bot.polling()

Падает чат-бот. Проблема с bot.polling()



0



211 / 108 / 44

Регистрация: 12.12.2016

Сообщений: 387

09.07.2019, 17:53

3



0



Cheetah7

0 / 0 / 0

Регистрация: 10.06.2016

Сообщений: 21

10.07.2019, 22:42

 [ТС]

4

Добавила прокси. Перед этим поставила несколько библиотек:
pip install requests[socks]
pip install gunicorn
pip install PuSocks
pip install pyTelegramBotAPI —upgrade
pip install urllib3
pip install requests==2.10.0

Но бот так и не отвечает

Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import telebot
from telebot import apihelper
import const
import time
 
bot = telebot.TeleBot(const.API_TOKEN, threaded=False)
apihelper.proxy = {"https": "socks5://54.39.16.26:41279"}
 
@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
    bot.reply_to(message, "Привет! Я Бот!")
 
@bot.message_handler(func=lambda message: True)
def echo_all(message):
    bot.reply_to(message, message.text)
 
while True:
    try:
        bot.polling(none_stop=True, interval=0, timeout=20)
    except Exception as E:
        time.sleep(1)

Кто с таким сталкивался? Очень нужна помощь!!!



0



1286 / 671 / 365

Регистрация: 07.01.2019

Сообщений: 2,182

11.07.2019, 00:02

5



0



1 / 1 / 0

Регистрация: 10.01.2011

Сообщений: 82

07.06.2022, 13:13

6

чем отличается bot.infinity_polling от bot.polling?



0



Эксперт по компьютерным сетям

5889 / 3347 / 1033

Регистрация: 03.11.2009

Сообщений: 9,974

07.06.2022, 17:19

7

bot.polling вроде бы не обрабатывает ошибки и требует свой бесконечный цикл



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

07.06.2022, 17:19

Помогаю со студенческими работами здесь

Чат-бот на C++
Как сделать оффлайн бота для общения?В данный момент изучаю C++ и решил сделать такого!Также надо…

Чат-бот
Ниже полностью рабочий код для программы чат-бота, который вам отвечает.
У меня есть…

чат-бот
Подскажите пожалуйста..как написать чат-бот, что-то похожее на A.L.I.C.E.

Чат бот
Мою проблему объяснить не очень просто, но я постараюсь. Недавно я захотел написать чат бота на Qt…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

7

Делал большой проект на Python3, Телеграмм бот с множеством функций, из-за скудности багажа знаний и (как я понял это необходимо) кошелька на сервера использовал bot.polling() (Использую pyTelegramBotAPI) и буквально через пол часа бот падает. написал обычного бота для теста отклика через время, думая что перегрузил проект, но нет, в самом деле падает, код:

import telebot
import extras


bot = telebot.TeleBot(extras.token)


@bot.message_handler(content_types="text")
def handler_text(message):
    bot.send_message(message.from_user.id, 'Все ещё в деле')

bot.polling(none_stop=True)

Ошибка в консоли:

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagestelebotutil.py", line 58, in run
    task(*args, **kwargs)
  File "D:/Python/test.py", line 10, in handler_text
    bot.send_message(message.from_user.id, 'Все ещё в деле')
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagestelebot__init__.py", line 439, in send_message
    reply_markup, parse_mode, disable_notification))
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagestelebotapihelper.py", line 135, in send_message
    return _make_request(token, method_url, params=payload, method='post')
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagestelebotapihelper.py", line 54, in _make_request
    timeout=(connect_timeout, read_timeout), proxies=proxy)
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagesrequestssessions.py", line 508, in request
    resp = self.send(prep, **send_kwargs)
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagesrequestssessions.py", line 618, in send
    r = adapter.send(request, **kwargs)
  File "C:UsersMainWindowsPCAppDataLocalProgramsPythonPython36-32libsit
e-packagesrequestsadapters.py", line 490, in send
    raise ConnectionError(err, request=request)
requests.exceptions.ConnectionError: ('Connection aborted.', RemoteDisconnected(
'Remote end closed connection without response',))

Что то подобное
Что делать? На систему вебхуков переходить не хочу, не умею, может есть починка полинга?

import configparser
import config
import telebot
from telebot import types #buttons
from string import Template

bot = telebot.TeleBot(config.token)

user_dict = {}

class User:
    def __init__(self, city):
        self.city = city

        keys = ['fullname', 'phone']

        for key in keys:
            self.key = None

# если /help, /start
@bot.message_handler(commands=['start','help'])
def send_welcome(message):
    chat_id = message.chat.id
    bot.send_message(chat_id, "Здравствуйте." + "{message.from_user.first_name}" + " Я бот! Я могу вам помочь связаться с оператором для консультации.", reply_markup=markup)
    return(chat_id)
    markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2) 

#bot.send_message(message.chat.id, "Здравствуйте. {message.from_user.first_name}" + " Я бот! Я могу вам помочь связаться с оператором для консультации.", chat_id=call, reply_markup=markup)

def process_city_step(message):
    try:
        chat_id = message.chat.id
        user_dict[chat_id] = User(message.text)

        # удалить старую клавиатуру
        markup = types.ReplyKeyboardRemove(selective=False)

        msg = bot.send_message(chat_id, 'Как к вам обращаться?', reply_markup=markup)
        bot.register_next_step_handler(msg, process_fullname_step)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

def process_fullname_step(message):
    try:
        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.fullname = message.text

        msg = bot.send_message(chat_id, 'Ваш номер телефона')
        bot.register_next_step_handler(msg, process_phone_step)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

def process_phone_step(message):
    try:
        int(message.text)

        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.phone = message.text

    except Exception as e:
        msg = bot.reply_to(message, 'Вы ввели что то другое. Пожалуйста введите номер телефона.')
        bot.register_next_step_handler(msg, process_phone_step)

def process_social_step(message):
    try:
        chat_id = message.chat.id
        user = user_dict[chat_id]
        user.carModel = message.text

        markup = types.ReplyKeyboardMarkup(one_time_keyboard=True, resize_keyboard=True)
        itembtn1 = types.KeyboardButton('Только телефон')
        itembtn2 = types.KeyboardButton('Telegram')
        itembtn3 = types.KeyboardButton('Viber')
        itembtn4 = types.KeyboardButton('WhatsApp')
        markup.add(itembtn1, itembtn2, itembtn3, itembtn4)

        msg = bot.send_message(chat_id, 'Ваши соц сети', reply_markup=markup)
        bot.register_next_step_handler(msg)

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

        # ваша заявка "Имя пользователя"
        bot.send_message(chat_id, getRegData(user, 'Ваша заявка', message.from_user.first_name), parse_mode="Markdown")
        # отправить в группу
        bot.send_message(config.chat_id, getRegData(user, 'Заявка от бота', bot.get_me().username), parse_mode="Markdown")

    except Exception as e:
        bot.reply_to(message, 'ooops!!')

# формирует вид заявки регистрации
# нельзя делать перенос строки Template
# в send_message должно стоять parse_mode="Markdown"
def getRegData(user, title, name):
    t = Template('$title *$name* n ФИО: *$fullname* n Телефон: *$phone* ')

    return t.substitute({
        'title': title,
        'name': name,
        'fullname': user.fullname,
        'phone': user.phone
    })

# произвольный текст
@bot.message_handler(content_types=["text"])
def send_help(message):
    bot.send_message(message.chat.id, 'О нас - /aboutnРегистрация - /regnПомощь - /help')

# Enable saving next step handlers to file "./.handlers-saves/step.save".
# Delay=2 means that after any change in next step handlers (e.g. calling register_next_step_handler())
# saving will hapen after delay 2 seconds.
bot.enable_save_next_step_handlers(delay=2)

# Load next_step_handlers from save file (default "./.handlers-saves/step.save")
# WARNING It will work only if enable_save_next_step_handlers was called!
bot.load_next_step_handlers()

if __name__ == '__main__':
    bot.polling(none_stop=True)

Понравилась статья? Поделить с друзьями:
  • Bosch стиральная машина ошибка е28
  • Bosch стиральная машина ошибка e63
  • Bosch стиральная машина ошибка e23 что делать
  • Bosch стиралка ошибка f21
  • Bosch посудомойка ошибка е04