컨트롤러 코드를 첨부하여 설명드리겠습니다.
먼저 컨트롤러가 생성되며 패치노트들을 저장할 PatchNotesStorage
객체를 만듭니다. MyCrawler
에서도 패치노트를 push하기 위해 PatchNotesStorage
가 필요하기 때문에 이를 싱글톤으로 만들 것을 고려했습니다. 하지만 어차피 이 두 군데 말고는 쓰일 일이 없어서 컨트롤러가 직접 넣어주는 방식을 선택했습니다.
run
method는 5분 주기로 반복됩니다.
crawler
에게 crawl을 시켰을 때, 문제가 없다면 crawler
가 직접 웹페이지에서 가져온 패치노트들을 PatchNotesStorage
에 push합니다. 그러고 나면 PatchNotesStorage
는 getNews
메소드를 통해 이전에 갖고있던 내용에 없는 새로운 내용을 추출합니다.
새로운 내용이 있다면 PatchNotesUtils
의 static 메소드인 parseNews
를 통해서 메시지를 가볍게 가공 후 디스코드 채팅방에 전달합니다.
(디스코드 방에 마크다운 문법이 적용되는 점도 호감입니다!)
package bnbnac.discordBot;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel;
import java.util.List;
import static bnbnac.discordBot.PatchNotesUtils.parseNews;
public class Controller {
public PatchNotesStorage patchNotesStorage;
public Crawler crawler;
JDA myJDA;
MessageChannel channel;
public Controller() {
patchNotesStorage = new PatchNotesStorage();
crawler = new MyCrawler(patchNotesStorage);
myJDA = new MyJDABuilder().build();
channel = null;
}
public void run() {
if (channel == null) {
channel = getChannel();
}
boolean needToSendFailMessage = crawler.crawl();
if (needToSendFailMessage) {
channel.sendMessage("홈페이지에 다시 연결되었습니다.");
return;
}
List<String> news = patchNotesStorage.getNews();
if (news.isEmpty()) {
return;
}
List<String> messages = parseNews(news, patchNotesStorage.getCurPatchNotes());
for (String message : messages) {
channel.sendMessage(message).queue();
}
}
public MessageChannel getChannel() {
String channelId = SecretReader.read(SecretReader.CHANNEL_ID);
return myJDA.getTextChannelById(channelId);
}
}