Skip to content

Commit

Permalink
Merge pull request #190 from JNU-econovation/feat-184
Browse files Browse the repository at this point in the history
feat: slack 자동화 메세지 기능 개발
  • Loading branch information
capDoYeonLee authored Dec 3, 2024
2 parents b45646d + f401f8d commit 4fa54b2
Show file tree
Hide file tree
Showing 5 changed files with 123 additions and 18 deletions.
2 changes: 2 additions & 0 deletions BE/error/src/main/java/com/example/demo/ErrorApplication.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@EnableJpaRepositories
@SpringBootApplication
@EnableJpaAuditing
@EnableScheduling
@EnableFeignClients(basePackages = "com.example.demo.auth.infra.oauth.slack.client")
//@OpenAPIDefinition(
// servers = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,11 @@
import com.example.demo.schedule.infrastructure.persistence.ScheduleEntity;
import com.example.demo.schedule.infrastructure.persistence.ScheduleJpaRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand All @@ -26,7 +28,7 @@ public class ScheduleService {
private final ScheduleResponseConverter responseConverter;
private final ScheduleDomainService domainService;
private final ScheduleJpaRepository scheduleJpaRepository;
private final FilterService filterService;
private static final int SCHEDULE_LOOKUP_DAYS = 5;


@Transactional
Expand Down Expand Up @@ -71,12 +73,13 @@ public List<AllPrivateCalendarResponse> getPrivateSchedule() {
return responseConverter.toPrivateModel(model);
}


public List<ScheduleEntity> findWeekendSchedule() {
//List<WeekendSchedule> schedules = new ArrayList<>();
List<ScheduleEntity> test = scheduleJpaRepository.findWeekendPublicSchedule();
if (test.size() == 0) {
System.out.println("empty");
}
return test;

LocalDateTime startDate = LocalDateTime.now();
LocalDateTime endDate = startDate.plusDays(SCHEDULE_LOOKUP_DAYS);

List<ScheduleEntity> schedules = scheduleJpaRepository.findWeekPublic(startDate, endDate);
return schedules;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
package com.example.demo.schedule.infrastructure;

import com.example.demo.auth.infra.oauth.slack.exception.SlackApiException;
import com.example.demo.schedule.application.service.ScheduleService;
import com.example.demo.schedule.infrastructure.persistence.ScheduleEntity;
import com.slack.api.Slack;
import com.slack.api.methods.MethodsClient;
import com.slack.api.methods.request.chat.ChatPostMessageRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

@Service
@Slf4j
@RequiredArgsConstructor
@PropertySource("classpath:/application.properties")
public class SlackService {

@Value("${spring.config.activate.on-profile.oauth.provider.slack.token}")
private String slackToken;
private final ScheduleService scheduleService;
private final static String CHANNEL_NAME = "에코노베이션-일정-소개-페이지";

public void sendSlackMessage(String message, String channel){


try{
MethodsClient methods = Slack.getInstance().methods(slackToken);

ChatPostMessageRequest request = ChatPostMessageRequest.builder()
.channel(CHANNEL_NAME)
.text(message)
.build();

methods.chatPostMessage(request);

log.info("Slack " + channel + " 에 메시지 보냄");

} catch (SlackApiException | IOException e) {
log.error(e.getMessage());
} catch (com.slack.api.methods.SlackApiException e) {
throw new RuntimeException(e);
}
}


public String makeSlackMessage() {
log.info("send slack message");
List<ScheduleEntity> schedules = scheduleService.findWeekendSchedule();

if (schedules.isEmpty()) {
return "이번주는 일정이 존재하지 않습니다.";
}

StringBuilder messageBuilder = new StringBuilder();

for (int i = 0; i < schedules.size(); i++) {
if (i > 0) {
messageBuilder.append("\n\n"); // 일정 사이에 한 줄 추가
}
messageBuilder.append(formatSchedule(schedules.get(i)));
}

return messageBuilder.toString();
}

public String formatSchedule(ScheduleEntity schedule) {
LocalDateTime startDate = schedule.getEventStartDate();

// 날짜와 시간을 지정된 형식으로 변환
String formattedDate = startDate.format(DateTimeFormatter.ofPattern("M월 d일 (E) HH:mm", Locale.KOREAN));

return String.format("(%s)\n- 일시: %s\n- 장소: %s",
schedule.getEventName(),
formattedDate,
schedule.getEventPlace());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,20 @@ public ScheduleEntity save(ScheduleEntity entity) {
}
}



public List<ScheduleEntity> findWeekPublic(LocalDateTime startDate, LocalDateTime endDate) {
return em.createQuery("SELECT s FROM ScheduleEntity s " +
"WHERE s.scheduleType = :scheduleType " +
"AND s.eventStartDate BETWEEN :startDate AND :endDate", ScheduleEntity.class)
.setParameter("scheduleType", "PUBLIC") // scheduleType 파라미터 설정
.setParameter("startDate", startDate) // startDate 파라미터 설정
.setParameter("endDate", endDate) // endDate 파라미터 설정
.getResultList();
}



public List<ScheduleEntity> findWeekendPublicSchedule() {
List<ScheduleEntity> entity = em.createQuery("SELECT s FROM ScheduleEntity s \n" +
"WHERE s.scheduleType = 'PUBLIC' \n" +
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@
import com.example.demo.common.presentation.response.MessageCode;
import com.example.demo.schedule.application.dto.*;
import com.example.demo.schedule.application.service.ScheduleService;
import com.example.demo.schedule.infrastructure.SlackService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.List;
Expand All @@ -19,6 +21,7 @@
public class ScheduleController {

private final ScheduleService scheduleService;
private final SlackService slackService;


@PostMapping
Expand Down Expand Up @@ -71,16 +74,11 @@ public ApiResponse<SuccessBody<List<AllPrivateCalendarResponse>>> getPrivate() {
return ApiResponseGenerator.success(response, HttpStatus.OK, MessageCode.GETALL);
}

// @GetMapping("slack/test")
// public void slackTest() {
//
// String event = slackService.makeSlackMessage();
// slackService.sendSlackMessage(event, "test");
// }
@GetMapping("slack/test")
@Scheduled(cron = "0 0 9 * * MON")
public void sendSlackMessage() {


// 일정 조회를 어떻게 리팩토링 할 수 있을까?
// 하나의 요청 uri를 가지고 내부
// 토큰이 존재한다면? 토근에서 값을 추출 후 memberId에 맞는 private 일정 + public 일정 응답
// 토큰이 존재하지 않다면? public 일정만 응답
String event = slackService.makeSlackMessage();
slackService.sendSlackMessage(event, "test");
}
}

0 comments on commit 4fa54b2

Please sign in to comment.