Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Well, you could’ve done this very easily if you had read the Documentation first.
The Defaults class is what you’re looking for.

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) # This will be set 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))

    app.run_polling()


if __name__ == "__main__":
    main()

And be mindful to read the documentation first next time. Things are well explained there.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading