How to: Integrating Jenkins with Telegram Bot
Tags: jenkins, beginners, codenewbie
Published: 2023-11-24 02:06:32

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](https://github.com/amalja0/jenkins-lokomotif-scheduler-report). The use case itself actually from [this post](https://dev.to/amalja0/how-to-sonarqube-code-coverage-in-jenkins-with-maven-project-3bb6).

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e3vc23b37mnuy6pow8kx.png)
3. Click on their profile. Click `Start`.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3hxsba3av5rivtxa8idp.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7pnh6sfpwka1wgz8lsgc.png)

## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/awzhi8dpfd99wi3b12ou.png)
3. Send some chat like `hi` to the bot
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6zg8o0dfhj0cco81ekf0.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qyowlw4qssly51zfsen7.png)
4. Scroll to the bottom. You will sew `Stores scoped to Jenkins` section. Click `System` on that table.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w816s54n3y6lpyyv5ehv.png)
5. You will be redirected into another page. Choose `Global credentials (unrestricted)`.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uta5gl7exzeokl01jy3d.png)
6. Click `Add Credentials` button.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ad6dn61zgbw2mrhqsxn.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fy3if3bndfl6pm3jj3i6.png)
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%" '''
            }
        }
    }
}
```
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0bz4ha6iutva9ioj9jr8.png)
6. When you already get redirected, tick the `Github project` checkbox.
7. Enter the repository url.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gebqepjsrfw1rwibo2bu.png)
8. Scroll down until you get into `Pipeline` Section.
9. In `Definition` dropdown, choose `Pipeline script from SCM`.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nsr9l37iwt6e7pd9mf1z.png)
10. In `SCM` dropdown, choose `Git`.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nivr6fz14jeyplfvv2do.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pmldr6dik4zwu3fk9try.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/y1uz4gi61vxx6o6nvsxv.png)
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m02pryex9lpdnuqswwmh.png)

After Build finish you will get a chat like this:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8poha5piebzym7gpijqr.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pvzchw0n5tqvddgsxdsi.png)