This post will explain a simple way to send a notification to a Telegram using cURL. Recently, I had to implement such a feature in one of the projects. I was to send a deployment success notification to the telegram channel Here are the steps I have taken to accomplish it.
Also read: All you need to know about telegram
Create a new bot
This post on the telegram’s official site will show you how to create a new bot. Telegram bot has a name, which you need to assign and generate a token that we will use in the cURL request.
Get the unique Id for the telegram channel
Every telegram channel has a unique Id. We need ID as parameter our curl request. To get the unique Id for the channel you need to fetch the bot updates and look for this id. Here is the simple bash script to look for it.
https://core.telegram.org/bots/api#sendmessage
We are using of the many enpoint from Telegram Bot API. Read more about the Telegram Bot API.
For the ease, I have also prepared the simple ruby script to fetch channel Id.
require 'logger'
require 'telegram_bot'
TELEGRAM_BOT_TOKEN = "YOUR_BOT_API_TOKEN"
bot = TelegramBot.new(token: TELEGRAM_BOT_TOKEN, logger: Logger.new(STDOUT))
bot.get_updates(fail_silently: true) do |message|
puts "@#{message.from.username}: #{message.text}"
puts "Chat-ID: #{message.chat.id}"
end
Finally using cURL
For sending the telegram messages using bot, we use following endpoint from telegram Bot API.
Couple of thing to note about this endpoint:
- It’s a POST request
- It takes important params in the body: chatId and text.
Here is the sample curl request
curl -X POST \
-H 'Content-Type: application/json' \
-d '{"chat_id": "123456789", "text": "This is a test from curl", "disable_notification": true}' \
https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage