Running flask and python-telegram-bot (asyncio) in the same process

I am trying to initialize Flask and python-telegram-bot in the same process in Python 3.11. But the problem is that flask is blocking and python-telegram-bot uses asyncio.

Now, this is the code I have.

First in the main function I try to initialize my two modules

from web_server import init_web_server
from telegram_bot import init_telegram_bot
import asyncio

async def main():
    await init_telegram_bot())

if __name__ == "__main__":

For each module, I do what it has to. For Flask, I create a thread, and for python-telegram-bot I initialize the async application.

import flask
import threading

def init_web_server():
    app = Flask(__name__)
    threading.Thread(target=lambda:"", port=5000, debug=True, use_reloader=False)).start()

import asyncio
from telegram.ext import Application

async def post_init(application: Application) -> None:
    print("Bot initialized")

async def init_telegram_bot():
    application = ApplicationBuilder().token(token).post_init(post_init).build()
    await application.initialize()
    await application.start()
    await application.updater.start_polling()

But there’s a problem here, since post_init never gets run (I never see the “Bot initialized” text on stdout). And I get an error: Fetching updates got a asyncio.CancelledError. Ignoring as this task may onlybe closed via Application.stop.

Been trying for a while to use application.run_polling() instead of initialize() + start() + updater.start_polling() but I think it internally does an since I always get the RuntimeError: This event loop is already running error.

Any help to understand why this is not working would be appreciated. And if the solution allowed to have other libraries using asyncio (perhaps by the means of gather() function) it would be great.

Leave a Comment