skip to Main Content

I created a telegram bot using python-telegram-bot v 20.2. I run it on the computer using application.run_polling(), and everything works fine.

But when I try to place it on a serverless structure with an entry point (handler(event, context)), I don’t understand how to make it work.

I added a webhook without any problems using setWebhook. And I get the data without any problems using json.loads(event['body']).

I tried using the solution from here, but couldn’t figure out how it works.

Please tell me how to make the serverless function respond to me in telegram.

Code:

# A simple example of a handler that I found.
async def handler(event, context):
    body = json.loads(event['body'])
    print(body)
    return {
        'statusCode': 200,
        'body': 'Webhook request received'
    }
# The code that works on my computer.
def main() -> None:
    application = Application.builder().token(config.MYTOKEN).build()
    application.add_handler(CommandHandler("start", send_welcome))
    application.run_polling()

if __name__ == '__main__':
    main()

2

Answers


  1. Chosen as BEST ANSWER

    Thanks to CallMeStag for the answer.

    The final code looks like this:

    async def handler(event, context):
        application = Application.builder().token(config.MYTOKEN).build()
        application.add_handler(CommandHandler("start", send_welcome))
        body = Update.de_json(data=json.loads(event['body']), bot=application.bot)
        await application.initialize()
        await application.process_update(body)
        await application.shutdown()
        return {
             'statusCode': 200,
             'body': 'Webhook request received'
        }
    

  2. You were already on the right wiki page 😉 Please read the last paragraph "Alternative: No long running tasks".

    The point is that run_polling (as wrapper around Application.{initialize, start, stop, shutdown}) is designed for scripts that run 24/7, which is not what you need in your case. You only need to call Application.initialize, Application.process_update and Application.shutdown.


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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search