M
M
Maxim2021-04-28 22:25:50
Python
Maxim, 2021-04-28 22:25:50

Why is the remote host forcibly disconnecting?

Wrote a python bot News Aggregator. To read all the news in Telegram, and not run through each source. So, the bot works perfectly and does not give any errors. But if I click on any news source after 20 minutes, the bot crashes with an error:

requests.exceptions.ConnectionError: 
('Connection aborted.', ConnectionResetError(10054, 
'Удаленный хост принудительно разорвал существующее подключение', None, 10054, None))

I decided to experiment and instead of choosing a news source, first enter commands like /start or /news. As a result, everything worked well and the news was displayed without errors. Just why after a while when you click on the news itself, and not by entering the command, the connection is broken - it is not clear.
I already googled the problem, but people basically had a different situation, which is not particularly similar to mine.
Now, if that is the last line of my bot code. Maybe something is wrong with her, but xs how to solve this problem.
bot.polling(none_stop=True, interval=0)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexa2007, 2021-05-02
@Maks1ma

Write user to database

@bot.message_handler(func=lambda message: message.text == "start")
@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Добро пожаловать в бот Агрегатор новостей! Здесь вы можете подписаться на рассылку '
                                      'интересующих вас новостей, которые бот будет вам отправлять. '
                                      'Для вывода новостных источников напишите команду /news', reply_markup = start_buttons())
    Base().add_user(message.from_user.id, message.chat.id)

Legacy, modified bot
class Mybot(telebot.TeleBot):
    def __init__(self,arg, *args, **kwargs):
        super().__init__(arg, *args, **kwargs)

    def loop_poop(self):
        while True:
            parse_all_news(self)
            time.sleep(15)
            print(time.ctime())

    def polling(self, *args, **kwargs):
        thread = threading.Thread(target=self.loop_poop)
        thread.start()
        super().polling(*args, **kwargs)

One decorator instead of a dozen elif
@bot.callback_query_handler(func=lambda call: call.data in news_sources.values())
def callback_worker(call):
    news_source = ''
    for k,v in news_sources.items():
        if call.data == v:
            news_source = k
    try:
        Base().add_subscribe(call.from_user.id, call.data) 
        bot.edit_message_text(f'Вы подписались на новости {news_source}', call.message.chat.id, call.message.message_id, reply_markup=subscribe_news_buttons())
    except Exception as e:
        bot.send_message(call.message.chat.id, f'Подписка на новости {news_source} не удалась')

Creating callback buttons according to subscriptions
def subscribe_news_buttons():
    keyboard = types.InlineKeyboardMarkup()
    for btn_text, callback in news_sources.items():
        keyboard.add(types.InlineKeyboardButton(text=btn_text, callback_data=callback))
    return keyboard
        
def get_user_subscribes(user_id):
    keyboard = types.InlineKeyboardMarkup()
    sc = Base().get_subscribes(user_id)
    for chanel,sbs in sc:
        if sbs == '1':
            news_source = ''
            for k,v in news_sources.items():
                if chanel == v:
                    news_source = k
            keyboard.add(types.InlineKeyboardButton(text='Отписаться от '+news_source, callback_data=f'del_{chanel}'))
    return keyboard

Getting subscriptions from the database
def get_subscribes(self,user_id):
        r1,r2=[],[]
        sql = f"SELECT * FROM {self.table} WHERE {user_id} = user_id"
        try:
            res = self.cursor.execute(sql).fetchall()
            rows = self.cursor.execute(sql).description
            x=0
            for row in rows[2:]:
                r1.append(row[0])
            for _ in res[0][2:]:
                r2.append(_)
            result = zip(r1,r2)
            return list(result)
        except Exception as e:
            return False, e

Full code

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question