user23447338
user23447338

Reputation: 11

How to send message after restarting telegram bot?

I try to make telegram bot which can send an alarm. I use python-telegram-bot Bot works, it sends messages at time. I save times and messages in sqlite db. When the bot restarts he set alarms from db. I want the bot sends a message to a user when the bot is restarted and I don't understand how to do it. Please, help

Main function:

def main() -> None:
    """Run bot."""
    application = Application.builder().token("TOKEN").build()
    # on different commands - answer in Telegram
    application.add_handler(CommandHandler(["start", "help"], start))    application.add_handler(CommandHandler("set", set_timer))    application.add_handler(CommandHandler("unset", unset))   application.add_handler(CommandHandler("s",set_alarm))
    def_reply_handler = MessageHandler(filters.TEXT & (~filters.COMMAND), def_reply)   application.add_handler(def_reply_handler)   
    # handlers
    unknown_handler = MessageHandler(filters.COMMAND, unknown)   application.add_handler(unknown_handler)
    # Run the bot until the user presses Ctrl-C

    cursor.execute('''SELECT * FROM alarms''')
    res = cursor.fetchall()
    conn.commit()
    print(res)
    for row in res:
        id = row[0]
        chat_id = row[1]
        adate = datetime.strptime(row[2], '%Y-%m-%d %H:%M:%S')
        delta = adate - current_time
        print(f"zzzzzzz, {adate=},{delta=}")
        alarm_name = row[3]
        print(adate,current_time)
        if adate < current_time:
            #cursor.execute('''DELETE FROM alarms WHERE id= ?''',(row[0],))
            print("deleted",row)
            conn.commit()
            application.bot.send_message(chat_id=chat_id, text="TEXT TEXT TEXT")
        else:
            application.job_queue.run_once(alarm, delta, chat_id=chat_id, name=str(chat_id), data={"value": delta, "timer_name": alarm_name})

    application.run_polling(allowed_updates=Update.ALL_TYPES)

if __name__ == "__main__":
    main()

I get the error:

deleted (14, 979854333, '2024-02-15 13:56:00', 'normally good')

<string>:363: RuntimeWarning: coroutine 'ExtBot.send_message' was never awaited

RuntimeWarning: Enable tracemalloc to get the object allocation traceback


Since main function is not async i tried:

def main() -> None:
    """Run bot."""
    application = Application.builder().token("token").build()
    async def send_notification(chat_id, text):
        await application.bot.send_message(chat_id=chat_id, text=text)
.
.
.

        print(adate,current_time)
        if adate < current_time:
            #cursor.execute('''DELETE FROM alarms WHERE id= ?''',(row[0],))
            print("deleted",row)
            conn.commit()
            asyncio.run(send_notification(chat_id, "ffffff"))

With this lines the bot sends the message after restarting but it's all it can done.

The error: raise NetworkError(f"Unknown error in HTTP implementation: {exc!r}") from exc telegram.error.NetworkError: Unknown error in HTTP implementation: RuntimeError('Event loop is closed')

Upvotes: 0

Views: 182

Answers (1)

Paarth Siloiya
Paarth Siloiya

Reputation: 11

I think you need to await the line where you used send_message()

await application.bot.send_message(chat_id=chat_id, text="TEXT TEXT TEXT")

Upvotes: 0

Related Questions