ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Spring boot Discord Webhook Send Message
    6/WEB 2023. 12. 21. 01:56
    Controller
    package discord.controller;
    
    import lunaedies.discord.service.DiscordWebhookService;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.ResponseEntity;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    
    import java.net.URLDecoder;
    
    @Controller
    @RequestMapping("/discord")
    public class DiscordController {
    
        private final DiscordWebhookService discordWebhookService;
        private final String webhookUrl;
        private final String defaultMessage;
    
        // DiscordController 생성자
        public DiscordController(DiscordWebhookService discordWebhookService,
                                 @Value("${discord.webhook.url}") String webhookUrl,
                                 @Value("${discord.default.message}") String defaultMessage) {
            this.discordWebhookService = discordWebhookService;
            this.webhookUrl = webhookUrl;
            this.defaultMessage = defaultMessage;
        }
    
        // Discord에 메시지를 보내는 엔드포인트
        @GetMapping("/send-message")
        public ResponseEntity<String> sendMessageToDiscord(@RequestParam("defaultMessage") String defaultMessage) {
            try {
                // URL 디코딩하여 한글 메시지 복원
                String decodedMessage = URLDecoder.decode(defaultMessage, "UTF-8");
                // DiscordWebhookService를 사용하여 메시지를 보냄
                discordWebhookService.sendMessageToDiscordWebhook(webhookUrl, decodedMessage);
                // 성공적으로 메시지를 보냈음을 반환
                return ResponseEntity.ok("Message sent to Discord!");
            } catch (Exception e) {
                // 예외 처리: 메시지 보내기 실패
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .body("Failed to send message to Discord: " + e.getMessage());
            }
        }
    
        // senderMessage 템플릿을 반환하는 엔드포인트
        @GetMapping("/senderMessage")
        public String showIndex(){
            // senderMessage 템플릿을 클라이언트에 반환하여 보여줌
            return "senderMessage";
        }
    }
    Service
    package discord.service;
    
    import com.fasterxml.jackson.databind.ObjectMapper;
    import lunaedies.discord.vo.DiscordMessage;
    import org.apache.http.HttpResponse;
    import org.apache.http.client.HttpClient;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.StringEntity;
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.stereotype.Service;
    
    import java.io.IOException;
    import java.nio.charset.StandardCharsets;
    
    @Service
    public class DiscordWebhookService {
    
        // Logger 선언
        private static final Logger LOGGER = LoggerFactory.getLogger(DiscordWebhookService.class);
    
        // 의존성 주입
        private final HttpClient httpClient;
        private final ObjectMapper objectMapper;
    
        // 생성자
        public DiscordWebhookService(HttpClient httpClient, ObjectMapper objectMapper) {
            this.httpClient = httpClient;
            this.objectMapper = objectMapper;
        }
    
        // Discord로 메시지 보내는 메서드
        public void sendMessageToDiscordWebhook(String webhookUrl, String message) {
            try {
                // HTTP POST 요청 생성
                HttpPost httpPost = new HttpPost(webhookUrl);
    
                // DiscordMessage 객체 생성 및 JSON으로 직렬화
                DiscordMessage discordMessage = new DiscordMessage(message);
                String json = objectMapper.writeValueAsString(discordMessage);
    
                // JSON을 UTF-8로 인코딩하여 StringEntity 생성
                StringEntity params = new StringEntity(json, StandardCharsets.UTF_8);
    
                // 헤더 설정 (JSON 타입 지정)
                httpPost.setHeader("Content-type", "application/json");
    
                // 요청에 본문 설정
                httpPost.setEntity(params);
    
                // HTTP 요청 보내기
                HttpResponse response = httpClient.execute(httpPost);
    
                // 응답 상태 코드 확인
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 204) {
                    LOGGER.info("Message sent to Discord successfully."); // 성공 로깅
                } else {
                    LOGGER.error("Failed to send message to Discord. Response code: {}", statusCode); // 실패 로깅
                }
            } catch (IOException e) {
                LOGGER.error("Error while sending message to Discord: {}", e.getMessage()); // 예외 발생 시 로깅
            }
        }
    }
    senderMessage.html
    <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8">
        <title>Discord Message Sender</title>
        <!-- 최신 jQuery 버전 추가 -->
        <script src="https://code.jquery.com/jquery-3.7.1.js" integrity="sha256-eKhayi8LEQwp4NKxN+CfCh+3qOVUtJn3QNZ0TciWLP4=" crossorigin="anonymous"></script>
    </head>
    <body>
    <form th:action="@{/discord/send-message}" method="post" id="discordForm">
        <!-- 메시지 입력란 및 전송 버튼 -->
        <label for="message">Message:</label>
        <input type="text" id="message" name="message">
        <button type="button" onclick="sendMessage()">Send</button>
    </form>
    
    <script th:inline="javascript">
        function sendMessage() {
            // 사용자가 입력한 메시지 가져오기
            var message = $("#message").val();
            $.ajax({
                type: "GET",
                url: "/discord/send-message",
                data: { defaultMessage: message }, // defaultMessage라는 이름으로 메시지 데이터 전달
                success: function(response) {
                    // 성공 시 알림 표시 및 입력란 초기화
                    alert(response);
                    $("#message").focus().val("");
                },
                error: function(xhr, status, error) {
                    // 오류 시 알림 표시
                    alert("Error: " + error);
                }
            });
        }
    </script>
    </body>
    </html>
    application.properties
    # application.properties
    
    discord.webhook.url=https://discord.com/api/webhooks/~~~
    discord.default.message=Hello, Discord from Spring Boot!
    build.gradle
        //Spring boot 웹 의존성 추가
        implementation 'org.springframework.boot:spring-boot-starter-web'
        // 테스트용 Spring boot 의존성 추가
        testImplementation 'org.springframework.boot:spring-boot-starter-test'
        //Apache HttpClient 의존성 추가
        implementation group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.14'
        //thymeleaffmf 사용하기 위한 Spring Boot Starter 의존성 추가
        implementation 'org.springframework.boot:spring-boot-starter-thymeleaf'
        //Lombok을 컴파일 타임에만 필요로 하는 의존성 추가
        compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.30'
        //Lombok을 사용하여 어노테이션을 프로세싱하기 위한 의존성 추가
        annotationProcessor 'org.projectlombok:lombok:1.18.30'

    '6 > WEB' 카테고리의 다른 글

    Spring boot 시작  (0) 2024.01.01
    JSP빠르게 시작하기  (0) 2016.02.19
    spring mybatis postgresql 연동  (0) 2015.11.02
Designed by Tistory.