package com.sparta.springtrello.slack;
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.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;
@Service
public class SlackNotificationService {
@Value("${slack.webhook.url}")
private String slackWebhookUrl;
private final RestTemplate restTemplate = new RestTemplate();
public void sendSlackMessage(String message) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
Map<String, String> body = new HashMap<>();
body.put("text", message);
HttpEntity<Map<String, String>> request = new HttpEntity<>(body, headers);
restTemplate.exchange(slackWebhookUrl, HttpMethod.POST, request, String.class);
}
}
- Slack Api에서 제공하는 webhook기능을 사용했다. 발급받은 URL을 properties에 입력
- 헤더와 메세지를 생성하고, POST요청을 보내는 방식이다.
@PostMapping("/workspaces/{id}/members")
public ResponseEntity<ApiResponseDto<?>> saveMember(@AuthenticationPrincipal AuthUser authUser,
@PathVariable Long id,
@RequestBody MemberSaveRequestDto requestDto){
memberService.saveMember(authUser,id,requestDto);
String slackMessage = String.format("Workspace ID: %d, User ID: %d - 새로운 맴버가 등록되었습니다", id, authUser.getId());
slackNotificationService.sendSlackMessage(slackMessage);
return ResponseEntity.ok(ApiResponseDto.success(null));
}
- 알림설정하고싶은 API가 수행되고 알림기능이 실행될수 있도록 만든 예시(Controller계층에서 설정)