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
Thanks to CallMeStag for the answer.
The final code looks like this:
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 aroundApplication.{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 callApplication.initialize
,Application.process_update
andApplication.shutdown
.Disclaimer: I’m currently the maintainer of
python-telegram-bot
.