Search code examples
python-3.xtelegram-botpython-telegram-bot

How to make my telegram bot's handler not block each other?


I have a bot made with python-telegram-bot library. Here, I have to pass block=False to make the functions not block each other. But as my code gets bigger, adding block=True to each handler becomes quite a hassle. Is there a way to make all the handlers block=False?

Here's how my code looks like now.

from telegram.ext import ApplicationBuilder, CommandHandler, CallbackContext, Defaults
from telegram import Update, Bot, constants


async def start_c(u: Update, c: CallbackContext):
    bot: Bot = c.bot
    chat_id = u.message.chat_id
    await bot.sendMessage(chat_id, "<b>I'm alive!</b>")


async def help_c(u: Update, c: CallbackContext):
    bot: Bot = c.bot
    chat_id = u.message.chat_id
    await bot.sendMessage(chat_id, "Help Command!")


def main():
    key = "MY TOKEN"
    df = Defaults(parse_mode=constants.ParseMode.HTML)
    app = ApplicationBuilder().token(key).connect_timeout(30).defaults(df).build()

    app.add_handler(CommandHandler("start", start_c, block=False))
    app.add_handler(CommandHandler("help", help_c, block=False))

    app.run_polling()


if __name__ == "__main__":
    main()

I tried storing the commandNames and functions in a dict and then iterate over them and add block=False to each one. But that's a bit of code too!


Solution

  • You can set block=False in the Defaults along with parse_mode=constants.ParseMode.HTML. Check out the docs for Defaults to see what else you can pass there.

    Here's how you can use it:

    from telegram.ext import Defaults # import the Defaults class
    
    # Your Other Code Here
    
    def main():
        key = "MY TOKEN"
        df = Defaults(block=False) # `block=True` for all handlers
        app = ApplicationBuilder().token(key).connect_timeout(30).defaults(df).build()
    
        app.add_handler(CommandHandler("start", start_c)) # No need to set here anymore.
        app.add_handler(CommandHandler("help", help_c, block=True)) # but you can manually set it to `True` for some handlers
    
        app.run_polling()
    
    
    if __name__ == "__main__":
        main()