프로젝트
[Spring Boot] 슬랙 메시지 보내기(Incoming WebHooks)
LeeBorn
2020. 10. 5. 21:03
반응형
슬랙의 "Incoming WebHooks"을 이용해서 메시지를 보내는 방법이다.
먼저 슬랙에서 앱의 설치 및 설정이 필요하다.
1. 슬랙을 설치하고, "Incoming WebHooks" 앱을 추가한다.
2. 앱의 설정으로 이동한다.
3. 보낼 채널을 선택하고, Webhook URL을 복사한다.
- 아래부턴 직접 작성하면 된다.
4. 아래 코드를 작성한다.
url에 3에서 복사한 Webhook URL을 넣어주기만 하면 된다.
import java.util.HashMap;
import java.util.Map;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
@RestController
public class RestMainController {
@GetMapping("/send")
public void send(){
RestTemplate restTemplate = new RestTemplate();
Map<String,Object> request = new HashMap<String,Object>();
request.put("username", "slackbot");
request.put("text", "custom-slack-msg");
HttpEntity<Map<String,Object>> entity = new HttpEntity<Map<String,Object>>(request);
String url = "https://hooks.slack.com/services/~~~~~~~~~"; // 사용할 슬랙의 Webhook URL 넣기
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
}
}
5. 채널에서 메시지를 확인한다.
소스는 최대한 단순하게 적으려고 text를 보냈지만,
메시지는 다양한 템플릿으로 전송할 수 있다.
반응형