Skip to content
This repository has been archived by the owner on Aug 2, 2023. It is now read-only.

Commit

Permalink
feat: ChatBot実装 (#886)
Browse files Browse the repository at this point in the history
* feat: ChatBot実装

* fix: 5文字未満の通常会話の場合はAPIに投げない

* fix: 通信含めて非同期に変更
  • Loading branch information
book000 authored Jul 26, 2022
1 parent 0f981a5 commit ec8eb99
Show file tree
Hide file tree
Showing 6 changed files with 248 additions and 77 deletions.
8 changes: 8 additions & 0 deletions src/main/java/com/jaoafa/mymaid4/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ public final class Main extends JavaPlugin {
private static MyMaidConfig config = null;
private static Rollbar rollbar = null;
private MinecraftHelp<CommandSender> minecraftHelp;
private static MeboChatBot meboChatBot = null;

@Override
public void onEnable() {
Expand Down Expand Up @@ -105,6 +106,10 @@ public void onEnable() {
MyMaidData.setBlacklist(new Blacklist());

initCreativeInventoryItems();

if (config.getMeboApiKey() != null && config.getMeboAgentId() != null) {
meboChatBot = new MeboChatBot(config.getMeboApiKey(), config.getMeboAgentId());
}
}

@Override
Expand Down Expand Up @@ -511,4 +516,7 @@ public static Rollbar getRollbar() {
return rollbar;
}

public static MeboChatBot getMeboChatBot() {
return meboChatBot;
}
}
70 changes: 70 additions & 0 deletions src/main/java/com/jaoafa/mymaid4/command/Cmd_ChatBot.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
/*
* jaoLicense
*
* Copyright (c) 2022 jao Minecraft Server
*
* The following license applies to this project: jaoLicense
*
* Japanese: https://github.com/jaoafa/jao-Minecraft-Server/blob/master/jaoLICENSE.md
* English: https://github.com/jaoafa/jao-Minecraft-Server/blob/master/jaoLICENSE-en.md
*/

package com.jaoafa.mymaid4.command;

import cloud.commandframework.Command;
import cloud.commandframework.arguments.standard.StringArgument;
import cloud.commandframework.context.CommandContext;
import cloud.commandframework.meta.CommandMeta;
import com.jaoafa.mymaid4.Main;
import com.jaoafa.mymaid4.lib.CommandPremise;
import com.jaoafa.mymaid4.lib.MeboChatBot;
import com.jaoafa.mymaid4.lib.MyMaidCommand;
import com.jaoafa.mymaid4.lib.MyMaidLibrary;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;

import java.util.List;

public class Cmd_ChatBot extends MyMaidLibrary implements CommandPremise {
@Override
public MyMaidCommand.Detail details() {
return new MyMaidCommand.Detail(
"chatbot",
List.of("q", "question", "質問", "しつもん"),
"よくある質問への応対をします。"
);
}

@Override
public MyMaidCommand.Cmd register(Command.Builder<CommandSender> builder) {
return new MyMaidCommand.Cmd(
builder
.meta(CommandMeta.DESCRIPTION, "よくある質問への応対をします。")
.argument(StringArgument.greedy("text"))
.handler(this::question)
.build()
);
}

void question(CommandContext<CommandSender> context) {
Player player = (Player) context.getSender();
String text = context.get("text");

if (Main.getMeboChatBot() == null) {
SendMessage(player, details(), "チャットに必要な情報が定義されていません。");
return;
}

MeboChatBot chatBot = Main.getMeboChatBot();
MeboChatBot.MeboResponse response = chatBot.chat(player, text);
if (response == null) {
SendMessage(player, details(), "チャットに必要な情報が定義されていません。");
return;
}
if (!response.status()) {
SendMessage(player, details(), "なんかうまくいきませんでした。");
return;
}
SendMessage(player, details(), response.message());
}
}
59 changes: 59 additions & 0 deletions src/main/java/com/jaoafa/mymaid4/event/Event_ChatBot.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* jaoLicense
*
* Copyright (c) 2022 jao Minecraft Server
*
* The following license applies to this project: jaoLicense
*
* Japanese: https://github.com/jaoafa/jao-Minecraft-Server/blob/master/jaoLICENSE.md
* English: https://github.com/jaoafa/jao-Minecraft-Server/blob/master/jaoLICENSE-en.md
*/

package com.jaoafa.mymaid4.event;

import com.jaoafa.mymaid4.Main;
import com.jaoafa.mymaid4.lib.EventPremise;
import com.jaoafa.mymaid4.lib.MeboChatBot;
import com.jaoafa.mymaid4.lib.MyMaidLibrary;
import io.papermc.paper.event.player.AsyncChatEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.scheduler.BukkitRunnable;

public class Event_ChatBot extends MyMaidLibrary implements Listener, EventPremise {
@Override
public String description() {
return "ChatBotに関する処理を行います。";
}

@EventHandler
public void onAsyncPlayerChatEvent(AsyncChatEvent event) {
Player player = event.getPlayer();
String content = PlainTextComponentSerializer.plainText().serialize(event.message());

if (content.length() < 5) {
return;
}

new BukkitRunnable() {
public void run() {
MeboChatBot chatBot = Main.getMeboChatBot();
MeboChatBot.MeboResponse response = chatBot.chat(player, content);
if (response == null) {
return;
}
if (!response.status()) {
return;
}
if (response.score() < 85) {
return;
}

MyMaidLibrary.chatFake(NamedTextColor.GOLD, "jaotan", response.message(), true);
}
}.runTaskLaterAsynchronously(Main.getMain(), 10L);
}
}
77 changes: 0 additions & 77 deletions src/main/java/com/jaoafa/mymaid4/event/Event_WhereAreYou.java

This file was deleted.

89 changes: 89 additions & 0 deletions src/main/java/com/jaoafa/mymaid4/lib/MeboChatBot.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/*
* jaoLicense
*
* Copyright (c) 2022 jao Minecraft Server
*
* The following license applies to this project: jaoLicense
*
* Japanese: https://github.com/jaoafa/jao-Minecraft-Server/blob/master/jaoLICENSE.md
* English: https://github.com/jaoafa/jao-Minecraft-Server/blob/master/jaoLICENSE-en.md
*/

package com.jaoafa.mymaid4.lib;

import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.event.ClickEvent;
import net.kyori.adventure.text.event.HoverEvent;
import net.kyori.adventure.text.format.NamedTextColor;
import net.kyori.adventure.text.format.TextDecoration;
import okhttp3.*;
import org.bukkit.entity.Player;
import org.json.JSONObject;

import java.io.IOException;

public class MeboChatBot {
private final String apiKey;
private final String agentId;

public MeboChatBot(String apiKey, String agentId) {
this.apiKey = apiKey;
this.agentId = agentId;
}

public MeboResponse chat(Player player, String text) {
try {
String url = "https://api-mebo.dev/api";
OkHttpClient client = new OkHttpClient();
JSONObject json = new JSONObject();
json.put("api_key", apiKey);
json.put("agent_id", agentId);
json.put("utterance", text);
json.put("uid", player.getUniqueId().toString());

RequestBody requestBody = RequestBody.create(json.toString(), MediaType.parse("application/json; charset=UTF-8"));
Request request = new Request.Builder().url(url).post(requestBody).build();
Response response = client.newCall(request).execute();
if (response.code() != 200) {
response.close();
return new MeboResponse(false, 0, "HTTP Error: " + response.code(), null);
}

ResponseBody body = response.body();
if (body == null) throw new RuntimeException();

JSONObject jsonObject = new JSONObject(body.string());
response.close();

if (!jsonObject.has("bestResponse")) {
return new MeboResponse(false, 0, "No bestResponse", null);
}
// Main.getMyMaidLogger().info("MeboChatBot: " + jsonObject.getJSONObject("bestResponse").toString());

return new MeboResponse(
true,
jsonObject.getJSONObject("bestResponse").getDouble("score"),
jsonObject.getJSONObject("bestResponse").getString("utterance"),
jsonObject.getJSONObject("bestResponse").getString("url")
);
} catch (IOException e) {
e.printStackTrace();
return new MeboResponse(false, 0, "IOException", null);
}
}

public record MeboResponse(boolean status, double score, String rawMessage, String url) {
public Component message() {
if (url != null) {
return Component
.text(rawMessage)
.append(
Component.text(url, NamedTextColor.AQUA, TextDecoration.UNDERLINED)
.hoverEvent(HoverEvent.showText(Component.text("クリックすると「" + url + "」をブラウザで開きます。")))
.clickEvent(ClickEvent.openUrl(url))
);
}
return Component.text(rawMessage);
}
}
}
22 changes: 22 additions & 0 deletions src/main/java/com/jaoafa/mymaid4/lib/MyMaidConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public class MyMaidConfig {
private Long serverChatChannelId = null;
private String githubAccessToken = null;
private String rollbarAccessToken = null;
private String meboApiKey = null;
private String meboAgentId = null;

public void init() {
JavaPlugin plugin = Main.getJavaPlugin();
Expand Down Expand Up @@ -136,6 +138,18 @@ public void init() {
} else {
plugin.getLogger().warning(notFoundConfigKey("rollbarAccessToken"));
}

if (config.contains("meboApiKey")) {
meboApiKey = config.getString("meboApiKey");
} else {
plugin.getLogger().warning(notFoundConfigKey("meboApiKey"));
}

if (config.contains("meboAgentId")) {
meboAgentId = config.getString("meboAgentId");
} else {
plugin.getLogger().warning(notFoundConfigKey("meboAgentId"));
}
}

String notFoundConfigKey(String key) {
Expand Down Expand Up @@ -174,4 +188,12 @@ public String getGitHubAccessToken() {
public String getRollbarAccessToken() {
return rollbarAccessToken;
}

public String getMeboApiKey() {
return meboApiKey;
}

public String getMeboAgentId() {
return meboAgentId;
}
}

0 comments on commit ec8eb99

Please sign in to comment.