포스트

젠킨스 파이프라인 스크립트에서 텔레그램 메시지 보내기

물론 젠킨스용 텔레그램 플러그인도 있지만 개인적으로는 시행착오를 겪고 싶지 않았습니다. 플러그인이 출시된 지 최소 2년이 지났습니다. 리눅스에서 curl을 사용하여 텔레그램 메시지를 보내보겠습니다.

젠킨스 - 텔레그램 플러그인 젠킨스 - 텔레그램 플러그인

텔레그램 메시지 전송을 위한 Groovy 함수

젠킨스 스크립트에서 사용할 두 개의 Groovy 함수를 만들었습니다. func_telegram_sendMessage_message는 간단히 문자열을 삽입하여 텔레그램 메시지를 보내는 함수입니다. 또 다른 func_telegram_sendMessage_file은 텍스트 파일의 내용을 텔레그램 메시지로 보내는 함수입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// -----------------------------------------------
// func_telegram_sendMessage_message
// -----------------------------------------------
def func_telegram_sendMessage_message(title, message, token, chatid) {
    echo "### func_telegram_sendMessage_message, title=${title}, message=${message}, token=${token}, chatid=${chatid}"

    try {
        sh """
        curl -X POST \
                -d chat_id=${chatid} \
                -d parse_mode=HTML \
                -d text='<b>${title}</b>\n\n${message}' \
                https://api.telegram.org/bot${token}/sendMessage
        """
    } catch(Exception e) {
        currentBuild.result = 'SUCCESS'
    }
}

// -----------------------------------------------
// func_telegram_sendMessage_fileContents
// -----------------------------------------------
def func_telegram_sendMessage_fileContents(title, file, token, chatid) {
    echo "### func_telegram_sendMessage_file, title=${title}, file=${file}, token=${token}, chatid=${chatid}"

    boolean isFileExist = true
    def filecontents = ""
    if (fileExists("${file}") == true) {
        def filetext = sh(script: "cat ${file}", returnStdout: true).trim()
        filecontents = "<b>${file}</b>\n${filetext}"
    } else {
        filecontents = "<b>${file}</b>\nFile does not exist"
        isFileExist = false
    }

    func_telegram_sendMessage_message(title, filecontents, token, chatid)

    return isFileExist
}

// -----------------------------------------------
// func_telegram_sendDocument_file
// -----------------------------------------------
def func_telegram_sendDocument_file(file, token, chatid) {
    echo "### func_telegram_sendMessage_file, file=${file}, token=${token}, chatid=${chatid}"

    if (fileExists("${file}") == false) {
        return false
    }

    try {
        sh """
        curl -k \
        -F chat_id=${chatid} \
        -F document=@\"${file}\" \
                https://api.telegram.org/bot${token}/sendDocument
        """
    } catch(Exception e) {
        currentBuild.result = 'SUCCESS'
        return false
    }

    return true
}

아직 curl을 통해 텔레그램 메시지를 보내는 동안 오류가 발생하지 않았지만 오류로 인해 파이프라인 프로세스가 중단되는 것을 방지하기 위해 try-catch 문으로 컬 문을 래핑했습니다. 저는 개인적으로 텔레그램 메시지를 보내는 것보다 파이프라인 처리가 더 우선순위가 높다고 생각합니다.

파이프라인steps 내에서 함수 사용

아래는 파이프라인steps에서 위에서 생성한 함수를 호출하는 방법입니다. 텔레그램 봇의 tokenchatid를 하드코딩했습니다. 나중에 필요하게 되면 젠킨스의 Credentials 기능을 이용해 구현해보도록 하겠습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
steps {
    script {
        def token = g_si.TELEGRAM_TOKEN;
        def chatid = g_si.TELEGRAM_CHATID;
        
        func_telegram_sendMessage_message("title", "im message", token, chatid)
        func_telegram_sendMessage_file("file title", "./_report/aa.txt", chatid, chatid)
        
        func_telegram_sendMessage_message("im title", "im message", token, chatid)
        def rst = func_telegram_sendMessage_fileContents("im file title", "./_report/aa.txt", token, chatid)
        if (rst == true ) {
            func_telegram_sendMessage_file("./_report/aa.txt", token, chatid)
        }                        
    }
}

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.