Search code examples
pythonpandaspython-telegram-bot

telegram async does not work during iteration in python


I am testing the alerting system in Jupyter Notebook. I have a df with columns ds and y by day for a period of 2 years. I also have a list of dates for 3 months, up to the present day. I go through the list of dates, and for each individual day I make a query to the database, and add it to the existing df, then predict the value for that day, and compare the confidence interval of the predicted value with the actual value. If the actual value falls outside, I want to send a message in Telegram. This is where the error occurs. Separately, the code works without a telegram bot and a telegram bot if you substitute text in the message, for example, like this:

for i in range(10):
    import telegram
    #https://api.telegram.org/bot<your_token>/getUpdates
    my_token = '****'
    chat_id = '****'
    bot = telegram.Bot(token=my_token)
    # Отправление текстового отчета
    message = f'{i}'
    await bot.sendMessage(chat_id=chat_id, text=message)

but together I get the following error:

UnboundLocalError: local variable 'df' referenced before assignment

screen: enter image description here

Below is the function code:

# go through the list of dates that I want to pull from sql

for date in date_list:

# add the new row I just pulled from the database to the existing dataframe.  
    df = df.append(vpn_query(f"'{date}'"), ignore_index=True)

# I predict the indicator y for this day that I just added and compare it with the real result, write df with yhat_lower, yhat_upper, and y to the variable ttt 
    ttt = hhh(df) 
    
# I extract the predicted value of the two bounds, and the actual value of the variable.    
    yhat_lower = ttt['yhat_lower'].tolist()[0]
    yhat_upper = ttt['yhat_upper'].tolist()[0]
    y = ttt['y'].tolist()[0]

#compare the value of the predicted limits with the actual value:
    if y > yhat_upper or y < yhat_lower:
        if trend_find(df.y[::-1].tolist()) > 20:

#if there is a very large change in values >20% then I want to write a message in telegram
            df.loc[df.index[-1], 'new_column'] = 1



            import telegram
            #https://api.telegram.org/bot<your_token>/getUpdates
            my_token = '****'
            chat_id = '****'
            bot = telegram.Bot(token=my_token)
            message = f'Anomaly {date}'
            await bot.sendMessage(chat_id=chat_id, text=message)



        else:
            df.loc[df.index[-1], 'new_column'] = 0.5
    else:
        df.loc[df.index[-1], 'new_column'] = 0

Solution

  • import telegram
    async def hh():
        my_token = '****'
        chat_id = '****'
        bot = telegram.Bot(token=my_token)
        await bot.send_message(chat_id=chat_id, text='gaga') 
    
    async def my_func(df):
        for date in tqdm(date_list):
            df = df.append(vpn_query(f"'{date}'"), ignore_index=True)
            ttt = hhh(df)
            yhat_lower = ttt['yhat_lower'].tolist()[0]
            yhat_upper = ttt['yhat_upper'].tolist()[0]
            y = ttt['y'].tolist()[0]
            if y > yhat_upper or y < yhat_lower:
                if trend_find(df.y[::-1].tolist()) > 20:
                    df.loc[df.index[-1], 'new_column'] = 1
                else:
                    df.loc[df.index[-1], 'new_column'] = 0.5
            else:
                await hh()
                df.loc[df.index[-1], 'new_column'] = 0
    
    await my_func(df)