Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[#17] Make slack message json format #19

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions docker/mariadb/docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
version: '3.1'

services:
db:
image: mariadb
restart: always
environment:
MYSQL_ROOT_PASSWORD: admin
MYSQL_DATABASE: blogposting
MYSQL_USER: blogposting
MYSQL_PASSWORD: blogposting
adminer:
image: adminer
restart: always
ports:
- 8082:8080
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

근데 mariadb를 8080으로 띄우면 실제 서버는 몇번 포트로 띄우실 생각이실까요?


7 changes: 6 additions & 1 deletion study-core/build.gradle
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-batch'
implementation project(':study-slack-api')

runtimeOnly 'com.h2database:h2'

implementation 'org.springframework.boot:spring-boot-starter-batch'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'

testImplementation 'org.springframework.batch:spring-batch-test'
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,35 +1,36 @@
package com.study.service.batch;

import com.study.service.review.Review;
import com.study.service.review.ReviewHistory;
import com.study.service.review.ReviewHistoryRepository;
import com.study.service.review.ReviewRepository;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.study.service.review.*;
import com.study.service.slack.service.SlackService;
import com.study.service.user.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.transaction.Transactional;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Slf4j
@Component
@Transactional
@RequiredArgsConstructor
public class ReviewMatchTasklet implements Tasklet {

private AtomicInteger step = new AtomicInteger();
private final UserRepository userRepository;
private final ReviewRepository reviewRepository;
private final ReviewHistoryRepository reviewHistoryRepository;
private final SlackService slackService;

public ReviewMatchTasklet(UserRepository userRepository, ReviewRepository reviewRepository, ReviewHistoryRepository reviewHistoryRepository) {
this.userRepository = userRepository;
this.reviewRepository = reviewRepository;
this.reviewHistoryRepository = reviewHistoryRepository;
}

@Value("${slack.channel}")
private String channelName;

@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
Expand All @@ -41,7 +42,13 @@ public RepeatStatus execute(StepContribution contribution, ChunkContext chunkCon

reviewHistoryRepository.save(ReviewHistory.from(reviews));

// TODO send Slack API
String sendResult = slackService.sendMessage(
ReviewSlackMessage.makeReviewMatchingMessage(channelName, reviews));

log.info("Call Slack API result : {}", sendResult);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

로그 👍


SlackService s = new SlackService();

return RepeatStatus.FINISHED;
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
package com.study.service.review;

import com.study.service.slack.dto.MessageRequest;
import com.study.service.user.DeveloperType;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import static com.study.service.slack.dto.MessageRequest.SlackBlockType.MRKDWN;
import static com.study.service.slack.dto.MessageRequest.SlackBlockType.SECTION;

/*
* 리뷰 선정 slack api message 생성
*/
public class ReviewSlackMessage {

public static MessageRequest makeReviewMatchingMessage(String channelName, List<Review> reviews) {

LocalDateTime now = LocalDateTime.now();

MessageRequest.SlackBlock headSection = new MessageRequest.SlackBlock(
SECTION,
new MessageRequest.SlackBlockText(
MRKDWN,
String.format("*:mega: %d년 %d월 %d일 리뷰어 매칭*", now.getYear(), now.getMonth().getValue(), now.getDayOfMonth())));

MessageRequest.SlackBlock sectionFront = new MessageRequest.SlackBlock(
SECTION,
new MessageRequest.SlackBlockText(MRKDWN, "*프론트엔드*"));

MessageRequest.SlackBlock sectionFrontBody = new MessageRequest.SlackBlock(
SECTION,
new MessageRequest.SlackBlockText(MRKDWN, makeReviewMessageBody(reviews, DeveloperType.FRONTEND)));

MessageRequest.SlackBlock sectionBackend = new MessageRequest.SlackBlock(
SECTION,
new MessageRequest.SlackBlockText(MRKDWN, "*백엔드*"));

MessageRequest.SlackBlock sectionBackendBody = new MessageRequest.SlackBlock(
SECTION,
new MessageRequest.SlackBlockText(MRKDWN, makeReviewMessageBody(reviews, DeveloperType.BACKEND)));

return new MessageRequest(
channelName,
Arrays.asList(headSection, sectionFront, sectionFrontBody, sectionBackend, sectionBackendBody));
}

private static String makeReviewMessageBody(List<Review> reviews, DeveloperType devType) {
return reviews
.stream()
.filter(e -> e.getReviewer().getDeveloperType().equals(devType))
.map(r -> " - " + r.getReviewer().getName() + " -> " + r.getReviewee().getName())
.reduce("", ((s1, s2) -> s1 + "\n" + s2));
}
}
Original file line number Diff line number Diff line change
@@ -1,11 +1,48 @@
package com.study.service.slack.dto;

import com.fasterxml.jackson.annotation.JsonValue;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.RequiredArgsConstructor;

import java.util.List;

@RequiredArgsConstructor
@Getter
public class MessageRequest {
private final String channel;
private final String text;
private final List<SlackBlock> blocks;

@AllArgsConstructor
@Getter
public static class SlackBlock {
private SlackBlockType type;
private SlackBlockText text;
}

@AllArgsConstructor
@Getter
public static class SlackBlockText {
private SlackBlockType type;
private String text;

}

public enum SlackBlockType {
SECTION("section"), MRKDWN("mrkdwn");

private String name;

SlackBlockType(String name) {
this.name = name;
}

@JsonValue
public String getName() {
return name;
}

}


}
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@
@Slf4j
@Service
public class SlackService {
private static final String SLACK_API_BASE_URL = "https://slack.com/api";
private static final String SLACK_API_BASE_URL = "https://hooks.slack.com";
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

어? 원래 하던 방식으로 안하신 이유가 있나요?
봇으로 관리하는게 더 좋을거 같은데 왜 hooks을 쓰셨나요?

private final WebClient webClient;

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

@Value("${slack.url}")
private String url;

public SlackService() {
final ExchangeStrategies exchangeStrategies = ExchangeStrategies.builder()
.codecs(configurer -> configurer.defaultCodecs().maxInMemorySize(1024 * 1024 * 50))
Expand All @@ -38,7 +41,7 @@ public SlackService() {
.exchangeStrategies(exchangeStrategies)
.filter(ExchangeFilterFunction.ofRequestProcessor(
clientRequest -> {
log.error("Request: {} {} {}", clientRequest.method(), clientRequest.url(),
log.info("Request: {} {} {}", clientRequest.method(), clientRequest.url(),
clientRequest.body());
clientRequest.headers()
.forEach((name, values) -> values.forEach(
Expand All @@ -50,11 +53,11 @@ public SlackService() {
}

public String sendMessage(final MessageRequest messageRequest) {
return webClient.post().uri("/chat.postMessage")
return webClient.post().uri(url)
.header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
.body(BodyInserters.fromValue(messageRequest))
.retrieve()
.bodyToMono(String.class)
.block();
}
}
}
4 changes: 4 additions & 0 deletions study-slack-api/src/main/resources/application-slack.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
slack:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이쪽부분은 일단 삭제 해주세요!

token: my-token
url: ${slack-url}
channel: service개발