Search code examples
pythontelegrampython-telegram-bot

How can I break out of telegram bot loop application.run_polling()?


def bot_start():
    application = ApplicationBuilder().token("api_key").build()


    async def stop(update, context):
        await context.bot.send_message(chat_id=update.message.chat_id, text='Terminating Bot...')
        await application.stop()
        await Updater.shutdown(application.bot)
        await application.shutdown()

    async def error(update, context):
        err = f"Update: {update}\nError: {context.error}"
        logging.error(err, exc_info=context.error)
        await context.bot.send_message(chat_id=user_id, text=err)

   application.add_handler(CommandHandler('stop', stop))
   application.add_error_handler(error)

   application.run_polling()

I tried everything I could to stop it and I couldnt as it's not letting other lines of code that comes after calling bot_start() run. It basically never reaches them.


Solution

  • Application.run_polling is a convenience methods that starts everything and keeps the bot running until you signal the process to shut down. It's mainly intended to be used if the Application is the only long-running thing in your python process. If you want to run other things alongside your bot, you can instead manually call the methods listed in the docs of run_polling. You may also want to have a look at this example, where this is showcased for a setup for a custom webhook server is used instead of PTBs built-in one.


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