Search code examples
djangopython-telegram-bot

python-telegram-bot in django application


I’m trying to start python-telegram-bot in a web application with the django framework. To do this, I follow any example from the Telegram library and end up calling the method application.run_polling(). I know it’s not the best option because this blocks my web server, and I want to replace it with a better one, but I can’t find it.

According to official documentation, there is a tip that indicates the following:

When combining python-telegram-bot with other asyncio based frameworks, using this method is likely not the best choice, as it blocks the event loop until it receives a stop signal as described above. Instead, you can manually call the methods listed below to start and shut down the application and the updater. Keeping the event loop running and listening for a stop signal is then up to you.

And then I find the following section:

See also

initialize(), start(), stop(), shutdown() telegram.ext.Updater.start_polling(), telegram.ext.Updater.stop(), run_webhook()

I’ve tried to understand the methods in the list, but I can’t figure out how to run python-telegram-bot in the background and not affect my main server.

Are there any links or documents that expand the information or detail the steps to follow in these cases?

Thank you in advance

EDIT: Telegram I run it from an app configured in django as follows:

import asyncio

from django.apps import AppConfig
from telegram import Update
from telegram.ext import ContextTypes, Application, CommandHandler

from TaixTracking.configApp import ConfigApp


async def help_command(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
    await update.message.reply_text("Help!")


async def start_telegram():
    application = Application.builder().token(ConfigApp().get_value('telegram', 'token', '')).build()
    application.add_handler(CommandHandler("help", help_command))

    await application.initialize()
    await application.start()
    await application.updater.start_polling()
    print('Telegram load')


class CommunicationConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'communication'

    def ready(self):
        if not ConfigApp().is_telegram_launch():
            ConfigApp().set_telegram_launch(True)
            asyncio.run(start_telegram())

Solution

  • The first point: Don't run polling operation within webserver, use dedicated script to work with Django models and Telegram API. I'm using aiogram but save/load data from Postgres DB with Django ORM (I know that I can use SQLAlchemy but I need to use Django for some reasons) Second point: Use decorators to handle messages (look for aiogram docs)