If you ever wanted to get notified when certain things happen but didn’t find a lightweight solution – here comes captain Telegram.
Using a simple Telegram bot, it’s possible to send notifications to your mobile phone or browser. All the notifier node needs is curl
installed.
Registering a bot
First of all, a Telegram bot has to be registered in order to send messages later on. Follow these steps to get started:
- Using your Telegram client, send a message to
@BotFather
with the command/newbot
and follow the instructions. - Note the bot token you receive after successfully registering the bot.
- Message your bot with a simple message like
/start
or/test
.
Now use
curl -i -X GET https://api.telegram.org/bot<BOT_TOKEN>/getUpdates
to get the chat ID of the chat you created in the previous chat.
Sending messages
Now, you should have to following things:
- Bot API token
- Chat ID of the chat between you and your newly created bot.
To send a message, it’s as simple as using the following command structure
curl -i -X GET "https://api.telegram.org/bot<BOT_TOKEN>/sendMessage?chat_id=<CHAT_ID>&text=hello"
Example 1: Jenkins build notifications
In order to get notified in case a Jenkins build succeeds or fails, you can edit the Jenkinsfile
as follows
try {
// Build steps
}
catch(error) {
// Send Telegram message: Fail
error "Exception occurred, aborting"
}
// Send Telegram message: Success
Example 2: Travis notifications
If you use Travis CI to build your projects after pushing to GitHub, notifications can be implemented by editing the .travis.yml
file:
after_success:
- curl -iX GET "https://api.telegram.org/bot$TOKEN/sendMessage?chat_id=$CHATID&text=Build OK" 2>&1 >/dev/null
after_failure:
- curl -iX GET "https://api.telegram.org/bot$TOKEN/sendMessage?chat_id=$CHATID&text=Build failed" 2>&1 >/dev/null
Two things are important here:
- Redirect the output to
/dev/null
in order to prevent the chat ID from being logged into the public build log. - Add your secrets (
$TOKEN
and$CHATID
) to the repository specific settings in Travis to populate the used environment variables in a secure manner.