[API 활용] Slack Webhook + Kotlin + SpringBoot

C____JIN·2022년 11월 15일
1

API 활용

목록 보기
1/1
post-thumbnail

1. Webhook 생성

원하는 채널에 Webhook app 추가

  1. 해당 채널 통합에서 앱추가 클릭
  2. Webhook 검색 및 설치
  3. 원하는 채널 선택 후 앱 추가
  4. Webhook URL 기억하기

2. Kotlin 코드 작성

SlackWebhookService.kt

@Service
class SlackWebhookService(private val restTemplate: RestTemplate) {

    fun sendContent(content: String) {
        val jsonObj = JSONObject(
                """
                    {"attachments": [
                        { 
                            "pretext" : "attachments 제목입니다!",
                            "color" : "#2eb886",
                            "text" : ${content}
                        }
                      ]
                    }
                """.trimIndent()
        )

        val header = HttpHeaders()
        header.contentType = MediaType.APPLICATION_JSON
        val httpEntity = HttpEntity(jsonObj.toString(), header)

        var webhookUrl = "Webhook url을 입력하세요!"

        restTemplate.exchange(webhookUrl, HttpMethod.POST, httpEntity, String::class.java)

    }
}

SlackWebhookController.kt

@RestController
class SlackWebhookController(private val webhookCallService: SlackWebhookService) {
    @PostMapping("/msg")
    fun messageSendToSlack(@RequestParam(required = true) text: String): ResponseEntity<String>{
        webhookCallService.sendContent("${text}")
        return ResponseEntity("success", HttpStatus.OK)
    }
}

추가로 RestTemplate를 빈으로 주입 시켜야하는데, 그것은 다시 정리해서 따로 올리도록 하겠다!

자세한 내용은 github 참고

3. 테스트

1) Post man으로 전송

2) Slack에서 전송 확인

메시지 전송 형식(attachments)은
https://roseline.oopy.io/4d14964c-53fc-4b65-9e53-026fc52cb9cb
이곳을 참고

profile
개발 블로그🌐 개발일지💻

3개의 댓글

comment-user-thumbnail
2022년 11월 16일

오호~~ 이제 맥쓰시나여 ?

1개의 답글
comment-user-thumbnail
2022년 11월 17일

멋쟁이 cj님~
찐 개발자 모먼트 너무

답글 달기