Integrate Jenkins with Telegram
Telegram is a popular messaging application used by so many people and Jenkins has been known to be one of the most popular CI/CD tools. Wouldn’t it be cool if we could send messages from Jenkins to Telegram?
I’m going to show you how to do it in five easy steps.
#1 — Create a Telegram bot
Open telegram and in search box type @botfather
and click on it. Then it gives you instruction to how to create a bot.
typing /newbot
and entering will ask you for a bot name and username, choose something meaningful and press enter. It’s look like below.
After the bot is created it gives you a token that you can use to communicate to your bot with HTTP protocol.
Remember to send a private message to your bot with \start
to active it.
#2- Add the Telegram bot to a group
you can easily add your newly created bot to a group and typing @yourBotUserName
it will be added like any other user and it can send messages to the group as well.
.
.
.
.
.
.
#3 —Get your group id
Any group in telegram has a unique negative id witch is required as well as the token you previously gained to send messages.
To get that simply call this api with your token
https://api.telegram.org/bot<YourBOTToken>/getUpdates
It will give you bunch of information including the group id. Below is a sample output you might get. You have to find your chat id (negative value representing a group with the group name below it). Store this number.
#4- Prepare Jenkins
Now that you have your bot ready you can use http requests to send messages. You can send this calls from any where, in postman for example, in your back-end server on with help of HTTP Request
plugin, directly from Jenkins. So go ahead and install the plugin.
Also, the token is a secret value and we don’t want to use it directly. Instead we are going to put it inside Jenkins credentials and use it as a variable.
To do that go to Jenkins -> Credentials -> System -> Global Credentials
and add two new Secret String
Values with ids telegramToken
and telegramChatId
#5- Send a http request
Now, we define sendTelegram
function in our pipeline to send the messages.
As you can see it does nothing but using the HTTP Request
plugin to post a http request.
Congratulations you are done!
Still a better way?
Since this code is probably be used in more that one job you can define it as a library and use it anywhere you want. I described how to do it here. https://android.jlelse.eu/how-to-build-libraries-for-jenkins-pipelines-1772aa0da53d
I already build a library for this and you can find it here. https://github.com/MobodidTech/jenkins-shared
To use it add this lines to top of your pipeline code.
Then use it like telegram.sendTelegram(yourMessageHere)
Don’t forget to share your ideas in the comment section below, If you like the articles Clap! Also, Follow Me to read my other articles as well.