DEV Community

Amalia Hajarani
Amalia Hajarani

Posted on

How to: Integrating Jenkins with Telegram Bot

Hallo dear everyone whoever read this post. Today I'd love to share my another learning journey with Jenkins. You can find the final repository in here. The use case itself actually from this post.

Prerequisite

  1. Installed Java version of 17 and have it configured in environment variable.
  2. Installed Maven version of 3.9.5 and have it configured in environment variable.
  3. Installed Jenkins (mine is Jenkins 2.426.1) along with the configuration. You may read the post I've attached above to know more on how to configure Jenkins environment.

Creating Telegram Bot

  1. Open Telegram application. I use Telegram Web.
  2. Search for BotFather. Image description
  3. Click on their profile. Click Start. Image description
  4. Send them a chat of /newbot.
  5. Give your bot a name.
  6. Create a username for your bot.
  7. They will give you an access token. Image description

Getting Chat Id

  1. As you can see from the image above, BotFather give you a link to chat with your bot. Click that link.
  2. Click Start button located at the right corner. Image description
  3. Send some chat like hi to the bot Image description
  4. Get the chat id by opening this link https://api.telegram.org/bot<access token>/getUpdates. You will get a response like below. Copy the chat id to somewhere safe:

    {
      "ok": true,
      "result": [
        {
          "update_id": 948995789,
          "message": {
            "message_id": 3,
            "from": {
              "id": 5046210284,
              "is_bot": false,
              "first_name": "Lala",
              "username": "amaliahajarani",
              "language_code": "en"
            },
            "chat": {
              "id": 5046210284, // this is the chat id          "first_name": "Lala",
              "username": "amaliahajarani",
              "type": "private"
            },
            "date": 1700788242,
            "text": "hi"
          }
        }
      ]
    }
    

Creating credentials for Telegram Bot access token and chat id.

  1. Open Jenkins UI, mine is at http://localhost:8085/.
  2. In side bar, choose Manage Jenkins section.
  3. Go to Security section. Choose Credentials. Image description
  4. Scroll to the bottom. You will sew Stores scoped to Jenkins section. Click System on that table. Image description
  5. You will be redirected into another page. Choose Global credentials (unrestricted). Image description
  6. Click Add Credentials button. Image description
  7. First, we are going to create credentials for access token. For Kind dropdown, choose Secret text.
  8. Enter your access token into Secret section. Then, enter some identifier at ID field so you know what kind of credential is that. Then click Create button. Image description
  9. Now, with the same step from poin 6, create new credential for chat id.

Creating JenkinsFile

If you don't have JenkinsFile in your project yet, in the root of the project, create a new file without extensions called JenkinsFile (better use code editor like Visual Studio Code). Mine lookslike this:

pipeline{
    agent any
    environment {
        TELEGRAM_TOKEN = credentials('telegram-token') // change this line with your credential id for Telegram bot access token
        TELEGRAM_CHAT_ID = credentials('telegram-chat-id') // change this line with your credential id for Telegram bot chat id

        TEXT_PRE_BUILD = "Jenkins is building ${JOB_NAME}"
        TEXT_SUCCESS_BUILD = "${JOB_NAME} is Success"
        TEXT_FAILURE_BUILD = "${JOB_NAME} is Failure"
        TEXT_ABORTED_BUILD = "${JOB_NAME} is Aborted"
    }
    tools {
        maven 'MAVEN_HOME' 
    }
    stages{
        stage("Pre-Build"){
            steps{
                bat ''' curl -s -X POST https://api.telegram.org/bot"%TELEGRAM_TOKEN%"/sendMessage -d chat_id="%TELEGRAM_CHAT_ID%" -d text="%TEXT_PRE_BUILD%" '''
            }
        }
        stage("build"){
            steps{
                bat 'mvn clean install'
            }
        }
        stage('SonarQube analysis'){
            steps{
                withSonarQubeEnv(credentialsId:'jenkins-sonarqube', installationName: 'SonarQube') {
                    bat 'mvn sonar:sonar'
                }
            }
        }
        stage('SQuality Gate') {
            steps {
                timeout(time: 1, unit: 'MINUTES') {
                    waitForQualityGate abortPipeline: true
                }
            }
        }
    }
    post{
        success{
            script {
                bat ''' curl -s -X POST https://api.telegram.org/bot"%TELEGRAM_TOKEN%"/sendMessage -d chat_id="%TELEGRAM_CHAT_ID%" -d text="%TEXT_SUCCESS_BUILD%" '''
            }
        }
        failure{
            script {
                bat ''' curl -s -X POST https://api.telegram.org/bot"%TELEGRAM_TOKEN%"/sendMessage -d chat_id="%TELEGRAM_CHAT_ID%" -d text="%TEXT_FAILURE_BUILD%" '''
            }
        }
        aborted{
            script {
                bat ''' curl -s -X POST https://api.telegram.org/bot"%TELEGRAM_TOKEN%"/sendMessage -d chat_id="%TELEGRAM_CHAT_ID%" -d text="%TEXT_ABORTED_BUILD%" '''
            }
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

A little explanation of my JenkinsFile:

  1. I set environment that I need to run the pipeline like the credentials that will be used.
  2. To make mvn command works, I have to define MAVEN_HOME that is already configured in my Jenkins environment.
  3. The first stage of the pipeline is called Pre-Build where a chat will be sent to your telegram account that Jenkins is building something.
  4. In the second stage of build I use a command of mvn clean install since I have to run SonarQube and SonarQube is running with the package generated by that command.
  5. The third stage Sonarqube analysis is using SonarQube environment that I have already configured like the token credential and the installation name. Jenkins will run the command of mvn sonar:sonar to analyze the code.
  6. The last stage is to tell the Jenkins build status based on the result of SonarQube analysis. Either it is success, fail, or aborted.
  7. After these stages is run, Jenkins will send another chat to let you know the build result.

Makesure you push the JenkinsFile to your Git code base.

Creating Jenkins Pipeline Project

  1. Open Jenkins Dashboard.
  2. At sidebar, choose New Item.
  3. Enter your project name.
  4. Choose Pipeline.
  5. Click OK. Image description
  6. When you already get redirected, tick the Github project checkbox.
  7. Enter the repository url. Image description
  8. Scroll down until you get into Pipeline Section.
  9. In Definition dropdown, choose Pipeline script from SCM. Image description
  10. In SCM dropdown, choose Git. Image description
  11. Enter your URL repository that you usually use to clone the project.
  12. Enter the Git credentials. If you don't have it yet, you can just adding them by choosing username and password as the Kind.
  13. Change the Branches to build if needed. By default it is master but I change mine to main. Image description
  14. On Script Path field, enter the jenkins file name. I think it is case sensitive so make sure it is correct. Either it is JenkinsFile or Jenkinsfile or other. Image description
  15. Click Save.

Building the project

  1. At Jenkins Dashboard, choose the project you just created.
  2. At the sidebar, choose Build Now.
  3. Wait until the build is finish.

On the start of the build you will get chat at Telegram like this:
Image description

After Build finish you will get a chat like this:
Image description

This is my chat lookslike after several builds (this is the bot that I created at the first try that's why it is different).
Image description

Top comments (0)