Skip to content

Commit

Permalink
refactor(forge): 同步fabric变动2
Browse files Browse the repository at this point in the history
  • Loading branch information
cnlimiter committed Mar 20, 2024
1 parent 016452c commit e2cd1bb
Show file tree
Hide file tree
Showing 14 changed files with 400 additions and 130 deletions.
8 changes: 4 additions & 4 deletions forge/common.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ dependencies {
forge "net.minecraftforge:forge:${project.minecraft_version}-${project.forge_version}"


implementation forgeRuntimeLibrary (include("dev.vankka:dependencydownload-runtime:1.3.1")) {exclude module: 'jar-relocator'}
implementation forgeRuntimeLibrary (include("dev.vankka:dependencydownload-common:1.3.1"))
implementation ("cn.evole.onebot:OneBot-Client:${onebot_client_version}"){transitive = false}
implementation ("cn.evole.config:AtomConfig-Toml:${toml_version}"){transitive = false}
implementation forgeRuntimeLibrary ("dev.vankka:dependencydownload-runtime:1.3.1") {exclude module: 'jar-relocator'}
implementation forgeRuntimeLibrary ("dev.vankka:dependencydownload-common:1.3.1")
implementation forgeRuntimeLibrary (include("cn.evole.onebot:OneBot-Client:${onebot_client_version}")){transitive = false}
implementation forgeRuntimeLibrary (include("cn.evole.config:AtomConfig-Toml:${toml_version}")){transitive = false}

if (mcVersion == 11605) include ("org.slf4j:slf4j-api:2.0.7")
compileOnly ("org.projectlombok:lombok:1.18.24")
Expand Down
63 changes: 62 additions & 1 deletion forge/src/main/java/cn/evole/mods/mcbot/Const.java
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
package cn.evole.mods.mcbot;

import cn.evole.mods.mcbot.config.ModConfig;
import cn.evole.mods.mcbot.core.event.ITickEvent;
import cn.evole.mods.mcbot.util.onebot.MessageThread;
import cn.evole.onebot.sdk.action.ActionPath;
import com.google.gson.JsonObject;
import lombok.val;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.fml.ModList;
import net.minecraftforge.fml.loading.FMLPaths;
import java.nio.file.Path;
import java.util.concurrent.Callable;
//#if MC >= 11700
//$$ import org.slf4j.Logger;
//$$ import org.slf4j.LoggerFactory;
Expand All @@ -12,6 +19,12 @@
import org.apache.logging.log4j.LogManager;
//#endif

//#if MC < 11900
import net.minecraft.network.chat.TextComponent;
//#else
//$$ import net.minecraft.network.chat.Component;
//#endif

/**
* Description:
* Author: cnlimiter
Expand All @@ -28,6 +41,7 @@ public class Const {
public static boolean isShutdown = false;
public static Path configDir = FMLPaths.CONFIGDIR.get();
public static Path gameDir = FMLPaths.GAMEDIR.get();
public static final MessageThread messageThread = new MessageThread();

public static boolean isLoad(String modId){
return ModList.get().isLoaded(modId);
Expand All @@ -39,8 +53,55 @@ public static void sendAllGroupMsg(String message){
}
}

public static void sendAllGroupMsg(Callable<String> message){
for (long id : ModConfig.INSTANCE.getCommon().getGroupIdList()){
sendGroupMsg(id, message);
}
}

/**
* 玩家在游戏里发送消息
* @param message 消息
* @param player 玩家
*/
public static void sendAllGroupMsg(Callable<String> message, ServerPlayer player){
for (long id : ModConfig.INSTANCE.getCommon().getGroupIdList()){
messageThread.submit(id, message, false, player);
}
}

public static void sendGroupMsg(long id, String message){
IMcBot.onebot.getBot().sendGroupMsg(id, message, false);
messageThread.submit(id, message, false);
}

public static void sendGroupMsg(long id, Callable<String> message){
messageThread.submit(id, message, false);
}

/**
* 自定义请求 (不应清理)
* @param action 请求类型
* @param params 参数
*/
public static void customRequest(ActionPath action, JsonObject params){
messageThread.submit(action, params);
}

/**
* 向游戏中的所有人发送消息
*/
public static void sendAllPlayerMsg(String message){
//#if MC >= 11900
//$$ val toSend = Component.literal(message);
//#else
val toSend = new TextComponent(message);
//#endif

ITickEvent.getSendQueue().add(toSend);
}

public static void shutdown() {
messageThread.stop();
}


Expand Down
17 changes: 10 additions & 7 deletions forge/src/main/java/cn/evole/mods/mcbot/IMcBot.java
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@
import cn.evole.mods.mcbot.core.event.*;
import cn.evole.mods.mcbot.init.handler.CustomCmdHandler;
import cn.evole.mods.mcbot.util.FileUtil;
import cn.evole.mods.mcbot.util.lib.LibUtils;
import cn.evole.mods.mcbot.util.locale.I18n;
import cn.evole.mods.mcbot.util.onebot.CQUtils;
import cn.evole.mods.mcbot.util.onebot.KeepAlive;
import cn.evole.onebot.client.OneBotClient;
import net.minecraft.advancements.Advancement;
import net.minecraft.server.MinecraftServer;
Expand All @@ -17,8 +18,6 @@
import net.minecraft.world.level.Level;

import java.nio.file.Path;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class IMcBot {
public static MinecraftServer SERVER = null;
Expand All @@ -29,7 +28,9 @@ public class IMcBot {
public static McBot INSTANCE = new McBot();

public static OneBotClient onebot;
public static ExecutorService CQUtilsExecutor;

public static boolean connected = false;
public static KeepAlive keepAlive;

public MinecraftServer getServer() {
return SERVER;
Expand All @@ -44,7 +45,7 @@ public void init() {
FileUtil.checkFolder(CONFIG_FOLDER);
LIB_FOLDER = CONFIG_FOLDER.resolve("libs");
FileUtil.checkFolder(LIB_FOLDER);
LibUtils.create(LIB_FOLDER, "libs.txt").download();
//LibUtils.create(LIB_FOLDER, "libs.txt").download();//有bug,todo 修复
CONFIG_FILE = CONFIG_FOLDER.resolve("config.toml");
I18n.init();
UserBindApi.load(CONFIG_FOLDER);
Expand All @@ -60,7 +61,8 @@ public void onServerStarted(MinecraftServer server) {
onebot = OneBotClient.create(ModConfig.INSTANCE.getBotConfig().build()).open().registerEvents(new IBotEvent());
}
CustomCmdHandler.INSTANCE.load();//自定义命令加载
CQUtilsExecutor = Executors.newSingleThreadExecutor(); // 创建CQ码处理线程池
keepAlive = new KeepAlive();
Const.messageThread.register(keepAlive::register);//自动重连注册
}

public void onServerStopping(MinecraftServer server) {
Expand All @@ -72,7 +74,8 @@ public void onServerStopping(MinecraftServer server) {
}

public void onServerStopped(MinecraftServer server) {
CQUtilsExecutor.shutdownNow();
Const.shutdown();//消息线程关闭
CQUtils.shutdown();//cq转义线程关闭
if (onebot != null) onebot.close();
}

Expand Down
24 changes: 24 additions & 0 deletions forge/src/main/java/cn/evole/mods/mcbot/api/BotChatEvent.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package cn.evole.mods.mcbot.api;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import net.minecraft.server.level.ServerPlayer;
import net.minecraftforge.eventbus.api.Event;

/**
* BotChatEvent
*
* @author cnlimiter
* @version 1.0
* @description
* @date 2024/3/20 19:39
*/
@Getter
@Setter
@AllArgsConstructor
public class BotChatEvent extends Event {
private ServerPlayer player;
private int message_id;
private String message;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@


import cn.evole.mods.mcbot.IMcBot;
import cn.evole.mods.mcbot.McBot;
import cn.evole.mods.mcbot.config.ModConfig;
import cn.evole.mods.mcbot.core.event.IBotEvent;
import cn.evole.onebot.client.OneBotClient;
Expand All @@ -19,7 +18,7 @@

public class ConnectCommand {

public static int cqhttpExecute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
public static int execute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
val parameter = context.getArgument("parameter", String.class);


Expand All @@ -34,10 +33,7 @@ public static int cqhttpExecute(CommandContext<CommandSourceStack> context) thro
//#else
//$$ context.getSource().sendSuccess(Component.literal("▌ " +ChatFormatting.LIGHT_PURPLE + "尝试链接框架"), true);
//#endif
IMcBot.onebot = OneBotClient.create(ModConfig.INSTANCE.getBotConfig().build()).open().registerEvents(new IBotEvent());
ModConfig.INSTANCE.getStatus().setREnable(true);
ModConfig.INSTANCE.getCommon().setEnable(true);
ModConfig.INSTANCE.save();
doConnect();
return 1;

} else {
Expand All @@ -54,20 +50,25 @@ public static int cqhttpExecute(CommandContext<CommandSourceStack> context) thro



public static int cqhttpCommonExecute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
public static int commonExecute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
//#if MC >= 12000
//$$ context.getSource().sendSuccess(()->Component.literal("▌ " +ChatFormatting.LIGHT_PURPLE + "尝试链接框架"), true);
//#elseif MC < 11900
context.getSource().sendSuccess(new TextComponent("▌ " +ChatFormatting.LIGHT_PURPLE + "尝试链接框架"), true);
//#else
//$$ context.getSource().sendSuccess(Component.literal("▌ " +ChatFormatting.LIGHT_PURPLE + "尝试链接框架"), true);
//#endif
doConnect();
return 1;

}

public static void doConnect() {
IMcBot.onebot = OneBotClient.create(ModConfig.INSTANCE.getBotConfig().build()).open().registerEvents(new IBotEvent());
ModConfig.INSTANCE.getStatus().setREnable(true);
ModConfig.INSTANCE.getCommon().setEnable(true);
ModConfig.INSTANCE.save();
return 1;

IMcBot.connected = true;
}


Expand Down
8 changes: 5 additions & 3 deletions forge/src/main/java/cn/evole/mods/mcbot/config/BotConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,12 @@ public class BotConfig extends AutoLoadTomlConfig {
private boolean mirai = false;
@TableField(rightComment = "机器人qq")
private long botId = 0L;//机器人qq
@TableField(rightComment = "重连(未实现)")
@TableField(rightComment = "自动重连")
private boolean reconnect = true;
@TableField(rightComment = "重连次数(未实现)")
private int maxReconnectAttempts = 20;
@TableField(rightComment = "自动重连次数")
private int maxReconnectAttempts = 5;
@TableField(rightComment = "超时宽容度(毫秒)")
private long timeoutCompensation = 5000;

public BotConfig() {
super(null);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
package cn.evole.mods.mcbot.core.event;

import cn.evole.mods.mcbot.Const;
import cn.evole.mods.mcbot.IMcBot;
import cn.evole.mods.mcbot.cmds.CmdApi;
import cn.evole.mods.mcbot.core.data.ChatRecordApi;
import cn.evole.mods.mcbot.config.ModConfig;
import cn.evole.mods.mcbot.util.onebot.CQUtils;
import cn.evole.onebot.client.annotations.SubscribeEvent;
import cn.evole.onebot.client.interfaces.Listener;
import cn.evole.onebot.sdk.event.message.GroupMessageEvent;
import cn.evole.onebot.sdk.event.meta.HeartbeatMetaEvent;
import cn.evole.onebot.sdk.event.meta.LifecycleMetaEvent;
import cn.evole.onebot.sdk.event.notice.group.GroupDecreaseNoticeEvent;
import cn.evole.onebot.sdk.event.notice.group.GroupIncreaseNoticeEvent;
Expand Down Expand Up @@ -120,4 +122,9 @@ public void onLifeCycle(LifecycleMetaEvent event) {
}
}

@SubscribeEvent
public void onHeartbeat(HeartbeatMetaEvent event) {
IMcBot.keepAlive.onHeartbeat(event);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public static void register(ServerPlayer player, String message) {
ModConfig.INSTANCE.getCmd().isMcChatPrefixOn()
&& ModConfig.INSTANCE.getCmd().getMcChatPrefix().equals(split[0]) ? split[1] : message);

Const.sendAllGroupMsg(MsgUtils.builder().text(msg).build());
Const.sendAllGroupMsg(() -> MsgUtils.builder().text(msg).build(), player);

}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,9 +29,9 @@ public static void register(CommandDispatcher<CommandSourceStack> dispatcher){
Commands.literal("mcbot")
.requires(source -> source.hasPermission(2))
.then(Commands.literal("connect")
.executes(ConnectCommand::cqhttpCommonExecute)
.executes(ConnectCommand::commonExecute)
.then(Commands.argument("parameter", StringArgumentType.greedyString())
.executes(ConnectCommand::cqhttpExecute)
.executes(ConnectCommand::execute)
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,16 @@
* @date 2024/3/13 13:48
*/
public class ForgeClassAppender extends URLClassLoader implements ClasspathAppender {
public ForgeClassAppender(URL[] urls, ClassLoader parent) {
super(urls, parent);
static {
ClassLoader.registerAsParallelCapable();
}

public ForgeClassAppender(URL[] urls) {
super(urls);
}

public ForgeClassAppender(URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(urls, parent, factory);
}

public ForgeClassAppender(String name, URL[] urls, ClassLoader parent) {
super(name, urls, parent);
}

public ForgeClassAppender(String name, URL[] urls, ClassLoader parent, URLStreamHandlerFactory factory) {
super(name, urls, parent, factory);
public ForgeClassAppender(ClassLoader parent) {
super(new URL[0], parent);
}

public void addURLs(URL... urls) {
for (URL url : urls) {
this.addURL(url);
}
}
@Override
public void appendFileToClasspath(@NotNull Path path) throws MalformedURLException {
addURLs(path.toUri().toURL());
addURL(path.toUri().toURL());
}

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cn.evole.mods.mcbot.util.lib;


import cn.evole.mods.mcbot.McBot;
import dev.vankka.dependencydownload.DependencyManager;
import net.minecraftforge.fml.loading.FMLLoader;
import dev.vankka.dependencydownload.classpath.ClasspathAppender;
Expand Down Expand Up @@ -44,11 +45,11 @@ public class LibUtils {
private final ClasspathAppender classpathAppender;

public static LibUtils create(Path dataDirectory, String... paths) {
return new LibUtils(Executors.newSingleThreadExecutor(), new ForgeClassAppender(getJars(dataDirectory)), fromPaths(dataDirectory, paths));
return new LibUtils(Executors.newSingleThreadExecutor(), new ForgeClassAppender(getClassLoader()), fromPaths(dataDirectory, paths));
}

public static LibUtils create(Path dataDirectory, ExecutorService executor, String... paths) {
return new LibUtils(executor, new ForgeClassAppender(getJars(dataDirectory)), fromPaths(dataDirectory, paths));
return new LibUtils(executor, new ForgeClassAppender(getClassLoader()), fromPaths(dataDirectory, paths));
}

public static LibUtils create(Path dataDirectory, ClasspathAppender classpathAppender, String... paths) {
Expand All @@ -60,7 +61,7 @@ public static LibUtils create(Path dataDirectory, ExecutorService executor, Clas
}

public static LibUtils create(Path dataDirectory, DependencyManager dependencyManager) {
return new LibUtils(Executors.newSingleThreadExecutor(), new ForgeClassAppender(getJars(dataDirectory)), dependencyManager);
return new LibUtils(Executors.newSingleThreadExecutor(), new ForgeClassAppender(getClassLoader()), dependencyManager);
}


Expand Down Expand Up @@ -135,7 +136,7 @@ private static ClassLoader getClassLoader() {
//$$ loader = Launcher.INSTANCE.findLayerManager().flatMap(lm -> lm.getLayer(IModuleLayerManager.Layer.GAME)).orElseThrow().modules().stream().findFirst().map(Module::getClassLoader).orElse(null);
//#endif
if (loader == null)
loader = LibUtils.class.getClassLoader();
loader = McBot.class.getClassLoader();
return loader;
}

Expand Down
Loading

0 comments on commit e2cd1bb

Please sign in to comment.