Integration Jenkins — Telegram Bot

Muhammad Umar Al Fajar
3 min readDec 1, 2023

--

Hello, on this occasion I wanna share how to integrate Jenkins and Telegram Bot to send notification. Without wasting more time, let’s get straight to the point. (I used this project)

Create The Bot

First, go to telegram and search for botfather.

Enter then enter the commands:

/start

/newbot

And then you will be asked to give it a name and username.

After that, back to botfather to disable the privacy mode.

After all those, go search your bot.

Choose yours, and then click the START button, it will send a /start command to your bot.

Now you can use:

https://api.telegram.org/bot<YOUR:BOT_TOKEN>/getUpdates

To get the chat id.

Manage Jenkins

Now, go to Jenkins and choose Manage Jenkins menu on the left navigation.

Go to Credentials — System — Global credentials.

Add secret text credentials for the telegram bot token and chat id.

After that, back to our project’s Jenkinsfile to add post action.

pipeline {
agent any
tools {
maven 'jenkins-maven'
}
environment {
BUILD_NUMBER_ENV = "${env.BUILD_NUMBER}"
TEXT_SUCCESS_BUILD = "[#${env.BUILD_NUMBER}] Project: ${JOB_NAME} build Success"
TEXT_FAILURE_BUILD = "[#${env.BUILD_NUMBER}] Project: ${JOB_NAME} build Failure"
}

stages {
stage('SonarQube Analysis') {
steps {
withSonarQubeEnv('SonarQube') {
sh 'mvn clean install'
sh 'mvn clean package verify sonar:sonar'
echo 'SonarQube Analysis Completed'
}
}
}
stage("Quality Gate") {
steps {
waitForQualityGate abortPipeline: true
echo 'Quality Gate Completed'
}
}
}

post {
success {
script{
withCredentials([string(credentialsId: 'tele-token', variable: 'TOKEN'), string(credentialsId: 'tele-chat-id', variable: 'CHAT_ID')]) {
sh ' curl -s -X POST https://api.telegram.org/bot"$TOKEN"/sendMessage -d chat_id="$CHAT_ID" -d text="$TEXT_SUCCESS_BUILD" '
}
}
}
failure {
script{
withCredentials([string(credentialsId: 'tele-token', variable: 'TOKEN'), string(credentialsId: 'tele-chat-id', variable: 'CHAT_ID')]) {
sh ' curl -s -X POST https://api.telegram.org/bot"$TOKEN"/sendMessage -d chat_id="$CHAT_ID" -d text="$TEXT_FAILURE_BUILD" '
}
}
}
}
}

Finally, build the job in Jenkins.

That’s all guys, have a good day.

--

--