Telegram notification from Jenkins

Posted on January 7, 2018
Tags:

The following Groovy PostBuild script can be used to send build notification to Telegram via a Telegram bot account. Note, that this is just using the HTTP POST API, meaning that you can’t interact with Jenkins via Telegram.

The message will include Jacoco coverage information if the build script is placed after the Jacoco post build reporting.

Use the following, dropping in the appropriate values in the first few lines:

// MODIFY THE FOLLOWING THREE LINES TO SUIT YOUR SPECIFIC PROJECT
def chatId = 'REPLACE WITH TELEGRAM CHAT ID'
def botId = 'REPLACE WITH TELEGRAM BOT ID'
def validStatuses = [hudson.model.Result.FAILURE, hudson.model.Result.UNSTABLE, hudson.model.Result.SUCCESS]

def result = manager.build.result
def name = manager.build.getProject().getName()

def coverage = ''

def action = manager.build.getActions().find { it.getUrlName() == "jacoco" }
if (action != null) {
    def percentage = action.getLineCoverage().getPercentageFloat();
    def previous = action.getPreviousResult()
    if (previous) {
        def delta = percentage - previous.getLineCoverage().getPercentageFloat();
        coverage = String.format("Coverage at %.02f%% (%+.02f)", percentage, delta)
    } else {
        coverage = String.format("Coverage at %.02f%%", percentage)
    }
} else {
    manager.listener.logger.println "No coverage info available"
}

if (validStatuses.contains(result)) {
    def urlText = java.net.URLEncoder.encode("$result building $name $coverage", "utf-8")
    println new URL("https://api.telegram.org/bot$botId/sendMessage?chat_id=$chatId&text=$urlText").getText()
}