Skip to content

Commit

Permalink
```refactor(mcbot): refactor command and bot API for permission overh…
Browse files Browse the repository at this point in the history
…aul- Rename variable 'group_name' to 'group_id' and 'qq_id' to 'user_id' for clarity.

- Implement placeholder replacement in commands to allow for dynamic command construction.
- Remove unused 'GuildRole' enum.
- Add 'PlaceHolderApi' class to handle placeholder replacements.
- Update 'UserInfoApi.get' method to accept 'group_id' and 'user_id' as parameters.
- Refactor 'CmdUtils' utility methods to support new command parsing logic.
- Modify event handling methods to utilize updated command and user info APIs.- Adjust configuration loading and command registration to reflect new permission system.

BREAKING CHANGE: Command syntax and permission checks have been overhauled. Existing
commands may need to be updated to accommodate new placeholder syntax and permission
requirements. Ensure commands are modified accordingly to maintain functionality.
```
  • Loading branch information
cnlimiter committed Aug 18, 2024
1 parent 4e0fd28 commit 46ce02c
Show file tree
Hide file tree
Showing 17 changed files with 169 additions and 71 deletions.
2 changes: 2 additions & 0 deletions common/src/main/java/cn/evole/mods/mcbot/Constants.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package cn.evole.mods.mcbot;

import cn.evole.mods.mcbot.api.cmd.McBotCommandSource;
import cn.evole.mods.mcbot.platform.Services;
import cn.evole.mods.mcbot.util.FileUtils;
import cn.evole.onebot.client.OneBotClient;
Expand Down Expand Up @@ -30,4 +31,5 @@ public class Constants {

public static OneBotClient onebot;
public static MinecraftServer SERVER = null;
public static McBotCommandSource mcBotCommand = null;
}
2 changes: 2 additions & 0 deletions common/src/main/java/cn/evole/mods/mcbot/McBot.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cn.evole.mods.mcbot;


import cn.evole.mods.mcbot.api.cmd.McBotCommandSource;
import cn.evole.mods.mcbot.api.config.ConfigManager;
import cn.evole.mods.mcbot.api.event.server.ServerGameEvents;
import cn.evole.mods.mcbot.common.config.*;
Expand Down Expand Up @@ -45,6 +46,7 @@ public static void onServerStarting(MinecraftServer server) {
}

public static void onServerStarted(MinecraftServer server) {
mcBotCommand = new McBotCommandSource(server);
if (ModConfig.get().getCommon().isAutoOpen()) {
onebot = OneBotClient
.create(ModConfig.get().getBotConfig().build())
Expand Down
8 changes: 4 additions & 4 deletions common/src/main/java/cn/evole/mods/mcbot/api/bot/BotApi.java
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@
* @Description:
*/
public class BotApi {
public static void sendGroupMsg(long id, String message) {
MsgThreadUtils.INSTANCE.submit(id, message, false);
public static void sendGroupMsg(long group_id, String message) {
MsgThreadUtils.INSTANCE.submit(group_id, message, false);
}

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

public static void sendAllGroupMsg(String message) {
Expand Down
29 changes: 20 additions & 9 deletions common/src/main/java/cn/evole/mods/mcbot/api/cmd/CmdApi.java
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package cn.evole.mods.mcbot.api.cmd;

import cn.evole.mods.mcbot.Constants;
import cn.evole.mods.mcbot.api.bot.BotApi;
import cn.evole.mods.mcbot.api.data.UserInfoApi;
import cn.evole.mods.mcbot.plugins.cmd.CmdHandler;
import cn.evole.mods.mcbot.util.CmdUtils;
import cn.evole.onebot.sdk.event.message.GroupMessageEvent;
import lombok.val;
Expand All @@ -14,22 +17,30 @@
public class CmdApi {


public static void invokeCommandGroup(GroupMessageEvent event, String msg) {
public static void invokeGroupCommand(GroupMessageEvent event, String msg) {
String originCmd = msg.substring(1);//去除前缀

val user_id = String.valueOf(event.getUserId());
val group_id = String.valueOf(event.getGroupId());

val cmd = CmdUtils.varParse(event, originCmd);


if (UserInfoApi.groupHas(group_id, user_id)){

if (cmd == null) return;

if (CmdUtils.groupAdminParse(event)) {
Constants.LOGGER.info(cmd.getCmd());
BotApi.sendGroupMsg(event.getGroupId(), Constants.mcBotCommand.runCommand(cmd.getCmd()));//执行指令
if (!cmd.getAfter_cmds().isEmpty())
cmd.getAfter_cmds().forEach(s -> BotApi.sendGroupMsg(event.getGroupId(), Constants.mcBotCommand.runCommand(s)));
} else if (CmdUtils.hasPermission(group_id, user_id, cmd)) {
BotApi.sendGroupMsg(event.getGroupId(), Constants.mcBotCommand.runCommand(cmd.getCmd()));//执行指令
if (!cmd.getAfter_cmds().isEmpty()) {//连续指令是否为空
cmd.getAfter_cmds().forEach(s -> {
if (CmdUtils.hasPermission(group_id, user_id, CmdHandler.cmds.get(s))) {//再次检测下条指令是否有权限
BotApi.sendGroupMsg(event.getGroupId(), Constants.mcBotCommand.runCommand(s));
}
});
}
}





}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
* @Description:
*/
public class McBotCommandSource implements CommandSource {
private static final Component RCON_COMPONENT = Component.literal("McBot");
private static final Component MCBOT_COMPONENT = Component.literal("McBot");
private final StringBuffer buffer = new StringBuffer();
private final MinecraftServer server;

Expand All @@ -33,7 +33,7 @@ public String getCommandResponse() {

public CommandSourceStack createCommandSourceStack() {
ServerLevel overworld = this.server.overworld();
return new CommandSourceStack(this, Vec3.atLowerCornerOf(overworld.getSharedSpawnPos()), Vec2.ZERO, overworld, 4, "McBot", RCON_COMPONENT, this.server, null);
return new CommandSourceStack(this, Vec3.atLowerCornerOf(overworld.getSharedSpawnPos()), Vec2.ZERO, overworld, 4, "McBot", MCBOT_COMPONENT, this.server, null);
}

@Override
Expand Down
12 changes: 12 additions & 0 deletions common/src/main/java/cn/evole/mods/mcbot/api/data/UserInfoApi.java
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
package cn.evole.mods.mcbot.api.data;

import cn.evole.mods.mcbot.Constants;
import cn.evole.mods.mcbot.common.config.ModConfig;
import cn.evole.mods.mcbot.plugins.data.UserInfo;
import cn.evole.mods.mcbot.util.FileUtils;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;

/**
Expand Down Expand Up @@ -35,6 +37,10 @@ public static boolean isInGame(String group_id, String user_id){
return false;
}

public static UserInfo get(String group_id, String user_id){
return userInfos.stream().filter(userInfo -> userInfo.getGroupId().equals(group_id) && userInfo.getQqId().equals(user_id)).findFirst().orElse(null);
}

public static void add(String group_id, String qq_id, String game_name){
if (!groupHas(group_id, qq_id)) {
UserInfo userInfo = new UserInfo();
Expand All @@ -43,6 +49,12 @@ public static void add(String group_id, String qq_id, String game_name){
userInfo.setGroupId(group_id);
userInfo.setGameName(game_name);
userInfo.setCoin(5);

List<String> permissions = new ArrayList<>();
for (String permission : userInfo.getPermissions()){
permissions.add(ModConfig.get().getBotConfig().getTag() + "." + permission);//添加权限tag,区分群组服
}
userInfo.setPermissions(permissions);
userInfos.add(userInfo);
}
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package cn.evole.mods.mcbot.api.placeholder;

/**
* @Project: McBot
* @Author: cnlimiter
* @CreateTime: 2024/8/18 14:08
* @Description:
*/
public class PlaceHolderApi {
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,24 @@
package cn.evole.mods.mcbot.common.command;

import cn.evole.mods.mcbot.api.data.UserInfoApi;
import cn.evole.mods.mcbot.common.config.ModConfig;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;

public class AddBindCommand {

public static int execute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
String group_name = context.getArgument("GroupName", String.class);
String qq_id = context.getArgument("QQId", String.class);
String group_id = String.valueOf(context.getArgument("GroupId", Long.class));
String qq_id = String.valueOf(context.getArgument("QQId", Long.class));
String game_name = context.getArgument("GameName", String.class);
//UserBindApi.add(group_name, qq_id, game_name);
ModConfig.save();
if (UserInfoApi.get(group_id, qq_id) == null) {
UserInfoApi.add(group_id, qq_id, game_name);
context.getSource().sendSuccess(() -> Component.literal("群: "+ group_id + " 的用户: " + qq_id + "绑定成功!"), true);
} else {
context.getSource().sendSuccess(() -> Component.literal("群: "+ group_id + " 的用户: " + qq_id + "已经绑定完毕!"), true);
}
return 1;
}
}
Original file line number Diff line number Diff line change
@@ -1,16 +1,23 @@
package cn.evole.mods.mcbot.common.command;

import cn.evole.mods.mcbot.api.data.UserInfoApi;
import cn.evole.mods.mcbot.common.config.ModConfig;
import com.mojang.brigadier.context.CommandContext;
import com.mojang.brigadier.exceptions.CommandSyntaxException;
import net.minecraft.commands.CommandSourceStack;
import net.minecraft.network.chat.Component;

public class DelBindCommand {

public static int execute(CommandContext<CommandSourceStack> context) throws CommandSyntaxException {
String qq_id = context.getArgument("QQId", String.class);
//UserBindApi.del(qq_id);
ModConfig.save();
String group_id = String.valueOf(context.getArgument("GroupId", Long.class));
String qq_id = String.valueOf(context.getArgument("QQId", Long.class));
if (UserInfoApi.get(group_id, qq_id) != null) {
UserInfoApi.del(group_id, qq_id);
context.getSource().sendSuccess(() -> Component.literal("群: "+ group_id + " 的用户: " + qq_id + " 删除成功!"), true);
} else {
context.getSource().sendSuccess(() -> Component.literal("群: "+ group_id + " 的用户: " + qq_id + " 未找到!"), true);
}
return 1;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@
@Setter
@ConfigSerializable
public class StatusConfig {
//连接的消息开关
@Comment("连接提醒")
private boolean connectInfoEnable = true;
//接收来自q群的消息开关
@Comment("全局接收")
private boolean rEnable = true;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package cn.evole.mods.mcbot.common.event;

import cn.evole.mods.mcbot.api.bot.BotApi;
import cn.evole.mods.mcbot.api.cmd.CmdApi;
import cn.evole.mods.mcbot.api.data.ChatRecordApi;
import cn.evole.mods.mcbot.common.config.ModConfig;
import cn.evole.mods.mcbot.util.onebot.CQUtils;
import cn.evole.onebot.client.annotations.SubscribeEvent;
Expand Down Expand Up @@ -57,14 +59,14 @@ private void onGroupMessage(GroupMessageEvent event, String send) {
: String.format("§b[§l%s§b]§a<%s>§f %s", ModConfig.get().getCmd().getQqGamePrefix(), groupNick, send)
: String.format("§a<%s>§f %s", groupNick, send);

//ChatRecordApi.add(String.valueOf(event.getMessageId()), String.valueOf(event.getGroupId()), String.valueOf(event.getSelfId()), finalMsg);
ChatRecordApi.add(String.valueOf(event.getMessageId()), String.valueOf(event.getGroupId()), String.valueOf(event.getSelfId()), finalMsg);

BotApi.sendAllPlayerMsg(finalMsg);
}


private void onGroupCmd(GroupMessageEvent event, String rawMsg) {
//CmdApi.invokeCommandGroup(rawMsg, event);
CmdApi.invokeGroupCommand(event, rawMsg);
}

@SubscribeEvent
Expand All @@ -90,7 +92,8 @@ public void onGroupMemberQuit(GroupDecreaseNoticeEvent event) {
@SubscribeEvent
public void onLifeCycle(LifecycleMetaEvent event) {
if (!event.getSubType().equals("connect")) return;
if (!ModConfig.get().getCommon().getGroupIdList().isEmpty()
if (!ModConfig.get().getStatus().isConnectInfoEnable()
&&!ModConfig.get().getCommon().getGroupIdList().isEmpty()
) {
val msg = "▌ 群服互联已连接 ┈━═☆";
BotApi.sendAllGroupMsg(msg);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,7 @@ public static void register(ServerPlayer player, String message) {
ModConfig.get().getCmd().isMcChatPrefixOn()
&& ModConfig.get().getCmd().getMcChatPrefix().equals(split[0]) ? split[1] : message);

BotApi.sendAllGroupMsg(() -> MsgUtils.builder().text(CQUtils.replace(msg)).build(), player);

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

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,16 @@ public static void register(CommandDispatcher<CommandSourceStack> dispatcher) {
.then(Commands.argument("MessageId", IntegerArgumentType.integer())
.executes(RecallCommand::execute)))
.then(Commands.literal("addBind")
.then(Commands.argument("GroupName", StringArgumentType.greedyString())
.then(Commands.argument("QQId", StringArgumentType.greedyString())
.then(Commands.argument("GroupId", LongArgumentType.longArg())
.then(Commands.argument("QQId", LongArgumentType.longArg())
.then(Commands.argument("GameName", StringArgumentType.greedyString())
.executes(AddBindCommand::execute)
))))
.then(Commands.literal("delBind")
.then(Commands.argument("QQId", StringArgumentType.greedyString())
.executes(DelBindCommand::execute)))
.then(Commands.argument("GroupId", LongArgumentType.longArg())
.then(Commands.argument("QQId", LongArgumentType.longArg())
.executes(DelBindCommand::execute)
)))


.then(Commands.literal("debug")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ public static void load() {

private static void writeDefault() {
if (!dir.exists() && dir.mkdirs()) {
JsonObject json1 = GSON.fromJson("{'id': 'list', 'cmd': 'list', 'alies': ['服务器在线'], 'allow_members': [], permission: 'ALL', 'answer': 'NO', 'enable': true}", JsonObject.class);
JsonObject json2 = GSON.fromJson("{'id': 'say', 'cmd': 'say %', 'alies': ['转发'], 'allow_members': [], permission: 'OP', 'answer': '转发成功!', 'enable': true}", JsonObject.class);
JsonObject json3 = GSON.fromJson("{'id': 'bind', 'cmd': 'mcbot addBind %', 'alies': ['绑定'], 'allow_members': [], permission: 'ALL', 'answer': '绑定 % 成功!', 'enable': true}", JsonObject.class);
JsonObject json1 = GSON.fromJson("{'id': 'list', 'cmd': 'list', 'alies': ['服务器在线'], 'allow_members': [], permission: 'ALL', 'after_cmds': [], 'answer': 'NO', 'enable': true}", JsonObject.class);
JsonObject json2 = GSON.fromJson("{'id': 'say', 'cmd': 'say %', 'alies': ['转发'], 'allow_members': [], permission: 'OP', 'after_cmds': [], 'answer': '转发成功!', 'enable': true}", JsonObject.class);
JsonObject json3 = GSON.fromJson("{'id': 'bind', 'cmd': 'mcbot addBind %', 'alies': ['绑定'], 'allow_members': [], permission: 'ALL', 'after_cmds': [], 'answer': '绑定 % 成功!', 'enable': true}", JsonObject.class);

// 尝试创建和写入文件
try (FileWriter writerList = new FileWriter(new File(dir, "list.json"));
Expand Down
Loading

0 comments on commit 46ce02c

Please sign in to comment.