透過 Telegram Chat Bot API 傳送警告訊息

Photo by Adem Ay on Unsplash
Photo by Adem Ay on Unsplash

Telegram Bot provides many APIs that you can build a bot to interact with users, you can leverage these APIs to build your own bot. I have a simple requirement that I need the telegram bot to send alarm messages automatically for me. How do I achieve this?

Creating your own Telegram Bot

First, you need to create your own bot from @BotFather, if you haven't created a bot by BotFather, take a look official document.

After creating a bot, you will receive this message from BotFather:

BotFather

The message will give the bot link and token - Be careful to protect your token.

Now you can click t.me/your-chatbot-name and it will navigate to the conversation, but your bot won't reply to you, because we didn't create program to deal with coming messages.

Interaction with your Bot

Now, we can interact by APIs to send a message by itself, following these steps:

🔶 Send /start to your bot (whatever message is ok)

🔶 Get our conversation chat id by the getMessage API

$ curl https://api.telegram.org/bot${token}/getUpdates

Or just paste the link to the browser, and replace ${token} with your bot token, you will get this data eventually:

{
"ok": true,
"result": [
{
"update_id": 123,
"message": {
"message_id": 456,
"from": {
"id": 789,
"is_bot": false,
"first_name": "Foo",
"last_name": "Bar",
"username": "foobar",
"language_code": "en"
},
"chat": {
"id": 123456,
"first_name": "Foo",
"last_name": "Bar",
"username": "foobar",
"type": "private"
},
"date": 1636113755,
"text": "test"
}
}
]
}

Copy the id of the chat field, we need chatId to send a message.

🔶 Send a message by sendMessage API:

$ curl https://api.telegram.org/bot${token}/sendMessage?chat_id=${chatId}&text=${text}

As above mentioned, you can use curl command or paste URL to the browser, and don't forget to replace ${token}, ${chatId} and ${text}.

${text} representation of the message that you want to send.

Cron Job ❤️ Scripts

If your system provides cron, by leveraging these APIs and commands, you can write a simple script and put it into crontab, you're created a very simple telegram chatbot ✅.

Here is a example script:

#!/bin/bash
CHAT_ID="id"
TOKEN="token"
TEXT="Hello, World"
curl -G -s -o /dev/null "https://api.telegram.org/bot$TOKEN/sendMessage?" \
--data-urlencode "text=$TEXT" \
--data-urlencode "chat_id=$CHAT_ID"
exit 0

Reference