컴퓨터 프로그래밍/Spring

[Spring] Discord 알림 구현

한33 2024. 10. 16. 12:35

webhookController

package com.sparta.springusersetting.domain.webhook.controller;

import com.sparta.springusersetting.domain.webhook.service.WebhookService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
public class WebhookController {

    private final WebhookService webhookService;

    @GetMapping("/send-discord")
    public String sendDiscordMessage(@RequestParam String message) {
        webhookService.sendDiscordNotification(message);
        return "알림이 전송되었습니다!";
    }
}

 

webhookService

package com.sparta.springusersetting.domain.webhook.service;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class WebhookService {

    @Value("${spring.webhook.discord-url}")
    private String webhookUrl;

    private final RestTemplate restTemplate = new RestTemplate();

    public void sendDiscordNotification(String template, Object...args) {

        String message = String.format(template,args);

        Map<String, String> body = new HashMap<>();
        body.put("content", message);

        // HTTP 요청 설정
        HttpHeaders headers = new HttpHeaders();
        headers.set("Content-Type", "application/json");

        HttpEntity<Map<String, String>> request = new HttpEntity<>(body, headers);

        // Webhook 호출
        ResponseEntity<String> response = restTemplate.exchange(
                webhookUrl,
                HttpMethod.POST,
                request,
                String.class
        );

        if (response.getStatusCode().is2xxSuccessful()) {
            System.out.println("Discord 알림 전송 성공!");
        } else {
            System.out.println("Discord 알림 전송 실패: " + response.getBody());
        }
    }
}

알람 커스터마이징

ㅇㅇㅇ이 ㅇㅇㅇ에 댓글을 달았습니다 !

ㅇㅇㅇ 이 새로운 멤버가 되었습니다 !

 

와 같이 같은 알람 구현 로직이지만 메세지만 상황에 따라 커스터마이징 해야하는 경우 가용변수 를 키워드로 사용했다.

 

public void sendDiscordNotification(String template, Object...args) {

    String message = String.format(template,args);

 

Object...ars 를 이용해서 정해지지않은 수의 변수를 받아서 template 을 만들어서 들어왔다.

 

webhookService.sendDiscordNotification("%s 님이 새로운 회원이 되셨어요 !", newUser.getUserName());
webhookService.sendDiscordNotification(
        "%s 님이 <%s> 카드에 댓글을 달았어요 ! [ %s (%s) ]",
        user.getUserName(),
        card.getTitle(),
        requestDto.getContent(),
        requestDto.getCommentEmoji()
);

 

가용변수를 이용하면 위와 같이 커스터마이징해서 상황에 따라 알림 문구를 만들어서 띄울 수 있다.

 

문자열은 Enum 으로 관리해도 좋을 것 같다.


application.yml

webhook:
  discord-url : ${DISCORD_URL}

 

spring: 아래에 위와 같이 설정을 해주었다.

 

discord-url 에는 discrod 채널 생성 후 해당 웹 후크 URI 를 넣어주면 된다.