Делал большой проект на 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:\Users\MainWindowsPC\AppData\Local\Programs\Python\Python36-32\lib\sit
e-packages\telebot\util.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:\Users\MainWindowsPC\AppData\Local\Programs\Python\Python36-32\lib\sit
e-packages\telebot\__init__.py", line 439, in send_message
reply_markup, parse_mode, disable_notification))
File "C:\Users\MainWindowsPC\AppData\Local\Programs\Python\Python36-32\lib\sit
e-packages\telebot\apihelper.py", line 135, in send_message
return _make_request(token, method_url, params=payload, method='post')
File "C:\Users\MainWindowsPC\AppData\Local\Programs\Python\Python36-32\lib\sit
e-packages\telebot\apihelper.py", line 54, in _make_request
timeout=(connect_timeout, read_timeout), proxies=proxy)
File "C:\Users\MainWindowsPC\AppData\Local\Programs\Python\Python36-32\lib\sit
e-packages\requests\sessions.py", line 508, in request
resp = self.send(prep, **send_kwargs)
File "C:\Users\MainWindowsPC\AppData\Local\Programs\Python\Python36-32\lib\sit
e-packages\requests\sessions.py", line 618, in send
r = adapter.send(request, **kwargs)
File "C:\Users\MainWindowsPC\AppData\Local\Programs\Python\Python36-32\lib\sit
e-packages\requests\adapters.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.
Сделал тестовый код для бота по готовому гайду:
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import telebot
import config
import random
from telebot import types
from telebot import apihelper
#making proxy
apihelper.proxy = {'https':'socks5h://208.113.220.250:34571'}
#starting
bot=telebot.TeleBot(config.TOKEN)
@bot.message_handler(commands=['start'])
def welcome(message):
message = 'привет!'
# keyboard
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item = types.KeyboardButton("Рандомное число")
item2 = types.KeyboardButton("Как дела?")
markup.add(item1, item2)
bot.send_message(message.chat.id, "Добро пожаловать, {0.first_name}!\nЯ - <b>{1.first_name}</b>, бот созданный чтобы быть подопытным кроликом.".format(message.from_user, bot.get_me()),
parse_mode='html', reply_markup=markup)
@bot.message_handler(content_types=['text'])
def lalala(message):
if message.chat.type == 'private':
if message.text == 'Рандомное число':
bot.send_message(message.chat.id, str(random.randint(0,100)))
elif message.text == 'Как дела?':
markup = types.InlineKeyboardMarkup(row_width=2)
item1 = types.InlineKeyboardButton("Хорошо", callback_data='good')
item2 = types.InlineKeyboardButton("Не очень", callback_data='bad')
markup.add(item1, item2)
bot.send_message(message.chat.id, 'Отлично, сам как?', reply_markup=markup)
else:
bot.send_message(message.chat.id, 'Я не знаю что ответить')
@bot.callback_query_handler(func=lambda call: True)
def callback_inline(call):
try:
if call.message:
if call.data == 'good':
bot.send_message(call.message.chat.id, 'Вот и отличненько')
elif call.data == 'bad':
bot.send_message(call.message.chat.id, 'Бывает')
# remove inline buttons
bot.edit_message_text(chat_id=call.message.chat.id, message_id=call.message.message_id, text="Как дела?",
reply_markup=None)
# show alert
bot.answer_callback_query(callback_query_id=call.id, show_alert=False,
text="ЭТО ТЕСТОВОЕ УВЕДОМЛЕНИЕ!!11")
bot.polling(none_stop=True)
Вроде все работает, но появляется ошибка:
Как можно исправить?
Если есть примечание к коду тоже выслушаю.
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, 'О нас - /about\nРегистрация - /reg\nПомощь - /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)
Loading