AWS Telegram Bot Connector
Serverless application that implements a Telegram bot connector for message receive and send.
Telegram bot configurations
Create a new bot talking to @BotFather and copy the provide token (needed for TelegramBotToken parameter).
Retrieve list of sender IPs
Telegram report which IPs they’re sending webhook from.
Here the latest values:
149.154.160.0/20
91.108.4.0/22
Retrieve updates
Retrieve bot updates navigating to https://api.telegram.org/bot<here the bot token>/getUpdates
.
You should see a response like this:
{"ok":true,"result":[{"update_id":1234567890,
"message":{"message_id":10,"from":{"id":1234567890,"is_bot":false,"first_name":"Fabio","username":"daaru","language_code":"it"},"chat":{"id":1234567890,"first_name":"Fabio","username":"daaru","type":"private"},"date":1234567890,"text":"test"}}]}
The chat.id
is the value to use in TelegramChatsWhitelist parameter.
Set Webhook
A StepFunction triggered by stack created event will automatically register the webhook using the setWebhook bot API.
In order to check if the webhook is correctly registered navigating to `https://api.telegram.org/bot<here the bot token>/getWebhookInfo`. You should see a response like this:
{"ok":true,"result":{"url":"https://xxxxxxxxxxxx.execute-api.eu-west-1.amazonaws.com/webhook/","has_custom_certificate":false,"pending_update_count":0,"max_connections":40,"ip_address":"0.0.0.0"}}
If the response is empty the webhook wasn’t registered correctly:
{"ok":true,"result":{"url":"","has_custom_certificate":false,"pending_update_count":0}}
Set the WebHook URL endpoint (retrieved from WebhookEndpoint stack output after the first deploy) navigating to: https://api.telegram.org/bot<here the bot token>/setWebhook?url=<here the webhook endpoint url>
. You should see a response like this:
{"ok":true,"result":true,"description":"Webhook was set"}
Receive a message
When a message is sent to the bot (and the username whitelist pass) this application send an event to the exported EventBridge bus with the following format:
{
"source": "org.telegram.webhook",
"detail-type": "Message Received",
"detail": { /* Update object */ }
}
Event’s details as the same format as Update object.
Send a message
In order to send a message through the Telegram bot send an event to the exported EventBridge bus with the following format:
{
"detail-type": "Send Message",
"detail": {
"chat_id": 1234567,
"text": "this is an **example** message"
}
}
With this approach message communication can be handled asynchronously outside the connector application just interacting with the exported Event Bridge bus.
Also an username and source IP whitelist is implemented in order to keep the integration as safe as possible.
Repository: daaru00/aws-telegram-bot-connector
Credits: Cloudcraft.
Originally written on Jan 11, 2022.