JAVA/프로젝트

스프링부트 Slack 알림 연동

whyHbr 2024. 11. 25. 00:38
728x90
반응형

https://api.slack.com/apps

 

Slack API: Applications | Slack

Your Apps Don't see an app you're looking for? Sign in to another workspace.

api.slack.com

create new app - OAuth Permissions - add on OAuth scope 에서 channels:read, chat:write 추가

setting - install app - install to workspace 허용.

위 과정을 거치면 OAuth token 이 발급됨.

 

통합 - 앱추가 - 만든 앱 추가하기

 

 

이 토큰을 properties 에 등록.

slack.token=

 

 build.gradle 에 추가

implementation("com.slack.api:bolt:1.18.0")
implementation("com.slack.api:bolt-servlet:1.18.0")
implementation("com.slack.api:bolt-jetty:1.18.0") 

 

 

테스트:

결과:

 

코드:


@Service
@Log4j2
@RequiredArgsConstructor
public class SlackService {

    @Value("${slack.token}")
    String slackToken;

    public void sendSlackMessage(String message, String channel) {
        String channelAddress = "";
        log.info("Channel: " + channel);
        if (channel.equals("error")) {
            channelAddress = "#모니터링";
        }

        try {
            MethodsClient methods = Slack.getInstance().methods(slackToken);

            ChatPostMessageRequest request = ChatPostMessageRequest.builder()
                    .channel(channelAddress)
                    .text(message)
                    .build();

            methods.chatPostMessage(request);
            log.info("requeset :{}", request);

            log.info("Slack " + channel + " 에 메시지 보냄");
        } catch (SlackApiException | IOException e) {
            log.error("Slack API 호출 중 오류 발생: ", e);
            if (e instanceof SlackApiException) {
                SlackApiException slackApiException = (SlackApiException) e;
                log.error("Slack API 응답 상태: {}", slackApiException.getResponse());
            }
        }
    }
}
728x90