Can't get Telegram bot to send messages to user and run polling loop at the same time (python-telegram-bot)

Question:

I m trying to build a telegram bot usin the telegram.ext.Application class of python-telegram-bot and I need the bot to send periodic messages to a specific user while also running its polling loop to receive incoming messages from other users.

I ve done a lot-lot-lot of searching and tried various combinations but I cant seem to get it to work. THis is the code I have so far (I removed message handlers to give you the minimum possible code example)

import asyncio
import logging
from telegram.ext import Application

token = '1111111111:AAAoOOV_Aaa1aaAAAaA1AA11A1aAaAAaAAA'
user_id = 0000000000

application = Application.builder().token(token).build()


async def send_message_to_user(user_id, message_text):
    try:
        await application.bot.send_message(chat_id=user_id, text=message_text)
    except Exception as e:
        logging.error(f"Error while sending message to user {user_id}: {e}")


async def main() -> None:
    await send_message_to_user(user_id, "hello user, dont forget to get your pills")

    application.run_polling()


if __name__ == "__main__":
    asyncio.run(main())

The send_message_to_user coroutine works fine on its own, but when I try to combine it with the run_polling method (with or without await before it), i get this error

RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
sys:1: RuntimeWarning: coroutine 'Application.shutdown' was never awaited
sys:1: RuntimeWarning: coroutine 'Application.initialize' was never awaited

I think run_polling has its own event loop and cant run asyncronously but unfortunately Im not experienced with asynchronous programming so can anyone help me figure out how to send periodic messages to a specific user while also running a telegram bot’s polling loop?

Thanks in advance for your help!

Asked By: Tamar Gogoladze

||

Answers:

python-telegram-bot comes with the JobQueue, a built-in scheduling interface that allows you to run repeating tasks seamlessly within the framework.

You might also be interested in this wiki section, which covers the general use case of running some asyncio logic in parallel to the bot.


Disclaimer: I’m currently the maintainer of python-telegram-bot.

Answered By: CallMeStag