Skip to content

Commit

Permalink
impl gpt, vs, youtube, vs command
Browse files Browse the repository at this point in the history
  • Loading branch information
irostub committed Dec 30, 2023
1 parent d90c46e commit 266280a
Show file tree
Hide file tree
Showing 20 changed files with 746 additions and 6 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package com.irostub.domain.entity.standard;

import com.irostub.domain.entity.BaseEntity;
import lombok.Getter;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.time.LocalDateTime;

@Getter
@Entity
public class Music extends BaseEntity {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String description;
private String url;
private String videoId;

protected Music() {
}

public Music(String title, String description, String url, String videoId) {
this.title = title;
this.description = description;
this.url = url;
this.videoId = videoId;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.irostub.domain.repository;


import com.irostub.domain.entity.standard.Music;
import org.springframework.data.jpa.repository.JpaRepository;

public interface MusicRepository extends JpaRepository<Music, Long> {
Boolean existsByVideoId(String videoId);
}
16 changes: 16 additions & 0 deletions whaple-standard/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,22 @@
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.google.api-client</groupId>
<artifactId>google-api-client</artifactId>
<version>1.23.0</version>
</dependency>
<dependency>
<groupId>com.google.oauth-client</groupId>
<artifactId>google-oauth-client-jetty</artifactId>
<version>1.23.0</version>
</dependency>
<dependency>
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-youtube</artifactId>
<version>v3-rev222-1.25.0</version>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,19 @@ public final boolean executeCommand(AbsSender absSender, Message message) {
String[] commandSplit = StringUtils.split(commandMessage, BotCommand.COMMAND_PARAMETER_SEPARATOR);

String command = commandSplit[0];
if("help".equals(command) || "도움".equals(command) || "h".equals(command)){
commandHolderMap.get("도움말").processMessage(absSender,message, new String[]{});
return true;
}

if (commandHolderMap.containsKey(commandSplit[0])) {
String[] parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length);

String[] parameters;
try {
parameters = Arrays.copyOfRange(commandSplit, 1, commandSplit.length);
} catch (Exception e) {
parameters = new String[]{};
}
commandHolderMap.get(command).processMessage(absSender, message, parameters);
return true;
} else if (defaultConsumer != null) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,11 @@

import com.irostub.standard.bot.checkio.CheckIoCommand;
import com.irostub.standard.bot.fridaylunch.FridayLunchCommand;
import com.irostub.standard.bot.gpt.GptCommand;
import com.irostub.standard.bot.hangang.HangangCommand;
import com.irostub.standard.bot.music.MusicCommand;
import com.irostub.standard.bot.rps.RpsCommand;
import com.irostub.standard.bot.vs.VsCommand;
import com.irostub.standard.bot.weather_alert.WeatherAlertCommand;
import com.irostub.standard.bot.ping.PingCommand;
import com.irostub.standard.bot.restaurant.RestaurantCommand;
Expand All @@ -22,7 +26,10 @@ public class CommandHolderConfig {
private final FridayLunchCommand fridayLunchCommand;
private final CheckIoCommand checkIoCommand;
private final WeatherAlertCommand weatherAlertCommand;

private final RpsCommand rpsCommand;
private final VsCommand vsCommand;
private final GptCommand gptCommand;
private final MusicCommand musicCommand;
@Bean
public CommandHolder commandHolder(){
CommandHolder commandHolder = new CommandHolder();
Expand All @@ -34,6 +41,10 @@ public CommandHolder commandHolder(){
commandHolder.register(fridayLunchCommand);
commandHolder.register(checkIoCommand);
commandHolder.register(weatherAlertCommand);
commandHolder.register(rpsCommand);
commandHolder.register(vsCommand);
commandHolder.register(gptCommand);
commandHolder.register(musicCommand);
return commandHolder;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,8 @@
public class HelpCommand extends ManCommand {

private static final String COMMAND_IDENTIFIER = "도움말";
private static final String COMMAND_DESCRIPTION = "모든 명령어를 보여줍니다. {i}도움말 [명령] 을 사용하여 명령의 사용 방법을 볼 수 있습니다.";
private static final String EXTENDED_DESCRIPTION = "이 명령은 봇에서 사용할 수 있는 모든 명령을 표시합니다.\n {i}도움말 [명령] 을 사용하여 더 자세한 명령을 확인할 수 있습니다.";
private static final String COMMAND_DESCRIPTION = "모든 명령어를 보여줍니다. {i}도움말 [명령어] 을 사용하여 명령의 사용 방법을 볼 수 있습니다.";
private static final String EXTENDED_DESCRIPTION = "이 명령은 봇에서 사용할 수 있는 모든 명령을 표시합니다.\n {i}도움말 [명령어] 을 사용하여 더 자세한 명령을 확인할 수 있습니다.\n 문의사항은 쿠버네티스그룹 신동민을 찾아주세요.";

public static String getHelpText(IBotCommand...botCommands) {
StringBuilder reply = new StringBuilder();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import com.irostub.standard.bot.config.AccountHolder;
import com.irostub.standard.bot.config.AppProperties;
import com.irostub.standard.bot.fridaylunch.FridayCallbackAction;
import com.irostub.standard.bot.reactive.MusicCallbackAction;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
Expand All @@ -25,21 +26,26 @@ public class WhapleBot extends TelegramLongPollingBot {
private final ChatGroupUserService chatGroupUserService;
private final AccountService accountService;
private final FridayCallbackAction fridayCallbackAction;
private final MusicCallbackAction musicCallbackAction;

@Autowired
public WhapleBot(CommandHolder commandHolder,
AppProperties appProperties,
ChatGroupUserService chatGroupUserService,
AccountService accountService,
FridayCallbackAction fridayCallbackAction) {
FridayCallbackAction fridayCallbackAction,
MusicCallbackAction musicCallbackAction) {
super(appProperties.getBot().getToken());
this.commandHolder = commandHolder;
this.properties = appProperties;
this.chatGroupUserService = chatGroupUserService;
this.accountService = accountService;
// this.callBackHolder = callBackHolder;
this.fridayCallbackAction = fridayCallbackAction;
this.musicCallbackAction = musicCallbackAction;
}


@Override
public void onUpdateReceived(Update update) {
if (update.hasMessage()) {
Expand All @@ -52,6 +58,7 @@ public void onUpdateReceived(Update update) {
return;
}
}

processNonCommandUpdate(update);
}

Expand Down Expand Up @@ -112,6 +119,10 @@ void processNonCommandUpdate(Update update){
if (update.getCallbackQuery().getData().equals("friday")) {
fridayCallbackAction.callback(this, update);
}

if (update.getCallbackQuery().getData().startsWith("music")) {
musicCallbackAction.callback(this, update);
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ public class AppProperties {
private PublicApi publicApi;
private Kakao kakao;
private String scrumId;

private String chatgptToken;
private String youtubeToken;
private String youtubeAppName;
@Data
public static class Bot{
private String token;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
package com.irostub.standard.bot.gpt;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.irostub.standard.bot.DefaultBotCommand;
import com.irostub.standard.bot.IManCommand;
import com.irostub.standard.bot.config.AppProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.telegram.telegrambots.meta.api.methods.send.SendMessage;
import org.telegram.telegrambots.meta.api.objects.Chat;
import org.telegram.telegrambots.meta.api.objects.User;
import org.telegram.telegrambots.meta.bots.AbsSender;
import org.telegram.telegrambots.meta.exceptions.TelegramApiException;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.List;

@Service
@Slf4j
public class GptCommand extends DefaultBotCommand implements IManCommand {
private final AppProperties appProperties;

public GptCommand(AppProperties appProperties) {
super("gpt", "AI 를 통해 질문에 답변합니다.");
this.appProperties = appProperties;
}

@Override
public String getExtendedDescription() {
return "!gpt [질문]\n" +
"\n" +
"---예시---\n" +
"!gpt 오늘은 날씨가 좋아. 뭘 해야 할까?";
}

@Override
public void execute(AbsSender absSender, User user, Chat chat, Integer messageId, String[] arguments) {
if (arguments.length < 1) {
SendMessage message = SendMessage.builder()
.chatId(chat.getId())
.text("질문이 없는 것 같습니다..")
.build();
sendMessage(absSender, message);
return;
}

String prompt = String.join(COMMAND_PARAMETER_SEPARATOR, arguments);

GptMessage gptSystem = new GptMessage();
gptSystem.setRole("system");
gptSystem.setContent("당신은 프로그래밍의 전문가입니다. " +
"JAVA, GO, Javascript 등의 각종 언어에 능숙 합니다. " +
"또한, React, Spring 과 같은 개발 프레임워크에 대해서도 잘 알고 있습니다. " +
"당신은 Kubernetes 또한 매우 잘 알고 있습니다. " +
"데이터 서치하고 이를 기반으로 사용자가 질문한 내용에 사실만 답변을 합니다." +
"유저를 반드시 선생님 이라고 부르십시오. ");

GptMessage gptUser = new GptMessage();
gptUser.setRole("user");
gptUser.setContent(prompt);

ObjectMapper mapper = new ObjectMapper();
GptRequest chatGptRequest = new GptRequest("gpt-3.5-turbo", List.of(gptSystem, gptUser), 1, null);
String input;
try {
input = mapper.writeValueAsString(chatGptRequest);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}

HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://api.openai.com/v1/chat/completions"))
.header("Content-Type", "application/json")
.header("Authorization", appProperties.getChatgptToken())
.POST(HttpRequest.BodyPublishers.ofString(input))
.build();

HttpClient client = HttpClient.newHttpClient();
HttpResponse<String> response = null;
try {
response = client.send(request, HttpResponse.BodyHandlers.ofString());
} catch (Throwable e) {
log.error("http communication error, e=",e);
}

if (response.statusCode() == 200) {
GptResponse chatGptResponse = null;
try {
chatGptResponse = mapper.readValue(response.body(), GptResponse.class);
} catch (JsonProcessingException e) {
log.error("parse error, e=",e);
}
String answer = chatGptResponse.getChoices()[chatGptResponse.getChoices().length-1].getMessage().getContent();

if (!answer.isEmpty()) {
SendMessage message = SendMessage.builder()
.chatId(chat.getId())
.text(answer)
.parseMode("Markdown")
.build();
sendMessage(absSender, message);
}
} else {
log.error("status code={}, error={}",response.statusCode(),response.body());
}
}
private void sendMessage(AbsSender absSender, SendMessage send) {
try {
absSender.execute(send);
} catch (TelegramApiException e) {
throw new RuntimeException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
package com.irostub.standard.bot.gpt;

import lombok.Data;

@Data
public class GptMessage {
private String role;
private String content;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.irostub.standard.bot.gpt;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@AllArgsConstructor
@NoArgsConstructor
@Data
public class GptRequest {
private String model;
private List<GptMessage> messages = new ArrayList<>();
private int temperature;
private Integer max_tokens;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package com.irostub.standard.bot.gpt;

import lombok.Data;

@Data
public class GptResponse {
private String id;
private String object;
private int created;
private String model;
private GptResponseChoice[] choices;
private GptResponseUsage usage;
private Object system_fingerprint;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.irostub.standard.bot.gpt;

import lombok.Data;

@Data
public class GptResponseChoice {
private int index;
private GptMessage message;
private Object logprobs;
private String finish_reason;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.irostub.standard.bot.gpt;

import lombok.Data;

@Data
public class GptResponseUsage {
private int prompt_tokens;
private int completion_tokens;
private int total_tokens;
}
Loading

0 comments on commit 266280a

Please sign in to comment.