Python Telegram Bot Job won't get back on execution after network fluctuation

Viewed 117

since my network at home is reconnecting every night, my computer is off internet for some seconds up to minutes. When running my python telegram bot, it throws errors coming from urllib3 as urllib3.exceptions.MaxRetryError: and requests as requests.exceptions.ConnectionError and telegram package error as telegram.error.NetworkError: urllib3 HTTPError

My programm is still able to run telegrams commandhandler tasks upon request in telegram, but the main job has stopped working. Any ideas how to get it working again?

For simplicity I created just this minimal example. The error can be easily induced by disconnecting from wifi or ethernet. Dependent on where in the code the disconnect happens, the sequence of the error appearing might change.

import logging
from time import sleep
from yfinance import download as yfdownload
from telegram.ext import (
    Updater,
    CallbackContext,
)

# Enable logging

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
print = logger.info

stocklist = ["MSFT", "TSLA", "BABA", "DE", "BIDU", "FSLY", "REPYY", "CRWD", "NET", "AMD", "BNTX", "CRWD", "WING"]

def callback_minute(context):
    checkStatus(context)
    job_minute = context.job_queue.run_once(callback_minute, 10)
   
def checkStatus(context):
    for ticker in stocklist:
        while True:
            try:
                price = yfdownload(ticker, progress = False).iloc[-1]["Close"].round(3)
                print("Current price for: " + ticker + " is: " + str(price))
                break
            except:
                sleep(1)
                continue
        

def error_handler(update: object, context: CallbackContext):
    logger.error(msg="Exception while handling an update:", exc_info=context.error)
    print("can I do something here ?")

def main():
    token = "insert telegram token here"
    updater = Updater(token, request_kwargs = {"read_timeout" : None, "connect_timeout" : None})
    j = updater.job_queue
    dispatcher = updater.dispatcher
    dispatcher.add_error_handler(error_handler)
    job_minute = j.run_once(callback_minute, when = 5)
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
0 Answers
Related