Vaibhav Vishwakarma
Vaibhav Vishwakarma

Reputation: 99

Using Telegram Bot with Django

I am trying to use my telegram bot with Django. I want the code to keep running in the background. I am Using the apps.py to do this but there's one problem when the bot starts as it's an infinite loop, the Django server is never started.

Apps.py:

from django.apps import AppConfig
import os

class BotConfig(AppConfig):
    default_auto_field = 'django.db.models.BigAutoField'
    name = 'bot'
    
    def ready(self):
        from . import jobs

        if os.environ.get('RUN_MAIN', None) != 'true':
            jobs.StartBot()

Jobs.py:

def StartBot():
    
    updater = Updater("API KEY")
    dp = updater.dispatcher
    dp.add_handler(ChatMemberHandler(GetStatus, ChatMemberHandler.CHAT_MEMBER))
    updater.start_polling(allowed_updates=Update.ALL_TYPES)
    updater.idle()

What's the best way to run my bot in the background? while making sure that the Django server runs normally. I tried Django background tasks but it's not compatible with Django 4.0.

Upvotes: 0

Views: 943

Answers (1)

CallMeStag
CallMeStag

Reputation: 7020

The purpose of Updater.idle is to keep the main thread alive because start_polling only starts some background threads that don't block the main thread. If you want to run other stuff in the main thread, skip updater.idle() and instead call Updater.stop manually when the program should shut down.


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

Upvotes: 1

Related Questions