diff --git a/README.md b/README.md index 37e492d..cbab248 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,6 @@ 专为AllayMC设计的下一代基岩版服务器管理解决方案,提供安全的无第三方QQ机器人依赖管理体验。 -> [!NOTE] -> 由于技术原因,暂时无法为Allay提供命令回调,请等待后续更新. -> ## 🌟 核心优势 | 特性 | 传统方案 | HuHoBot | diff --git a/build.gradle.kts b/build.gradle.kts index d57c198..9ddfc7f 100644 --- a/build.gradle.kts +++ b/build.gradle.kts @@ -5,9 +5,9 @@ plugins { id("com.github.johnrengelman.shadow") version "8.1.1" } -group = "cn.huohuas001.huHoBot" +group = "cn.huohuas001.huhobot" description = "HuHoBot Allay Adapter" -version = "0.0.10" +version = "0.1.0" java { toolchain { @@ -21,7 +21,7 @@ repositories { } dependencies { - compileOnly(group = "org.allaymc.allay", name = "api", version = "0.13.0") + compileOnly(group = "org.allaymc.allay", name = "api", version = "0.14.0") compileOnly(group = "org.projectlombok", name = "lombok", version = "1.18.34") implementation(group = "org.java-websocket", name = "Java-WebSocket", version = "1.5.4") diff --git a/src/main/java/cn/huohuas001/huHoBot/Api/BotCustomCommand.java b/src/main/java/cn/huohuas001/huHoBot/Api/BotCustomCommand.java deleted file mode 100644 index 67dae0d..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/Api/BotCustomCommand.java +++ /dev/null @@ -1,40 +0,0 @@ -package cn.huohuas001.huHoBot.Api; - -import cn.huohuas001.huHoBot.HuHoBot; -import cn.huohuas001.huHoBot.WsClient; -import com.alibaba.fastjson2.JSONObject; -import lombok.AccessLevel; -import lombok.Getter; -import org.allaymc.api.eventbus.event.CancellableEvent; -import org.allaymc.api.eventbus.event.Event; - -import java.util.List; - -@Getter -public class BotCustomCommand extends Event implements CancellableEvent { - - private final String command; - private final JSONObject data; - private final List param; - @Getter(AccessLevel.NONE) - private final String packId; - private final boolean runByAdmin; - - public BotCustomCommand(String command, JSONObject data, String packId, boolean runByAdmin) { - this.command = command; - this.data = data; - this.param = data.getList("runParams", String.class); - this.packId = packId; - this.runByAdmin = runByAdmin; - } - - public void respone(String msg, String type) { - WsClient client = HuHoBot.getClientManager().getClient(); - client.respone(msg, type, packId); - } - - public void respone(JSONObject msg, String type) { - WsClient client = HuHoBot.getClientManager().getClient(); - client.respone(msg.toJSONString(), type, packId); - } -} diff --git a/src/main/java/cn/huohuas001/huHoBot/Command/HuHoBotCommand.java b/src/main/java/cn/huohuas001/huHoBot/Command/HuHoBotCommand.java index 5a4d55c..ed2cc79 100644 --- a/src/main/java/cn/huohuas001/huHoBot/Command/HuHoBotCommand.java +++ b/src/main/java/cn/huohuas001/huHoBot/Command/HuHoBotCommand.java @@ -1,7 +1,7 @@ -package cn.huohuas001.huHoBot.Command; +package cn.huohuas001.huhobot.command; -import cn.huohuas001.huHoBot.HuHoBot; -import cn.huohuas001.huHoBot.NetEvent.bindRequest; +import cn.huohuas001.huhobot.HuHoBot; +import cn.huohuas001.huhobot.websocket.handler.BindRequest; import org.allaymc.api.command.Command; import org.allaymc.api.command.tree.CommandTree; import org.allaymc.api.permission.PermissionGroups; @@ -18,7 +18,7 @@ public void prepareCommandTree(CommandTree tree) { tree.getRoot() .key("reconnect") .exec(context -> { - if (HuHoBot.getPlugin().reconnect()) { + if (HuHoBot.getInstance().reconnect()) { context.addOutput(TextFormat.GOLD + "重连机器人成功."); } else { context.addOutput(TextFormat.DARK_RED + "重连机器人失败:已在连接状态."); @@ -29,7 +29,7 @@ public void prepareCommandTree(CommandTree tree) { .root() .key("disconnect") .exec(context -> { - if (HuHoBot.getPlugin().disConnectServer()) { + if (HuHoBot.getInstance().disConnectServer()) { context.addOutput(TextFormat.GOLD + "已断开机器人连接."); } return context.success(); @@ -39,7 +39,7 @@ public void prepareCommandTree(CommandTree tree) { .str("code") .exec(context -> { String Code = context.getResult(1); - bindRequest obj = HuHoBot.getPlugin().bindRequestObj; + BindRequest obj = HuHoBot.getInstance().getBindRequest(); if (obj.confirmBind(Code)) { context.addOutput(TextFormat.GOLD + "已向服务器发送确认绑定请求,请等待服务端下发配置文件."); } else { @@ -63,6 +63,12 @@ public void prepareCommandTree(CommandTree tree) { HuHoBot.reloadConfig(); context.addOutput(TextFormat.GOLD + "已重载配置文件."); return context.success(); + }) + .root() + .key("test") + .exec(ctx -> { + HuHoBot.getInstance().runCommand("version", ""); + return ctx.success(); }); } diff --git a/src/main/java/cn/huohuas001/huHoBot/GameEvent/GameEventListener.java b/src/main/java/cn/huohuas001/huHoBot/GameEvent/GameEventListener.java deleted file mode 100644 index 50e54c2..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/GameEvent/GameEventListener.java +++ /dev/null @@ -1,29 +0,0 @@ -package cn.huohuas001.huHoBot.GameEvent; - -import cn.huohuas001.huHoBot.HuHoBot; -import cn.huohuas001.huHoBot.Settings.PluginConfig; -import com.alibaba.fastjson2.JSONObject; -import org.allaymc.api.eventbus.EventHandler; -import org.allaymc.api.eventbus.event.player.PlayerChatEvent; - -public class GameEventListener { - @EventHandler - private void onPlayerChat(PlayerChatEvent event) { - String message = event.getMessage(); - String playerName = event.getPlayer().getDisplayName(); - - PluginConfig config = HuHoBot.getConfig(); - - String format = config.getChatConfig().getFromGame(); - String prefix = config.getChatConfig().getPostPrefix(); - boolean isPostChat = config.getChatConfig().isPostChat(); - String serverId = config.getServerId(); - if (message.startsWith(prefix) && isPostChat) { - JSONObject body = new JSONObject(); - body.put("serverId", serverId); - String formated = format.replace("{name}", playerName).replace("{msg}", message.substring(prefix.length())); - body.put("msg", formated); - HuHoBot.getClientManager().getClient().sendMessage("chat", body); - } - } -} diff --git a/src/main/java/cn/huohuas001/huHoBot/HuHoBot.java b/src/main/java/cn/huohuas001/huHoBot/HuHoBot.java index e047495..4e79091 100644 --- a/src/main/java/cn/huohuas001/huHoBot/HuHoBot.java +++ b/src/main/java/cn/huohuas001/huHoBot/HuHoBot.java @@ -1,16 +1,15 @@ -package cn.huohuas001.huHoBot; +package cn.huohuas001.huhobot; -import cn.huohuas001.huHoBot.Command.HuHoBotCommand; -import cn.huohuas001.huHoBot.GameEvent.GameEventListener; -import cn.huohuas001.huHoBot.NetEvent.*; -import cn.huohuas001.huHoBot.Settings.PluginConfig; +import cn.huohuas001.huhobot.command.HuHoBotCommand; +import cn.huohuas001.huhobot.utils.HuHoBotCommandSender; +import cn.huohuas001.huhobot.websocket.WSClientManager; +import cn.huohuas001.huhobot.websocket.handler.*; import com.alibaba.fastjson2.JSONObject; import eu.okaeri.configs.ConfigManager; import eu.okaeri.configs.yaml.snakeyaml.YamlSnakeYamlConfigurer; import lombok.Getter; -import lombok.extern.slf4j.Slf4j; -import org.allaymc.api.command.CommandResult; -import org.allaymc.api.command.CommandSender; +import org.allaymc.api.eventbus.EventHandler; +import org.allaymc.api.eventbus.event.player.PlayerChatEvent; import org.allaymc.api.plugin.Plugin; import org.allaymc.api.registry.Registries; import org.allaymc.api.server.Server; @@ -19,20 +18,24 @@ import java.util.HashMap; import java.util.Map; -@Slf4j public class HuHoBot extends Plugin { + private static final String CONFIG_FILE_NAME = "plugins/HuHoBot/config.yml"; + + @Getter private static HuHoBot instance; @Getter - private static PluginConfig config; + private static HuHoBotConfig config; @Getter - private static WebsocketClientManager clientManager; //Websocket客户端 - private final Map eventList = new HashMap<>(); //事件列表 + private static WSClientManager clientManager; //Websocket客户端 - public bindRequest bindRequestObj; + private final Map requestHandlers; //事件处理器列表 + + @Getter + private BindRequest bindRequest; - public static HuHoBot getPlugin() { - return instance; + public HuHoBot() { + this.requestHandlers = new HashMap<>(); } public static void reloadConfig() { @@ -40,18 +43,13 @@ public static void reloadConfig() { config.save(); } - @Override - public void onEnable() { - Server.getInstance().getEventBus().registerListener(new GameEventListener()); - } - @Override public void onLoad() { instance = this; // 创建配置管理器 config = ConfigManager.create( - PluginConfig.class, + HuHoBotConfig.class, it -> { // Specify configurer implementation, optionally additional serdes packages it.withConfigurer(new YamlSnakeYamlConfigurer()); @@ -66,51 +64,52 @@ public void onLoad() { } ); - // 初始化默认值 - config.initializeDefaults(); - config.save(); - //注册命令 Registries.COMMANDS.register(new HuHoBotCommand()); //注册事件 - totalRegEvent(); + registerRequestHandlers(); + pluginLogger.info("HuHoBot Loaded. By HuoHuas001"); + } + + @Override + public void onEnable() { //连接 - clientManager = new WebsocketClientManager(); + clientManager = new WSClientManager(); clientManager.connectServer(); - log.info("HuHoBot Loaded. By HuoHuas001"); + Server.getInstance().getEventBus().registerListener(this); } /** - * 注册Websocket事件 + * 注册Websocket请求处理器 * - * @param eventName 事件名称 - * @param event 事件对象 + * @param requestName 请求名称 + * @param handler 请求处理器 */ - private void registerEvent(String eventName, EventRunner event) { - eventList.put(eventName, event); + private void registerRequestHandler(String requestName, RequestHandler handler) { + requestHandlers.put(requestName, handler); } /** - * 统一事件注册 + * 统一请求处理器注册 */ - private void totalRegEvent() { - registerEvent("sendConfig", new SendConfig()); - registerEvent("shaked", new Shaked()); - registerEvent("chat", new Chat()); - registerEvent("add", new AddAllowList()); - registerEvent("delete", new DelAllowList()); - registerEvent("cmd", new RunCommand()); - registerEvent("queryList", new QueryAllowList()); - registerEvent("queryOnline", new QueryOnline()); - registerEvent("shutdown", new ShutDown()); - registerEvent("run", new CustomRun()); - registerEvent("runAdmin", new CustomRunAdmin()); - registerEvent("heart", new Heart()); - bindRequestObj = new bindRequest(); - registerEvent("bindRequest", bindRequestObj); + private void registerRequestHandlers() { + registerRequestHandler("sendConfig", new SendConfig()); + registerRequestHandler("shaked", new Shaked()); + registerRequestHandler("chat", new Chat()); + registerRequestHandler("add", new EditAllowList(true)); + registerRequestHandler("delete", new EditAllowList(false)); + registerRequestHandler("cmd", new RunCommand()); + registerRequestHandler("queryList", new QueryAllowList()); + registerRequestHandler("queryOnline", new QueryOnline()); + registerRequestHandler("shutdown", new ShutDown()); + registerRequestHandler("run", new CustomRun(false)); + registerRequestHandler("runAdmin", new CustomRun(true)); + registerRequestHandler("heart", new Heart()); + bindRequest = new BindRequest(); + registerRequestHandler("bindRequest", bindRequest); } public void onWsMsg(JSONObject data) { @@ -118,27 +117,27 @@ public void onWsMsg(JSONObject data) { JSONObject body = data.getJSONObject("body"); String type = header.getString("type"); - String packId = header.getString("id"); + String id = header.getString("id"); - EventRunner event = eventList.get(type); - if (event != null) { - event.EventCall(packId, body); + RequestHandler handler = requestHandlers.get(type); + if (handler != null) { + handler.handle(id, body); } else { - log.error("在处理消息是遇到错误: 未知的消息类型{}", type); - log.error("此错误具有不可容错性!请检查插件是否为最新!"); - log.info("正在断开连接..."); + pluginLogger.error("在处理消息是遇到错误: 未知的消息类型{}", type); + pluginLogger.error("此错误具有不可容错性!请检查插件是否为最新!"); + pluginLogger.info("正在断开连接..."); clientManager.shutdownClient(); } } - public void runCommand(String command, String packId) { - CommandSender orginalSender = Server.getInstance(); - CommandResult result = Registries.COMMANDS.execute(orginalSender, command); - String resultTextBuilder = "暂不支持返回值."; + public void runCommand(String command, String requestId) { + var sender = new HuHoBotCommandSender(); + var result = Registries.COMMANDS.execute(sender, command); + var message = sender.getOutputs().toString(); if (result.isSuccess()) { - clientManager.getClient().respone("已执行,命令回调如下:\n" + resultTextBuilder, "success", packId); + clientManager.getClient().response("已执行,命令回调如下:\n" + message, "success", requestId); } else { - clientManager.getClient().respone("已执行,命令回调如下:\n" + resultTextBuilder, "error", packId); + clientManager.getClient().response("已执行,命令回调如下:\n" + message, "error", requestId); } } @@ -157,9 +156,7 @@ public boolean isBind() { */ public void sendBindMessage() { if (!isBind()) { - String serverId = config.getServerId(); - String message = "服务器尚未在机器人进行绑定,请在群内输入\"/绑定 " + serverId + "\""; - log.warn(message); + pluginLogger.warn("服务器尚未在机器人进行绑定,请在群内输入\"/绑定 " + config.getServerId() + "\""); } } @@ -187,5 +184,23 @@ public boolean disConnectServer() { return clientManager.shutdownClient(); } - + @EventHandler + private void onPlayerChat(PlayerChatEvent event) { + String message = event.getMessage(); + String playerName = event.getPlayer().getDisplayName(); + + HuHoBotConfig config = HuHoBot.getConfig(); + + String format = config.getChatConfig().getFromGame(); + String prefix = config.getChatConfig().getPostPrefix(); + boolean isPostChat = config.getChatConfig().isPostChat(); + String serverId = config.getServerId(); + if (message.startsWith(prefix) && isPostChat) { + JSONObject body = new JSONObject(); + body.put("serverId", serverId); + String formated = format.replace("{name}", playerName).replace("{msg}", message.substring(prefix.length())); + body.put("msg", formated); + HuHoBot.getClientManager().getClient().sendMessage("chat", body); + } + } } \ No newline at end of file diff --git a/src/main/java/cn/huohuas001/huHoBot/Settings/PluginConfig.java b/src/main/java/cn/huohuas001/huHoBot/HuHoBotConfig.java similarity index 68% rename from src/main/java/cn/huohuas001/huHoBot/Settings/PluginConfig.java rename to src/main/java/cn/huohuas001/huHoBot/HuHoBotConfig.java index 595171d..b5e3cc1 100644 --- a/src/main/java/cn/huohuas001/huHoBot/Settings/PluginConfig.java +++ b/src/main/java/cn/huohuas001/huHoBot/HuHoBotConfig.java @@ -1,11 +1,10 @@ -package cn.huohuas001.huHoBot.Settings; +package cn.huohuas001.huhobot; -import cn.huohuas001.huHoBot.Tools.PackId; +import cn.huohuas001.huhobot.utils.Utils; import eu.okaeri.configs.OkaeriConfig; import eu.okaeri.configs.annotation.Comment; import eu.okaeri.configs.annotation.CustomKey; -import eu.okaeri.configs.annotation.NameStrategy; -import eu.okaeri.configs.annotation.Names; +import eu.okaeri.configs.annotation.Exclude; import lombok.Getter; import lombok.Setter; @@ -15,9 +14,10 @@ import java.util.stream.Collectors; // 主配置类 -@Names(strategy = NameStrategy.IDENTITY) -public class PluginConfig extends OkaeriConfig { - private final transient int CurrentVersion = 2; +@SuppressWarnings("ALL") +public class HuHoBotConfig extends OkaeriConfig { + @Exclude + private static final int CURRENT_VERSION = 2; // region Getters & Setters // region 核心配置 @@ -47,50 +47,45 @@ public class PluginConfig extends OkaeriConfig { "post_chat: 是否转发聊天消息", "post_prefix: 消息转发前缀" }) - @CustomKey("chatConfig") - private final ChatConfig chatConfig = new ChatConfig(); + private ChatConfig chatConfig = new ChatConfig(); + // 弃用旧字段并标记为 transient 防止持久化 @Deprecated - @CustomKey("chatFormatGroup") private transient String chatFormatGroup; + // region 新的MOTD配置结构 + @Getter @Comment({ "MOTD服务器配置", "api: 状态查询API地址,使用{server_ip}和{server_port}作为占位符", "text: 显示文本格式,使用{online}作为在线人数占位符" }) - @CustomKey("motd") - private final MotdConfig motd = new MotdConfig(); + private MotdConfig motd = new MotdConfig(); // endregion + @Getter - @Comment({ - "服务器显示名称" - }) - @CustomKey("serverName") - private final String serverName = "AllayMC"; + @Comment("服务器显示名称") + private String serverName = "AllayMC"; + // region 自定义命令 @Getter @Comment("自定义命令列表") - @CustomKey("customCommand") - private final List customCommand = Arrays.asList( + private List customCommand = Arrays.asList( new CustomCommand("加白名", "whitelist add &1", 0), new CustomCommand("管理加白名", "whitelist add &1", 1) ); // endregion + // 在PluginConfig类顶部添加版本字段 @Comment("配置版本 (检测到版本小于1时会自动迁移旧配置)") @CustomKey("version") private int configVersion = 1; // endregion + // 废弃原有motdUrl字段 @Deprecated - @CustomKey("motdUrl") private transient String motdUrl; - public MotdConfig getMotd() { - return motd; - } - @Deprecated public String getMotdUrl() { return motd.getServerIp() + ":" + motd.getServerPort(); @@ -106,11 +101,11 @@ public Map getCustomCommandMap() { // 初始化方法示例 public void initializeDefaults() { if (this.serverId == null) { - this.serverId = PackId.getPackID(); + this.serverId = Utils.randomID(); } // 自动迁移逻辑(当版本号不存在时) - if (this.configVersion < CurrentVersion) { + if (this.configVersion < CURRENT_VERSION) { performConfigMigration(); } } @@ -140,11 +135,12 @@ private void performConfigMigration() { } // endregion - @Names(strategy = NameStrategy.IDENTITY) + @Getter public static class ChatConfig extends OkaeriConfig { + // Getters @Comment("游戏端消息格式") @CustomKey("from_game") - private final String fromGame = "<{name}> {msg}"; + private String fromGame = "<{name}> {msg}"; @Comment("群聊消息格式") @CustomKey("from_group") @@ -157,27 +153,11 @@ public static class ChatConfig extends OkaeriConfig { @Comment("消息转发前缀") @CustomKey("post_prefix") private String postPrefix = ""; - - // Getters - public String getFromGame() { - return fromGame; - } - - public String getFromGroup() { - return fromGroup; - } - - public boolean isPostChat() { - return postChat; - } - - public String getPostPrefix() { - return postPrefix; - } } - @Names(strategy = NameStrategy.IDENTITY) + @Getter public static class MotdConfig extends OkaeriConfig { + // Getters @Comment("服务器IP地址") @CustomKey("server_ip") private String serverIp = "play.easecation.net"; @@ -187,47 +167,23 @@ public static class MotdConfig extends OkaeriConfig { private int serverPort = 19132; @Comment("状态查询API地址") - private final String api = "https://motdbe.blackbe.work/status_img?host={server_ip}:{server_port}"; + private String api = "https://motdbe.blackbe.work/status_img?host={server_ip}:{server_port}"; @Comment("显示文本格式") - private final String text = "共{online}人在线"; + private String text = "共{online}人在线"; @Comment("是否输出在线列表") @CustomKey("output_online_list") - private final boolean outputOnlineList = true; + private boolean outputOnlineList = true; @Comment("是否发布状态图片") @CustomKey("post_img") - private final boolean postImg = true; - - // Getters - public String getServerIp() { - return serverIp; - } - - public int getServerPort() { - return serverPort; - } - - public String getApi() { - return api; - } - - public String getText() { - return text; - } - - public boolean isOutputOnlineList() { - return outputOnlineList; - } - - public boolean isPostImg() { - return postImg; - } + private boolean postImg = true; } - @Names(strategy = NameStrategy.IDENTITY) + @Getter public static class CustomCommand extends OkaeriConfig { + // Getters 必须存在 @Comment("触发指令 (支持中文)") private String key; @@ -246,18 +202,5 @@ public CustomCommand(String key, String command, int permission) { this.command = command; this.permission = permission; } - - // Getters 必须存在 - public String getKey() { - return key; - } - - public String getCommand() { - return command; - } - - public int getPermission() { - return permission; - } } } \ No newline at end of file diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/AddAllowList.java b/src/main/java/cn/huohuas001/huHoBot/NetEvent/AddAllowList.java deleted file mode 100644 index 9e00503..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/AddAllowList.java +++ /dev/null @@ -1,18 +0,0 @@ -package cn.huohuas001.huHoBot.NetEvent; - -import cn.huohuas001.huHoBot.Settings.PluginConfig; -import org.allaymc.api.server.Server; - -public class AddAllowList extends EventRunner { - @Override - public boolean run() { - String XboxId = body.getString("xboxid"); - if (Server.getInstance().getPlayerManager().addToWhitelist(XboxId)) { - PluginConfig config = this.getConfig(); - String name = config.getServerName(); - respone(name + "已接受添加名为" + XboxId + "的白名单请求", "success"); - } - - return true; - } -} diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/CustomRun.java b/src/main/java/cn/huohuas001/huHoBot/NetEvent/CustomRun.java deleted file mode 100644 index bf883fe..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/CustomRun.java +++ /dev/null @@ -1,44 +0,0 @@ -package cn.huohuas001.huHoBot.NetEvent; - - -import cn.huohuas001.huHoBot.Api.BotCustomCommand; -import cn.huohuas001.huHoBot.HuHoBot; -import cn.huohuas001.huHoBot.Settings.PluginConfig; - -import java.util.List; -import java.util.Map; - -public class CustomRun extends EventRunner { - private final HuHoBot plugin = HuHoBot.getPlugin(); - - @Override - public boolean run() { - String keyWord = body.getString("key"); - List param = body.getList("runParams", String.class); - - Map commandMap = getConfig().getCustomCommandMap(); - // 测试查找功能 - PluginConfig.CustomCommand result = commandMap.get(keyWord); - if (result == null) { - BotCustomCommand event = new BotCustomCommand(keyWord, body, packId, false); - event.call(); - - if (!event.isCancelled()) { - respone("无效的关键字", "error"); - } - return true; - } - - String command = result.getCommand(); - for (int i = 0; i < param.size(); i++) { - int replaceNum = i + 1; - command = command.replace("&" + replaceNum, param.get(i)); - } - if (result.getPermission() > 0) { - respone("权限不足,若您为管理员,请使用/管理员执行", "error"); - return false; - } - runCommand(command); - return true; - } -} diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/CustomRunAdmin.java b/src/main/java/cn/huohuas001/huHoBot/NetEvent/CustomRunAdmin.java deleted file mode 100644 index 2666bbe..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/CustomRunAdmin.java +++ /dev/null @@ -1,36 +0,0 @@ -package cn.huohuas001.huHoBot.NetEvent; - -import cn.huohuas001.huHoBot.Api.BotCustomCommand; -import cn.huohuas001.huHoBot.Settings.PluginConfig; - -import java.util.List; -import java.util.Map; - -public class CustomRunAdmin extends EventRunner { - @Override - public boolean run() { - String keyWord = body.getString("key"); - List param = body.getList("runParams", String.class); - - Map commandMap = getConfig().getCustomCommandMap(); - // 测试查找功能 - PluginConfig.CustomCommand result = commandMap.get(keyWord); - if (result == null) { - BotCustomCommand event = new BotCustomCommand(keyWord, body, packId, true); - - if (!event.isCancelled()) { - respone("无效的关键字", "error"); - } - return true; - } - - String command = result.getCommand(); - for (int i = 0; i < param.size(); i++) { - int replaceNum = i + 1; - command = command.replace("&" + replaceNum, param.get(i)); - } - - runCommand(command); - return false; - } -} diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/DelAllowList.java b/src/main/java/cn/huohuas001/huHoBot/NetEvent/DelAllowList.java deleted file mode 100644 index 43023dd..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/DelAllowList.java +++ /dev/null @@ -1,17 +0,0 @@ -package cn.huohuas001.huHoBot.NetEvent; - -import cn.huohuas001.huHoBot.Settings.PluginConfig; -import org.allaymc.api.server.Server; - -public class DelAllowList extends EventRunner { - @Override - public boolean run() { - String XboxId = body.getString("xboxid"); - if (Server.getInstance().getPlayerManager().removeFromWhitelist(XboxId)) { - PluginConfig config = this.getConfig(); - String name = config.getServerName(); - respone(name + "已接受删除名为" + XboxId + "的白名单请求", "success"); - } - return true; - } -} diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/EventRunner.java b/src/main/java/cn/huohuas001/huHoBot/NetEvent/EventRunner.java deleted file mode 100644 index 11b3771..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/EventRunner.java +++ /dev/null @@ -1,40 +0,0 @@ -package cn.huohuas001.huHoBot.NetEvent; - -import cn.huohuas001.huHoBot.HuHoBot; -import cn.huohuas001.huHoBot.Settings.PluginConfig; -import cn.huohuas001.huHoBot.WsClient; -import com.alibaba.fastjson2.JSONObject; - -public class EventRunner { - String packId; - JSONObject body; - - void respone(String msg, String type) { - WsClient client = HuHoBot.getClientManager().getClient(); - client.respone(msg, type, packId); - } - - void sendMessage(String type, JSONObject body) { - WsClient client = HuHoBot.getClientManager().getClient(); - client.sendMessage(type, body, packId); - } - - PluginConfig getConfig() { - return HuHoBot.getConfig(); - } - - void runCommand(String command) { - HuHoBot.getPlugin().runCommand(command, packId); - } - - public boolean EventCall(String packId, JSONObject body) { - this.packId = packId; - this.body = body; - return run(); - } - - boolean run() { - return true; - } - -} diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/Heart.java b/src/main/java/cn/huohuas001/huHoBot/NetEvent/Heart.java deleted file mode 100644 index 28352b6..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/Heart.java +++ /dev/null @@ -1,8 +0,0 @@ -package cn.huohuas001.huHoBot.NetEvent; - -public class Heart extends EventRunner { - @Override - public boolean run() { - return true; - } -} \ No newline at end of file diff --git a/src/main/java/cn/huohuas001/huHoBot/Tools/ConsoleSender.java b/src/main/java/cn/huohuas001/huHoBot/Tools/ConsoleSender.java deleted file mode 100644 index b1ab911..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/Tools/ConsoleSender.java +++ /dev/null @@ -1,51 +0,0 @@ -package cn.huohuas001.huHoBot.Tools; - -/* -import org.allaymc.api.command.CommandResult; -import org.allaymc.api.command.CommandSender; -import org.allaymc.api.entity.Entity; -import org.allaymc.api.entity.interfaces.EntityPlayer; -import org.allaymc.api.i18n.TrContainer; -import org.allaymc.api.math.location.Location3dc; -import org.allaymc.api.permission.tree.PermissionTree; -import org.allaymc.api.server.Server; -import org.allaymc.api.world.gamerule.GameRule; -import org.cloudburstmc.protocol.bedrock.data.command.CommandOriginData; - -public class ConsoleSender implements CommandSender { - - @Override - public String getCommandSenderName() { - return ""; - } - - @Override - public CommandOriginData getCommandOriginData() { - return null; - } - - @Override - public Location3dc getCmdExecuteLocation() { - return null; - } - - @Override - public void sendText(String s) { - - } - - @Override - public void sendTr(String s, boolean b, Object... objects) { - - } - - @Override - public void sendCommandOutputs(CommandSender commandSender, int i, TrContainer... trContainers) { - - } - - @Override - public PermissionTree getPermissionTree() { - return null; - } -}*/ diff --git a/src/main/java/cn/huohuas001/huHoBot/Tools/PackId.java b/src/main/java/cn/huohuas001/huHoBot/Tools/PackId.java deleted file mode 100644 index a9a5224..0000000 --- a/src/main/java/cn/huohuas001/huHoBot/Tools/PackId.java +++ /dev/null @@ -1,11 +0,0 @@ -package cn.huohuas001.huHoBot.Tools; - -import java.util.UUID; - - -public class PackId { - public static String getPackID() { - UUID guid = UUID.randomUUID(); - return guid.toString().replace("-", ""); - } -} diff --git a/src/main/java/cn/huohuas001/huHoBot/event/BotCustomCommandEvent.java b/src/main/java/cn/huohuas001/huHoBot/event/BotCustomCommandEvent.java new file mode 100644 index 0000000..af7261d --- /dev/null +++ b/src/main/java/cn/huohuas001/huHoBot/event/BotCustomCommandEvent.java @@ -0,0 +1,40 @@ +package cn.huohuas001.huhobot.event; + +import cn.huohuas001.huhobot.HuHoBot; +import cn.huohuas001.huhobot.websocket.WSClient; +import com.alibaba.fastjson2.JSONObject; +import lombok.AccessLevel; +import lombok.Getter; +import org.allaymc.api.eventbus.event.CancellableEvent; +import org.allaymc.api.eventbus.event.Event; + +import java.util.List; + +@Getter +public class BotCustomCommandEvent extends Event implements CancellableEvent { + + private final String command; + private final JSONObject data; + private final List param; + @Getter(AccessLevel.NONE) + private final String requestId; + private final boolean runByAdmin; + + public BotCustomCommandEvent(String command, JSONObject data, String requestId, boolean runByAdmin) { + this.command = command; + this.data = data; + this.param = data.getList("runParams", String.class); + this.requestId = requestId; + this.runByAdmin = runByAdmin; + } + + public void response(String msg, String type) { + WSClient client = HuHoBot.getClientManager().getClient(); + client.response(msg, type, requestId); + } + + public void response(JSONObject msg, String type) { + WSClient client = HuHoBot.getClientManager().getClient(); + client.response(msg.toJSONString(), type, requestId); + } +} diff --git a/src/main/java/cn/huohuas001/huHoBot/Tools/SetController.java b/src/main/java/cn/huohuas001/huHoBot/utils/CollectionUtils.java similarity index 53% rename from src/main/java/cn/huohuas001/huHoBot/Tools/SetController.java rename to src/main/java/cn/huohuas001/huHoBot/utils/CollectionUtils.java index 2870c9d..a4f65a7 100644 --- a/src/main/java/cn/huohuas001/huHoBot/Tools/SetController.java +++ b/src/main/java/cn/huohuas001/huHoBot/utils/CollectionUtils.java @@ -1,41 +1,38 @@ -package cn.huohuas001.huHoBot.Tools; - +package cn.huohuas001.huhobot.utils; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.stream.Collectors; -public class SetController { +public final class CollectionUtils { /** * 将一个Set集合转换为List,然后分割成多个子List。 * - * @param set 要分割的Set集合。 - * @param size 每个子List的最大容量。 - * @param Set集合中元素的类型。 + * @param set 要分割的Set集合。 + * @param size 每个子List的最大容量。 + * @param Set集合中元素的类型。 * @return 分割后的List列表。 */ - public static List> chunkSet(Set set, int size) { + public static List> chunkSet(Set set, int size) { // 将Set转换为List - List list = set.stream().collect(Collectors.toList()); + var list = new ArrayList<>(set); // 使用chunkList方法进行分片 return chunkList(list, size); } - private static List> chunkList(List list, int size) { - List> chunks = new ArrayList<>(); + private static List> chunkList(List list, int size) { + var chunks = new ArrayList>(); for (int i = 0; i < list.size(); i += size) { - List chunk = list.subList(i, Math.min(i + size, list.size())); + var chunk = list.subList(i, Math.min(i + size, list.size())); chunks.add(chunk); } return chunks; } - public static List searchInSet(Set set, String keyword) { return set.stream() .filter(s -> s.contains(keyword)) .collect(Collectors.toList()); } - } diff --git a/src/main/java/cn/huohuas001/huHoBot/utils/HuHoBotCommandSender.java b/src/main/java/cn/huohuas001/huHoBot/utils/HuHoBotCommandSender.java new file mode 100644 index 0000000..aa5449c --- /dev/null +++ b/src/main/java/cn/huohuas001/huHoBot/utils/HuHoBotCommandSender.java @@ -0,0 +1,53 @@ +package cn.huohuas001.huhobot.utils; + +import cn.huohuas001.huhobot.HuHoBot; +import lombok.Getter; +import org.allaymc.api.command.CommandSender; +import org.allaymc.api.math.location.Location3dc; +import org.allaymc.api.message.I18n; +import org.allaymc.api.message.LangCode; +import org.allaymc.api.message.TrContainer; +import org.allaymc.api.permission.PermissionGroup; +import org.allaymc.api.permission.PermissionGroups; +import org.allaymc.api.server.Server; + +public class HuHoBotCommandSender implements CommandSender { + + @Getter + public final StringBuilder outputs = new StringBuilder(); + + @Override + public String getCommandSenderName() { + return "HuHoBot"; + } + + @Override + public Location3dc getCommandExecuteLocation() { + return Server.getInstance().getWorldPool().getDefaultWorld().getSpawnPoint(); + } + + @Override + public void sendMessage(String message) { + for (var line : message.split("\n")) { + this.outputs.append(line).append("\n"); + HuHoBot.getInstance().getPluginLogger().info(line); + } + } + + @Override + public void sendTranslatable(String translatable, Object... args) { + sendMessage(I18n.get().tr(LangCode.zh_CN, translatable, args)); + } + + @Override + public void sendCommandOutputs(CommandSender sender, int status, TrContainer... outputs) { + for (var output : outputs) { + sendMessage(I18n.get().tr(LangCode.zh_CN, output.str(), output.args())); + } + } + + @Override + public PermissionGroup getPermissionGroup() { + return PermissionGroups.OPERATOR; + } +} \ No newline at end of file diff --git a/src/main/java/cn/huohuas001/huHoBot/utils/Utils.java b/src/main/java/cn/huohuas001/huHoBot/utils/Utils.java new file mode 100644 index 0000000..d819a9b --- /dev/null +++ b/src/main/java/cn/huohuas001/huHoBot/utils/Utils.java @@ -0,0 +1,9 @@ +package cn.huohuas001.huhobot.utils; + +import java.util.UUID; + +public final class Utils { + public static String randomID() { + return UUID.randomUUID().toString().replace("-", ""); + } +} diff --git a/src/main/java/cn/huohuas001/huHoBot/WsClient.java b/src/main/java/cn/huohuas001/huHoBot/websocket/WSClient.java similarity index 76% rename from src/main/java/cn/huohuas001/huHoBot/WsClient.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/WSClient.java index b21fa72..fd95f22 100644 --- a/src/main/java/cn/huohuas001/huHoBot/WsClient.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/WSClient.java @@ -1,8 +1,9 @@ -package cn.huohuas001.huHoBot; +package cn.huohuas001.huhobot.websocket; -import cn.huohuas001.huHoBot.Settings.PluginConfig; -import cn.huohuas001.huHoBot.Tools.PackId; +import cn.huohuas001.huhobot.HuHoBot; +import cn.huohuas001.huhobot.HuHoBotConfig; +import cn.huohuas001.huhobot.utils.Utils; import com.alibaba.fastjson2.JSON; import com.alibaba.fastjson2.JSONObject; import lombok.extern.slf4j.Slf4j; @@ -17,10 +18,10 @@ import java.util.concurrent.CompletableFuture; @Slf4j -public class WsClient extends WebSocketClient { +public class WSClient extends WebSocketClient { private final Map> responseFutureList = new HashMap<>(); private final HuHoBot plugin; - private final WebsocketClientManager clientManager; + private final WSClientManager clientManager; /*public WsClient(URI serverUri, WebsocketClientManager clientManager, @@ -55,9 +56,9 @@ public class WsClient extends WebSocketClient { }*/ - public WsClient(URI serverUri, WebsocketClientManager clientManager) { + public WSClient(URI serverUri, WSClientManager clientManager) { super(serverUri); - this.plugin = HuHoBot.getPlugin(); + this.plugin = HuHoBot.getInstance(); //this.logger = plugin.getLogger(); this.clientManager = clientManager; } @@ -73,17 +74,17 @@ public void onMessage(String message) { //logger.info("Received: " + message); JSONObject jsonData = JSON.parseObject(message); JSONObject header = jsonData.getJSONObject("header"); - String packId = header.getString("id"); + String requestId = header.getString("id"); - if (responseFutureList.containsKey(packId)) { - CompletableFuture responseFuture = responseFutureList.get(packId); + if (responseFutureList.containsKey(requestId)) { + CompletableFuture responseFuture = responseFutureList.get(requestId); if (responseFuture != null && !responseFuture.isDone()) { responseFuture.complete(jsonData); } - responseFutureList.remove(packId); + responseFutureList.remove(requestId); } else { Scheduler scheduler = Server.getInstance().getScheduler(); - scheduler.runLater(HuHoBot.getPlugin(), () -> { + scheduler.runLater(HuHoBot.getInstance(), () -> { plugin.onWsMsg(jsonData); }); } @@ -109,22 +110,21 @@ public void onError(Exception ex) { * @param body 消息数据 */ public void sendMessage(String type, JSONObject body) { - String newPackId = PackId.getPackID(); - sendMessage(type, body, newPackId); + sendMessage(type, body, Utils.randomID()); } /** * 向服务端发送一条消息 * - * @param type 消息类型 - * @param body 消息数据 - * @param packId 消息Id + * @param type 消息类型 + * @param body 消息数据 + * @param requestId 消息Id */ - public void sendMessage(String type, JSONObject body, String packId) { + public void sendMessage(String type, JSONObject body, String requestId) { JSONObject data = new JSONObject(); JSONObject header = new JSONObject(); header.put("type", type); - header.put("id", packId); + header.put("id", requestId); data.put("header", header); data.put("body", body); if (this.isOpen()) { @@ -140,32 +140,31 @@ public void sendMessage(String type, JSONObject body, String packId) { * @return 消息回报体 */ public CompletableFuture sendRequestAndAwaitResponse(String type, JSONObject body) { - String newPackId = PackId.getPackID(); - return sendRequestAndAwaitResponse(type, body, newPackId); + return sendRequestAndAwaitResponse(type, body, Utils.randomID()); } /** * 向服务端发送一条消息并获取返回值 * - * @param type 消息类型 - * @param body 消息数据 - * @param packId 消息Id + * @param type 消息类型 + * @param body 消息数据 + * @param requestId 消息Id * @return 消息回报体 */ - public CompletableFuture sendRequestAndAwaitResponse(String type, JSONObject body, String packId) { + public CompletableFuture sendRequestAndAwaitResponse(String type, JSONObject body, String requestId) { if (this.isOpen()) { //打包数据并发送 JSONObject data = new JSONObject(); JSONObject header = new JSONObject(); header.put("type", type); - header.put("id", packId); + header.put("id", requestId); data.put("header", header); data.put("body", body); this.send(data.toJSONString()); //存储回报 CompletableFuture responseFuture = new CompletableFuture<>(); - responseFutureList.put(packId, responseFuture); + responseFutureList.put(requestId, responseFuture); return responseFuture; } else { @@ -179,29 +178,28 @@ public CompletableFuture sendRequestAndAwaitResponse(String type, JS * @param msg 回报消息 * @param type 回报类型:success|error */ - public void respone(String msg, String type) { - String newPackId = PackId.getPackID(); - this.respone(msg, type, newPackId); + public void response(String msg, String type) { + this.response(msg, type, Utils.randomID()); } /** * 向服务端发送一条回报 * - * @param msg 回报消息 - * @param type 回报类型:success|error - * @param packId 回报Id + * @param msg 回报消息 + * @param type 回报类型:success|error + * @param requestId 回报Id */ - public void respone(String msg, String type, String packId) { + public void response(String msg, String type, String requestId) { JSONObject body = new JSONObject(); body.put("msg", msg); - sendMessage(type, body, packId); + sendMessage(type, body, requestId); } /** * 向服务端握手 */ private void shakeHand() { - PluginConfig config = HuHoBot.getConfig(); + HuHoBotConfig config = HuHoBot.getConfig(); JSONObject body = new JSONObject(); body.put("serverId", config.getServerId()); if (config.get("hashKey") == null) { @@ -210,7 +208,7 @@ private void shakeHand() { body.put("hashKey", config.getHashKey()); } body.put("name", config.getServerName()); - body.put("version", HuHoBot.getPlugin().getPluginContainer().descriptor().getVersion()); + body.put("version", HuHoBot.getInstance().getPluginContainer().descriptor().getVersion()); body.put("platform", "allay"); sendMessage("shakeHand", body); } diff --git a/src/main/java/cn/huohuas001/huHoBot/WebsocketClientManager.java b/src/main/java/cn/huohuas001/huHoBot/websocket/WSClientManager.java similarity index 63% rename from src/main/java/cn/huohuas001/huHoBot/WebsocketClientManager.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/WSClientManager.java index 84d5928..f329d76 100644 --- a/src/main/java/cn/huohuas001/huHoBot/WebsocketClientManager.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/WSClientManager.java @@ -1,7 +1,8 @@ -package cn.huohuas001.huHoBot; +package cn.huohuas001.huhobot.websocket; -import cn.huohuas001.config.ServerConfig; +import cn.huohuas001.huhobot.HuHoBot; import com.alibaba.fastjson2.JSONObject; +import lombok.Setter; import lombok.extern.slf4j.Slf4j; import org.allaymc.api.scheduler.Scheduler; import org.allaymc.api.server.Server; @@ -11,33 +12,29 @@ import javax.net.ssl.X509TrustManager; import java.net.URI; import java.net.URISyntaxException; +import java.security.SecureRandom; import java.security.cert.X509Certificate; @Slf4j -public class WebsocketClientManager { - private static final String websocketUrl = ServerConfig.WS_SERVER_URL; //Websocket地址 - private static WsClient client; //Websocket客户端 - private final int RECONNECT_DELAY = 5; // 重连延迟时间,单位为秒 - private final int MAX_RECONNECT_ATTEMPTS = 5; // 最大重连尝试次数 - private final HuHoBot plugin; - private final Scheduler scheduler = Server.getInstance().getScheduler(); - private int ReconnectAttempts = 0; - private boolean shouldReconnect = true; // 控制是否重连的变量 - private int currentTask = 0; - private int autoDisConnectTask = 0; - - - public WebsocketClientManager() { - plugin = HuHoBot.getPlugin(); - } +public class WSClientManager { - /** - * 设置是否应该重连 - * - * @param shouldReconnect 是否应该重连 - */ - public void setShouldReconnect(boolean shouldReconnect) { - this.shouldReconnect = shouldReconnect; + private static final int RECONNECT_DELAY = 5; // 重连延迟时间,单位为秒 + private static final int MAX_RECONNECT_ATTEMPTS = 5; // 最大重连尝试次数 + + private static WSClient client; //Websocket客户端 + + private final Scheduler scheduler; + + private int reconnectAttempts; + @Setter + private boolean shouldReconnect; // 控制是否重连的变量 + + private int currentTask, autoDisConnectTask; + + + public WSClientManager() { + this.scheduler = Server.getInstance().getScheduler(); + this.shouldReconnect = true; } /** @@ -48,8 +45,8 @@ private boolean autoReconnect() { if (currentTask == 0) { return false; } - ReconnectAttempts++; - if (ReconnectAttempts >= MAX_RECONNECT_ATTEMPTS) { + reconnectAttempts++; + if (reconnectAttempts >= MAX_RECONNECT_ATTEMPTS) { log.warn(" 重连尝试已达到最大次数,将不再尝试重新连接。"); cancelCurrentTask(); return false; @@ -58,7 +55,7 @@ private boolean autoReconnect() { cancelCurrentTask(); return false; } - log.info(" 正在尝试重新连接,这是第({}/" + MAX_RECONNECT_ATTEMPTS + ")次连接", ReconnectAttempts); + log.info(" 正在尝试重新连接,这是第({}/" + MAX_RECONNECT_ATTEMPTS + ")次连接", reconnectAttempts); this.connectServer(); return true; } @@ -67,11 +64,11 @@ private boolean autoReconnect() { public void cancelCurrentTask() { if (currentTask != 0) { currentTask = 0; - ReconnectAttempts = 0; + reconnectAttempts = 0; } } - public WsClient getClient() { + public WSClient getClient() { return client; } @@ -90,7 +87,7 @@ public void autoDisConnectClient() { public void setAutoDisConnectTask() { if (autoDisConnectTask == 0) { - scheduler.scheduleDelayed(plugin, () -> { + scheduler.scheduleDelayed(HuHoBot.getInstance(), () -> { autoDisConnectClient(); return true; }, 6 * 60 * 60 * 20); @@ -104,18 +101,17 @@ public void setAutoDisConnectTask() { public boolean connectServer() { log.info(" 正在连接服务端..."); try { - URI uri = new URI(websocketUrl); + URI uri = new URI(ServerConfig.WS_SERVER_URL); if (client == null || !client.isOpen()) { - client = new WsClient(uri, this); + client = new WSClient(uri, this); setShouldReconnect(true); // 设置是否重连 client.connect(); } return true; } catch (URISyntaxException e) { - log.error(e.getStackTrace().toString()); + log.error("连接URL格式错误", e); } catch (Exception e) { - log.error("连接HuHoBot失败: " + e.getMessage()); - e.printStackTrace(); + log.error("连接HuHoBot失败", e); } return false; } @@ -128,16 +124,14 @@ public void checkClientTrusted(X509Certificate[] chain, String authType) { } public void checkServerTrusted(X509Certificate[] chain, String authType) { - // 添加调试信息 - /*logger.info("接受服务器证书: " + - (chain != null && chain.length > 0 ? chain[0].getSubjectDN() : "无证书"));*/ + log.debug("接受服务器证书: {}", chain != null && chain.length > 0 ? chain[0].getSubjectX500Principal() : "无证书"); } public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } - }, new java.security.SecureRandom()); + }, new SecureRandom()); // 设置协议版本 context.getDefaultSSLParameters().setProtocols(new String[]{"TLSv1.2", "TLSv1.3"}); @@ -154,7 +148,7 @@ public void sendHeart() { public void clientReconnect() { if (shouldReconnect && currentTask == 0) { - scheduler.scheduleRepeating(plugin, this::autoReconnect, this.RECONNECT_DELAY * 20); + scheduler.scheduleRepeating(HuHoBot.getInstance(), this::autoReconnect, RECONNECT_DELAY * 20); currentTask = 1; } } diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/bindRequest.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/BindRequest.java similarity index 58% rename from src/main/java/cn/huohuas001/huHoBot/NetEvent/bindRequest.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/handler/BindRequest.java index d9f0c1a..5c0e400 100644 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/bindRequest.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/BindRequest.java @@ -1,22 +1,19 @@ -package cn.huohuas001.huHoBot.NetEvent; +package cn.huohuas001.huhobot.websocket.handler; -import cn.huohuas001.huHoBot.HuHoBot; +import cn.huohuas001.huhobot.HuHoBot; import com.alibaba.fastjson2.JSONObject; -import lombok.extern.slf4j.Slf4j; import java.util.HashMap; import java.util.Map; -@Slf4j -public class bindRequest extends EventRunner { - private final HuHoBot plugin = HuHoBot.getPlugin(); +public class BindRequest extends RequestHandler { private final Map bindMap = new HashMap<>(); @Override public boolean run() { String bindCode = body.getString("bindCode"); - log.info("收到一个新的绑定请求,如确认绑定,请输入\"/huhobot bind {}\"来进行确认", bindCode); - bindMap.put(bindCode, packId); + HuHoBot.getInstance().getPluginLogger().info("收到一个新的绑定请求,如确认绑定,请输入\"/huhobot bind {}\"来进行确认", bindCode); + bindMap.put(bindCode, id); return true; } diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/Chat.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/Chat.java similarity index 66% rename from src/main/java/cn/huohuas001/huHoBot/NetEvent/Chat.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/handler/Chat.java index 26149b5..c0f7a3b 100644 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/Chat.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/Chat.java @@ -1,14 +1,15 @@ -package cn.huohuas001.huHoBot.NetEvent; +package cn.huohuas001.huhobot.websocket.handler; -import cn.huohuas001.huHoBot.Settings.PluginConfig; +import cn.huohuas001.huhobot.HuHoBot; +import cn.huohuas001.huhobot.HuHoBotConfig; import org.allaymc.api.server.Server; -public class Chat extends EventRunner { +public class Chat extends RequestHandler { @Override public boolean run() { String nick = body.getString("nick"); String msg = body.getString("msg"); - PluginConfig config = this.getConfig(); + HuHoBotConfig config = HuHoBot.getConfig(); String message = config.getChatConfig().getFromGroup().replace("{nick}", nick).replace("{msg}", msg); if (config.getChatConfig().isPostChat()) { Server.getInstance().getMessageChannel().broadcastMessage(message); diff --git a/src/main/java/cn/huohuas001/huHoBot/websocket/handler/CustomRun.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/CustomRun.java new file mode 100644 index 0000000..122981e --- /dev/null +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/CustomRun.java @@ -0,0 +1,46 @@ +package cn.huohuas001.huhobot.websocket.handler; + + +import cn.huohuas001.huhobot.HuHoBot; +import cn.huohuas001.huhobot.event.BotCustomCommandEvent; +import lombok.AllArgsConstructor; + +import java.util.List; + +@AllArgsConstructor +public class CustomRun extends RequestHandler { + + private final boolean runByAdmin; + + @Override + public boolean run() { + String keyWord = body.getString("key"); + List param = body.getList("runParams", String.class); + + var commandMap = HuHoBot.getConfig().getCustomCommandMap(); + // 测试查找功能 + var result = commandMap.get(keyWord); + if (result == null) { + var event = new BotCustomCommandEvent(keyWord, body, id, false); + event.call(); + if (!event.isCancelled()) { + response("无效的关键字", "error"); + } + + return true; + } + + String command = result.getCommand(); + for (int i = 0; i < param.size(); i++) { + int replaceNum = i + 1; + command = command.replace("&" + replaceNum, param.get(i)); + } + if (!runByAdmin && result.getPermission() > 0) { + response("权限不足,若您为管理员,请使用/管理员执行", "error"); + return false; + } + + runCommand(command); + return true; + } +} diff --git a/src/main/java/cn/huohuas001/huHoBot/websocket/handler/EditAllowList.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/EditAllowList.java new file mode 100644 index 0000000..ba33df8 --- /dev/null +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/EditAllowList.java @@ -0,0 +1,28 @@ +package cn.huohuas001.huhobot.websocket.handler; + +import cn.huohuas001.huhobot.HuHoBot; +import lombok.AllArgsConstructor; +import org.allaymc.api.server.Server; + +@AllArgsConstructor +public class EditAllowList extends RequestHandler { + + private final boolean add; + + @Override + public boolean run() { + String xboxId = body.getString("xboxid"); + if (add) { + if (Server.getInstance().getPlayerManager().addToWhitelist(xboxId)) { + String name = HuHoBot.getConfig().getServerName(); + response(name + "已接受添加名为" + xboxId + "的白名单请求", "success"); + } + } else { + if (Server.getInstance().getPlayerManager().removeFromWhitelist(xboxId)) { + String name = HuHoBot.getConfig().getServerName(); + response(name + "已接受删除名为" + xboxId + "的白名单请求", "success"); + } + } + return true; + } +} diff --git a/src/main/java/cn/huohuas001/huHoBot/websocket/handler/Heart.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/Heart.java new file mode 100644 index 0000000..599b40b --- /dev/null +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/Heart.java @@ -0,0 +1,8 @@ +package cn.huohuas001.huhobot.websocket.handler; + +public class Heart extends RequestHandler { + @Override + public boolean run() { + return true; + } +} \ No newline at end of file diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/QueryAllowList.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/QueryAllowList.java similarity index 88% rename from src/main/java/cn/huohuas001/huHoBot/NetEvent/QueryAllowList.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/handler/QueryAllowList.java index 0241fdb..ee276de 100644 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/QueryAllowList.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/QueryAllowList.java @@ -1,13 +1,13 @@ -package cn.huohuas001.huHoBot.NetEvent; +package cn.huohuas001.huhobot.websocket.handler; -import cn.huohuas001.huHoBot.Tools.SetController; +import cn.huohuas001.huhobot.utils.CollectionUtils; import com.alibaba.fastjson2.JSONObject; import org.allaymc.api.server.Server; import java.util.List; import java.util.Set; -public class QueryAllowList extends EventRunner { +public class QueryAllowList extends RequestHandler { @Override public boolean run() { Set whiteList = Server.getInstance().getPlayerManager().getWhitelistedPlayers(); @@ -23,7 +23,7 @@ public boolean run() { return true; } whitelistNameString.append("查询白名单关键词:").append(key).append("结果如下:\n"); - List filterList = SetController.searchInSet(whiteList, key); + List filterList = CollectionUtils.searchInSet(whiteList, key); if (filterList.isEmpty()) { whitelistNameString.append("无结果\n"); } else { @@ -37,7 +37,7 @@ public boolean run() { } else if (body.containsKey("page")) { int page = body.getInteger("page"); whitelistNameString.append("服内白名单如下:\n"); - List> splitedNameList = SetController.chunkSet(whiteList, 10); + List> splitedNameList = CollectionUtils.chunkSet(whiteList, 10); List currentNameList = splitedNameList.get(page - 1); if (page - 1 > splitedNameList.size()) { whitelistNameString.append("没有该页码\n"); @@ -52,7 +52,7 @@ public boolean run() { sendMessage("queryWl", rBody); } else { whitelistNameString.append("服内白名单如下:\n"); - List> splitedNameList = SetController.chunkSet(whiteList, 10); + List> splitedNameList = CollectionUtils.chunkSet(whiteList, 10); if (splitedNameList.isEmpty()) { whitelistNameString.append("无结果\n"); } else { diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/QueryOnline.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/QueryOnline.java similarity index 71% rename from src/main/java/cn/huohuas001/huHoBot/NetEvent/QueryOnline.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/handler/QueryOnline.java index 571cb36..6d6926a 100644 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/QueryOnline.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/QueryOnline.java @@ -1,26 +1,26 @@ -package cn.huohuas001.huHoBot.NetEvent; +package cn.huohuas001.huhobot.websocket.handler; +import cn.huohuas001.huhobot.HuHoBot; import com.alibaba.fastjson2.JSONObject; -import lombok.extern.slf4j.Slf4j; import org.allaymc.api.entity.interfaces.EntityPlayer; import org.allaymc.api.server.Server; import java.util.Map; import java.util.UUID; -@Slf4j -public class QueryOnline extends EventRunner { +public class QueryOnline extends RequestHandler { @Override public boolean run() { Map onlinePlayers = Server.getInstance().getPlayerManager().getPlayers(); - //获取motd Config - String server_ip = getConfig().getMotd().getServerIp(); - int server_port = getConfig().getMotd().getServerPort(); - String api = getConfig().getMotd().getApi(); - String text = getConfig().getMotd().getText(); - boolean output_online_list = getConfig().getMotd().isOutputOnlineList(); - boolean post_img = getConfig().getMotd().isPostImg(); + //获取motd + var config = HuHoBot.getConfig(); + String server_ip = config.getMotd().getServerIp(); + int server_port = config.getMotd().getServerPort(); + String api = config.getMotd().getApi(); + String text = config.getMotd().getText(); + boolean output_online_list = config.getMotd().isOutputOnlineList(); + boolean post_img = config.getMotd().isPostImg(); StringBuilder onlineNameString = new StringBuilder(); diff --git a/src/main/java/cn/huohuas001/huHoBot/websocket/handler/RequestHandler.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/RequestHandler.java new file mode 100644 index 0000000..587a526 --- /dev/null +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/RequestHandler.java @@ -0,0 +1,35 @@ +package cn.huohuas001.huhobot.websocket.handler; + +import cn.huohuas001.huhobot.HuHoBot; +import cn.huohuas001.huhobot.websocket.WSClient; +import com.alibaba.fastjson2.JSONObject; + +public class RequestHandler { + + protected String id; + protected JSONObject body; + + public boolean handle(String id, JSONObject body) { + this.id = id; + this.body = body; + return run(); + } + + protected boolean run() { + return true; + } + + protected void response(String msg, String type) { + WSClient client = HuHoBot.getClientManager().getClient(); + client.response(msg, type, id); + } + + protected void sendMessage(String type, JSONObject body) { + WSClient client = HuHoBot.getClientManager().getClient(); + client.sendMessage(type, body, id); + } + + protected void runCommand(String command) { + HuHoBot.getInstance().runCommand(command, id); + } +} diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/RunCommand.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/RunCommand.java similarity index 60% rename from src/main/java/cn/huohuas001/huHoBot/NetEvent/RunCommand.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/handler/RunCommand.java index cf3c09b..2077d62 100644 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/RunCommand.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/RunCommand.java @@ -1,7 +1,7 @@ -package cn.huohuas001.huHoBot.NetEvent; +package cn.huohuas001.huhobot.websocket.handler; -public class RunCommand extends EventRunner { +public class RunCommand extends RequestHandler { @Override public boolean run() { String command = body.getString("cmd"); diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/SendConfig.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/SendConfig.java similarity index 52% rename from src/main/java/cn/huohuas001/huHoBot/NetEvent/SendConfig.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/handler/SendConfig.java index 5ac0301..4dc24d3 100644 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/SendConfig.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/SendConfig.java @@ -1,16 +1,16 @@ -package cn.huohuas001.huHoBot.NetEvent; +package cn.huohuas001.huhobot.websocket.handler; -import cn.huohuas001.huHoBot.HuHoBot; -import cn.huohuas001.huHoBot.Settings.PluginConfig; -import lombok.extern.slf4j.Slf4j; +import cn.huohuas001.huhobot.HuHoBot; +import cn.huohuas001.huhobot.HuHoBotConfig; +import org.slf4j.Logger; -@Slf4j -public class SendConfig extends EventRunner { - private final HuHoBot plugin = HuHoBot.getPlugin(); +public class SendConfig extends RequestHandler { + + private static final Logger log = HuHoBot.getInstance().getPluginLogger(); @Override public boolean run() { - PluginConfig config = this.getConfig(); + HuHoBotConfig config = HuHoBot.getConfig(); config.setServerId(body.getString("serverId")); config.setHashKey(body.getString("hashKey")); config.save(); diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/Shaked.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/Shaked.java similarity index 65% rename from src/main/java/cn/huohuas001/huHoBot/NetEvent/Shaked.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/handler/Shaked.java index 711cccb..12c6bc3 100644 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/Shaked.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/Shaked.java @@ -1,18 +1,19 @@ -package cn.huohuas001.huHoBot.NetEvent; +package cn.huohuas001.huhobot.websocket.handler; -import cn.huohuas001.huHoBot.HuHoBot; -import lombok.extern.slf4j.Slf4j; +import cn.huohuas001.huhobot.HuHoBot; import org.allaymc.api.server.Server; +import org.allaymc.api.utils.TextFormat; +import org.slf4j.Logger; -@Slf4j -public class Shaked extends EventRunner { - private final HuHoBot plugin = HuHoBot.getPlugin(); +public class Shaked extends RequestHandler { + + private static final Logger log = HuHoBot.getInstance().getPluginLogger(); private void shakedProcess() { HuHoBot.getClientManager().setShouldReconnect(true); HuHoBot.getClientManager().cancelCurrentTask(); HuHoBot.getClientManager().setAutoDisConnectTask(); - Server.getInstance().getScheduler().scheduleRepeating(plugin, () -> { + Server.getInstance().getScheduler().scheduleRepeating(HuHoBot.getInstance(), () -> { HuHoBot.getClientManager().sendHeart(); return true; }, 5 * 20); @@ -32,15 +33,16 @@ public boolean run() { shakedProcess(); break; case 3: - log.error("握手失败,客户端密钥错误."); + log.error("{}握手失败,客户端密钥错误.", TextFormat.RED); HuHoBot.getClientManager().setShouldReconnect(false); break; case 6: log.info("与服务端握手成功,服务端等待绑定..."); shakedProcess(); + HuHoBot.getInstance().sendBindMessage(); break; default: - log.error("握手失败,原因{}", msg); + log.error("{}握手失败,原因{}", TextFormat.RED, msg); } return true; } diff --git a/src/main/java/cn/huohuas001/huHoBot/NetEvent/ShutDown.java b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/ShutDown.java similarity index 62% rename from src/main/java/cn/huohuas001/huHoBot/NetEvent/ShutDown.java rename to src/main/java/cn/huohuas001/huHoBot/websocket/handler/ShutDown.java index 5b39e8f..781ff1f 100644 --- a/src/main/java/cn/huohuas001/huHoBot/NetEvent/ShutDown.java +++ b/src/main/java/cn/huohuas001/huHoBot/websocket/handler/ShutDown.java @@ -1,11 +1,11 @@ -package cn.huohuas001.huHoBot.NetEvent; +package cn.huohuas001.huhobot.websocket.handler; -import cn.huohuas001.huHoBot.HuHoBot; -import lombok.extern.slf4j.Slf4j; +import cn.huohuas001.huhobot.HuHoBot; +import org.slf4j.Logger; -@Slf4j -public class ShutDown extends EventRunner { - private final HuHoBot plugin = HuHoBot.getPlugin(); +public class ShutDown extends RequestHandler { + + private static final Logger log = HuHoBot.getInstance().getPluginLogger(); @Override public boolean run() { diff --git a/src/main/resources/plugin.json b/src/main/resources/plugin.json index e36ddbd..e9cd459 100644 --- a/src/main/resources/plugin.json +++ b/src/main/resources/plugin.json @@ -1,7 +1,7 @@ { - "entrance": "cn.huohuas001.huHoBot.HuHoBot", + "entrance": "cn.huohuas001.huhobot.HuHoBot", "name": "HuHoBot", "authors": ["HuoHuas001"], - "version": "0.0.10", - "api_version": ">=0.13.0" + "version": "0.1.0", + "api_version": ">=0.14.0" } \ No newline at end of file diff --git a/src/main/templates/java/cn/huohuas001/config/ServerConfig.java.template b/src/main/templates/java/cn/huohuas001/huhobot/websocket/ServerConfig.java.template similarity index 70% rename from src/main/templates/java/cn/huohuas001/config/ServerConfig.java.template rename to src/main/templates/java/cn/huohuas001/huhobot/websocket/ServerConfig.java.template index ab55e2e..fd8a1eb 100644 --- a/src/main/templates/java/cn/huohuas001/config/ServerConfig.java.template +++ b/src/main/templates/java/cn/huohuas001/huhobot/websocket/ServerConfig.java.template @@ -1,4 +1,4 @@ -package cn.huohuas001.config; +package cn.huohuas001.huhobot.websocket; public class ServerConfig { public static final String WS_SERVER_URL = "${WS_SERVER_URL}";