Skip to content

Commit

Permalink
+ 现可以往游戏里发送图片了哦
Browse files Browse the repository at this point in the history
+ 与chatImage联动
  • Loading branch information
cnlimiter committed Feb 10, 2023
1 parent 2fc4828 commit acb4b0b
Show file tree
Hide file tree
Showing 12 changed files with 105 additions and 38 deletions.
3 changes: 2 additions & 1 deletion build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ repositories {

dependencies {

// To change the versions see the gradle.properties file
minecraft "com.mojang:minecraft:${project.minecraft_version}"
compileOnly 'org.projectlombok:lombok:1.18.24'
mappings loom.layered() {
Expand All @@ -29,6 +28,8 @@ dependencies {
modImplementation "net.fabricmc:fabric-loader:${project.loader_version}"
modImplementation include("cn.evolvefield.bot:OneBot-SDK:${project.sdk_version}")
modImplementation "net.fabricmc.fabric-api:fabric-api:${project.fabric_version}"
modImplementation fileTree(dir: 'libs', include: ['*.jar'])

//modImplementation include("eu.pb4:placeholder-api:${project.placeholder_version}")
annotationProcessor "cn.evolvefield.bot:OneBot-SDK:${project.sdk_version}"
annotationProcessor "org.projectlombok:lombok:1.18.24"
Expand Down
2 changes: 1 addition & 1 deletion gradle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ loader_version=0.14.13
# Mod Properties
version_prefix=1.19.X
mod_version=2.1.1
sdk_version=0.2.0-jdk17
sdk_version=0.2.1-jdk17
parchement_version=2022.12.18
maven_group=cn.evolvefield.mods
archives_base_name=Bot-Connect-fabric
Expand Down
6 changes: 3 additions & 3 deletions src/main/java/cn/evolvefield/mods/botapi/BotApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public class BotApi implements ModInitializer {
public static ModConfig config;

public BotApi() {

Const.ChatImageOn = FabricLoader.getInstance().isModLoaded("chatimage");
}

@Override
Expand Down Expand Up @@ -68,7 +68,7 @@ private void onServerStarted(MinecraftServer server) {
service.create();//创建websocket连接
bot = service.createBot();//创建机器人实例
} catch (Exception e) {
Static.LOGGER.error("§c机器人服务端未配置或未打开");
Const.LOGGER.error("§c机器人服务端未配置或未打开");
}
}
dispatchers = new EventDispatchers(blockingQueue);//创建事件分发器
Expand All @@ -86,7 +86,7 @@ private void onServerStopping(MinecraftServer server) {
service.close();
}
ConfigHandler.save(config);
Static.LOGGER.info("▌ §c正在关闭群服互联 §a┈━═☆");
Const.LOGGER.info("▌ §c正在关闭群服互联 §a┈━═☆");

}
}
17 changes: 17 additions & 0 deletions src/main/java/cn/evolvefield/mods/botapi/Const.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package cn.evolvefield.mods.botapi;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

/**
* Description:
* Author: cnlimiter
* Date: 2022/10/1 16:58
* Version: 1.0
*/
public class Const {
public static final String MODID = "botapi";
public static final Logger LOGGER = LogManager.getLogger(MODID);
public static boolean ChatImageOn;

}
16 changes: 0 additions & 16 deletions src/main/java/cn/evolvefield/mods/botapi/Static.java

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@


import cn.evolvefield.mods.botapi.BotApi;
import cn.evolvefield.mods.botapi.Static;
import cn.evolvefield.mods.botapi.Const;
import cn.evolvefield.mods.botapi.init.handler.ConfigHandler;
import cn.evolvefield.onebot.sdk.connection.ConnectFactory;
import com.mojang.brigadier.Command;
Expand Down Expand Up @@ -31,7 +31,7 @@ public static int cqhttpExecute(CommandContext<CommandSourceStack> context) thro
BotApi.service.create();//创建websocket连接
BotApi.bot = BotApi.service.createBot();//创建机器人实例
} catch (Exception e) {
Static.LOGGER.error(e.getMessage());
Const.LOGGER.error(e.getMessage());
}
BotApi.config.getStatus().setRECEIVE_ENABLED(true);
BotApi.config.getCommon().setEnable(true);
Expand Down Expand Up @@ -59,7 +59,7 @@ public static int miraiExecute(CommandContext<CommandSourceStack> context) throw
BotApi.service.create();//创建websocket连接
BotApi.bot = BotApi.service.createBot();//创建机器人实例
} catch (Exception e) {
Static.LOGGER.error(e.getMessage());
Const.LOGGER.error(e.getMessage());
}
BotApi.config.getStatus().setRECEIVE_ENABLED(true);
BotApi.config.getCommon().setEnable(true);
Expand All @@ -82,7 +82,7 @@ public static int cqhttpCommonExecute(CommandContext<CommandSourceStack> context
BotApi.service.create();//创建websocket连接
BotApi.bot = BotApi.service.createBot();//创建机器人实例
} catch (Exception e) {
Static.LOGGER.error(e.getMessage());
Const.LOGGER.error(e.getMessage());
}
BotApi.config.getStatus().setRECEIVE_ENABLED(true);
BotApi.config.getCommon().setEnable(true);
Expand All @@ -101,7 +101,7 @@ public static int miraiCommonExecute(CommandContext<CommandSourceStack> context)
BotApi.service.create();//创建websocket连接
BotApi.bot = BotApi.service.createBot();//创建机器人实例
} catch (Exception e) {
Static.LOGGER.error(e.getMessage());
Const.LOGGER.error(e.getMessage());
}
BotApi.config.getStatus().setRECEIVE_ENABLED(true);
BotApi.config.getCommon().setEnable(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ public static class Common {
private String languageSelect = "zh_cn";//选择语言系统
@SerializedName("auto_open")
private boolean autoOpen = true;//自动重连
@SerializedName("image_on")
private boolean imageOn = true;//是否开启聊天栏图片功能

public void addChannelId(String id) {
this.channelIdList.add(id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import cn.evolvefield.mods.botapi.BotApi;
import cn.evolvefield.mods.botapi.api.cmd.CmdApi;
import cn.evolvefield.mods.botapi.util.onebot.CQUtils;
import cn.evolvefield.onebot.sdk.listener.SimpleListener;
import cn.evolvefield.onebot.sdk.model.event.EventDispatchers;
import cn.evolvefield.onebot.sdk.model.event.message.GroupMessageEvent;
Expand Down Expand Up @@ -32,12 +33,13 @@ private static void GroupChatHandler(EventDispatchers dispatchers) {
public void onMessage(GroupMessageEvent event) {
if (BotApi.config.getCommon().getGroupIdList().contains(event.getGroupId())//判断是否是配置中的群
&& !event.getMessage().startsWith(BotApi.config.getCmd().getCommandStart())//过滤命令前缀
&& !event.getMessage().contains("[CQ:")//去除字符之外的其他cq码
&& BotApi.config.getStatus().isRECEIVE_ENABLED()//总接受开关
&& BotApi.config.getStatus().isR_CHAT_ENABLE()//接受聊天开关
&& event.getUserId() != BotApi.config.getCommon().getBotId()
) {
String send = event.getMessage();

String send = CQUtils.replace(event.getMessage());//暂时匹配仅符合字符串聊天内容与图片

if (BotApi.config.getCmd().isQqChatPrefixEnable()) {
var split = event.getMessage().split(" ");
if (BotApi.config.getCmd().getQqChatPrefix().equals(split[0])) //指定前缀发送
Expand All @@ -46,6 +48,8 @@ public void onMessage(GroupMessageEvent event) {
}
String toSend = String.format("§b[§l%s§r(§5%s§b)]§a<%s>§f %s", BotApi.config.getCmd().getQqPrefix(), event.getGroupId(), event.getSender().getNickname(), send);
TickEventHandler.getToSendQueue().add(toSend);


}
}
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ public static void init() {
var split = message.split(" ");
if (BotApi.config != null
&& BotApi.config.getStatus().isS_CHAT_ENABLE()
&& BotApi.config.getStatus().isSEND_ENABLED()) {
&& BotApi.config.getStatus().isSEND_ENABLED()
&& !message.contains("CICode")
) {
if (BotApi.config.getCommon().isGuildOn() && !BotApi.config.getCommon().getChannelIdList().isEmpty()) {
for (String id : BotApi.config.getCommon().getChannelIdList())
BotApi.bot.sendGuildMsg(BotApi.config.getCommon().getGuildId(),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package cn.evolvefield.mods.botapi.init.handler;

import cn.evolvefield.mods.botapi.Static;
import cn.evolvefield.mods.botapi.Const;
import cn.evolvefield.mods.botapi.api.cmd.CustomCmd;
import com.google.common.base.Stopwatch;
import com.google.common.collect.Lists;
Expand Down Expand Up @@ -60,7 +60,7 @@ public void load() {

stopwatch.stop();

Static.LOGGER.info("Loaded {} custom cmd(s) in {} ms", this.customCmdMap.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
Const.LOGGER.info("Loaded {} custom cmd(s) in {} ms", this.customCmdMap.size(), stopwatch.elapsed(TimeUnit.MILLISECONDS));
}

public void writeDefault() {
Expand Down Expand Up @@ -92,7 +92,7 @@ public void writeDefault() {
writer.close();
writer2.close();
} catch (Exception e) {
Static.LOGGER.error("An error occurred while generating default custom cmd", e);
Const.LOGGER.error("An error occurred while generating default custom cmd", e);
} finally {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(writer2);
Expand All @@ -116,11 +116,11 @@ private void loadFiles() {
var name = file.getName().replace(".json", "");
json = JsonParser.parseReader(reader).getAsJsonObject();

customCmd = CustomCmd.loadFromJson(new ResourceLocation(Static.MODID, name), json);
customCmd = CustomCmd.loadFromJson(new ResourceLocation(Const.MODID, name), json);

reader.close();
} catch (Exception e) {
Static.LOGGER.error("加载自定义命令出错,请检查文件", e);
Const.LOGGER.error("加载自定义命令出错,请检查文件", e);
} finally {
IOUtils.closeQuietly(reader);
}
Expand All @@ -129,7 +129,7 @@ private void loadFiles() {
String alies = customCmd.getCmdAlies();
if (customCmd.getCmdContent().contains("%"))
alies = customCmd.getCmdContent().split("%")[0].stripTrailing();
Static.LOGGER.debug(alies);
Const.LOGGER.debug(alies);
this.customCmdMap.put(alies, customCmd);


Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
package cn.evolvefield.mods.botapi.util.locale;

import cn.evolvefield.mods.botapi.BotApi;
import cn.evolvefield.mods.botapi.Static;
import cn.evolvefield.mods.botapi.Const;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.gson.Gson;
Expand Down Expand Up @@ -44,7 +44,7 @@ private static Translation loadDefault(String langId) {
InputStream inputStream = Translation.class.getResourceAsStream(resourceLocation);

if (inputStream == null) {
Static.LOGGER.info(String.format("No BotApi lang file for the language '%s' found. Make it to 'en_us' by default.", langId));
Const.LOGGER.info(String.format("No BotApi lang file for the language '%s' found. Make it to 'en_us' by default.", langId));
inputStream = I18n.class.getResourceAsStream(String.format(resourceFString, DEFAULT_LANGUAGE));
}

Expand All @@ -66,7 +66,7 @@ private static Translation loadDefault(String langId) {
inputStream.close();
}
} catch (JsonParseException | IOException var8) {
Static.LOGGER.error("Couldn't read strings from {}", resourceLocation, var8);
Const.LOGGER.error("Couldn't read strings from {}", resourceLocation, var8);
}

final Map<String, String> inputStream = builder.build();
Expand Down
57 changes: 57 additions & 0 deletions src/main/java/cn/evolvefield/mods/botapi/util/onebot/CQUtils.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package cn.evolvefield.mods.botapi.util.onebot;

import cn.evolvefield.mods.botapi.Const;
import cn.evolvefield.onebot.sdk.util.BotUtils;
import cn.evolvefield.onebot.sdk.util.RegexUtils;

import java.util.Arrays;
import java.util.concurrent.atomic.AtomicReference;
import java.util.regex.Pattern;

/**
* Project: Bot-Connect-fabric-1.18
* Author: cnlimiter
* Date: 2023/2/10 1:11
* Description:
*/
public class CQUtils {

private final static String CQ_CODE_SPLIT = "(?<=\\[CQ:[^]]{1,99999}])|(?=\\[CQ:[^]]{1,99999}])";

private final static String CQ_CODE_REGEX = "\\[CQ:([^,\\[\\]]+)((?:,[^,=\\[\\]]+=[^,\\[\\]]*)*)]";


public static boolean hasImg(String msg) {
String regex = "\\[CQ:image,[(\\s\\S)]*\\]";
var p = Pattern.compile(regex);
var m = p.matcher(msg);
return m.find();
}

public static String replace(String msg) {
if (Const.ChatImageOn) {
var matcher = RegexUtils.regexMatcher(CQ_CODE_REGEX, msg);//匹配cq码格式
AtomicReference<String> returnMsg = new AtomicReference<>("");//返回字符串
if (matcher == null) {
returnMsg.set(msg);//不包含任何cq码则返回原msg
} else {
//while (matcher.find()){//找到所有符合的matcher
if (matcher.group(1).equals("image")) {//如果是图片格式
Arrays.stream(matcher.group(2).split(","))//具体数据分割
.filter(args -> !args.isEmpty())//非空判断
.forEach(args -> {
if (args.substring(0, args.indexOf("=")).equals("url")) {//url
var v = BotUtils.unescape(args.substring(args.indexOf("=") + 1));//去除空格

returnMsg.set(matcher.replaceAll(String.format("[[CICode,url=%s,name=来自QQ的图片]]", v)));//转换ci码
}
});
}
//}
}

return returnMsg.get();

} else return msg;
}
}

0 comments on commit acb4b0b

Please sign in to comment.