Building a serverless Telegram bot
With the arrival of FaaS and all the serverless infrastructure providers (AWS, Google Cloud, Azure, etc) now is easy to deploy our own Telegram bot.
A Webhook-based bot it's the perfect use case for serverless computing, using for example Google Cloud Functions we'll have all these advantages:
- Our function will be associated to a public endpoint (IPv4 and IPv6) over HTTPS (using a valid certificate provided by Google)
- Pay only for function invocations and its compute resources consumption, so it could be cheaper than paying for a server powered on all the time
- No server management
- Scales automatically
Requirements
Before start building your bot you'll need to:
- Register a new bot following these instructions core.telegram.org/bots in order to get an API token
- Using a Google Cloud account, register a new project, enable the Cloud Functions API and install the Cloud SDK following the official quickstart
Code
In a few lines of Python you can code a simple echo bot that will reply with the same message that it receives:
# main.py import os import telegram def webhook(request): bot = telegram.Bot(token=os.environ["TELEGRAM_TOKEN"]) if request.method == "POST": update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id # Reply with the same message bot.sendMessage(chat_id=chat_id, text=update.message.text) return "ok"
The only dependency needed is the amazing python-telegram-bot library:
# requirements.txt python-telegram-bot==11.1.0