Add debug start and stop, fix Discord & game command registration

This commit is contained in:
Vankka 2025-01-02 23:50:14 +02:00
parent 66900db7dd
commit 45fefaedac
No known key found for this signature in database
GPG Key ID: 62E48025ED4E7EBB
11 changed files with 189 additions and 73 deletions

View File

@ -0,0 +1,35 @@
/*
* This file is part of DiscordSRV, licensed under the GPLv3 License
* Copyright (c) 2016-2025 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
package com.discordsrv.bukkit.command.game;
import com.discordsrv.bukkit.BukkitDiscordSRV;
import com.discordsrv.common.util.ReflectionUtil;
import org.bukkit.Server;
import org.bukkit.command.CommandMap;
public final class PaperCommandMap {
private PaperCommandMap() {}
public static boolean IS_SUPPORTED = ReflectionUtil.methodExists(Server.class, "getCommandMap", new Class[0]);
public static CommandMap getCommandMap(BukkitDiscordSRV discordSRV) {
return discordSRV.server().getCommandMap();
}
}

View File

@ -43,7 +43,7 @@ public class PaperChatRenderListener extends AbstractBukkitListener<AsyncChatDec
}
@EventHandler(priority = EventPriority.NORMAL, ignoreCancelled = true)
public void onAsyncPlayerChat(AsyncChatDecorateEvent event) {
public void onAsyncChatDecorate(AsyncChatDecorateEvent event) {
handleEvent(event);
}

View File

@ -7,7 +7,7 @@ repositories {
configurations {
commodore
compileOnly.extendsFrom commodore
compileOnlyApi.extendsFrom commodore
}
tasks.register('generateResourceForCommodore', GenerateDependencyDownloadResourceTask) {

View File

@ -21,8 +21,6 @@ package com.discordsrv.bukkit;
import com.discordsrv.api.DiscordSRVApi;
import com.discordsrv.api.reload.ReloadFlag;
import com.discordsrv.api.reload.ReloadResult;
import com.discordsrv.bukkit.command.game.handler.BukkitBasicCommandHandler;
import com.discordsrv.bukkit.command.game.handler.CommodoreHandler;
import com.discordsrv.bukkit.component.translation.BukkitTranslationLoader;
import com.discordsrv.bukkit.config.main.BukkitConfig;
import com.discordsrv.bukkit.player.BukkitPlayerProvider;
@ -30,7 +28,6 @@ import com.discordsrv.bukkit.plugin.BukkitPluginManager;
import com.discordsrv.bukkit.scheduler.BukkitScheduler;
import com.discordsrv.common.AbstractDiscordSRV;
import com.discordsrv.common.command.game.abstraction.GameCommandExecutionHelper;
import com.discordsrv.common.command.game.abstraction.handler.ICommandHandler;
import com.discordsrv.common.config.configurate.manager.ConnectionConfigManager;
import com.discordsrv.common.config.configurate.manager.MainConfigManager;
import com.discordsrv.common.config.configurate.manager.MessagesConfigManager;
@ -38,7 +35,6 @@ import com.discordsrv.common.config.configurate.manager.abstraction.ServerConfig
import com.discordsrv.common.config.connection.ConnectionConfig;
import com.discordsrv.common.config.messages.MessagesConfig;
import com.discordsrv.common.feature.debug.data.OnlineMode;
import com.discordsrv.common.util.ReflectionUtil;
import net.kyori.adventure.platform.bukkit.BukkitAudiences;
import org.bukkit.Server;
import org.bukkit.plugin.ServicePriority;
@ -56,7 +52,6 @@ public abstract class BukkitDiscordSRV extends AbstractDiscordSRV<IBukkitBootstr
private BukkitTranslationLoader translationLoader;
private final BukkitPluginManager pluginManager;
private ICommandHandler commandHandler;
private final ConnectionConfigManager<ConnectionConfig> connectionConfigManager;
private final MainConfigManager<BukkitConfig> configManager;
@ -82,13 +77,6 @@ public abstract class BukkitDiscordSRV extends AbstractDiscordSRV<IBukkitBootstr
this.audiences = BukkitAudiences.create(bootstrap.getPlugin());
this.translationLoader = new BukkitTranslationLoader(this);
// Commands
if (ReflectionUtil.classExists("com.mojang.brigadier.CommandDispatcher")) {
this.commandHandler = new CommodoreHandler(this);
} else {
this.commandHandler = new BukkitBasicCommandHandler(this);
}
// Integrations
registerIntegration("com.discordsrv.bukkit.integration.VaultIntegration");
registerIntegration("com.discordsrv.bukkit.integration.PlaceholderAPIIntegration");
@ -169,11 +157,6 @@ public abstract class BukkitDiscordSRV extends AbstractDiscordSRV<IBukkitBootstr
return pluginManager;
}
@Override
public ICommandHandler commandHandler() {
return commandHandler;
}
@Override
public ConnectionConfigManager<ConnectionConfig> connectionConfigManager() {
return connectionConfigManager;

View File

@ -20,6 +20,8 @@ package com.discordsrv.bukkit;
import com.discordsrv.bukkit.command.game.BukkitGameCommandExecutionHelper;
import com.discordsrv.bukkit.command.game.PaperGameCommandExecutionHelper;
import com.discordsrv.bukkit.command.game.handler.BukkitBasicCommandHandler;
import com.discordsrv.bukkit.command.game.handler.CommodoreHandler;
import com.discordsrv.bukkit.component.PaperComponentHandle;
import com.discordsrv.bukkit.console.BukkitConsole;
import com.discordsrv.bukkit.listener.*;
@ -29,6 +31,7 @@ import com.discordsrv.bukkit.requiredlinking.BukkitRequiredLinkingModule;
import com.discordsrv.bukkit.scheduler.BukkitScheduler;
import com.discordsrv.bukkit.scheduler.FoliaScheduler;
import com.discordsrv.common.command.game.abstraction.GameCommandExecutionHelper;
import com.discordsrv.common.command.game.abstraction.handler.ICommandHandler;
import com.discordsrv.common.feature.messageforwarding.game.MinecraftToDiscordChatModule;
import com.discordsrv.common.util.ReflectionUtil;
import org.bukkit.command.CommandMap;
@ -42,6 +45,8 @@ public class BukkitDiscordSRVImpl extends BukkitDiscordSRV {
private final BukkitPlayerProvider playerProvider;
private final BukkitConsole console;
private ICommandHandler commandHandler;
public BukkitDiscordSRVImpl(IBukkitBootstrap bootstrap) {
super(bootstrap);
@ -59,6 +64,13 @@ public class BukkitDiscordSRVImpl extends BukkitDiscordSRV {
@Override
protected void enable() throws Throwable {
// Commands
if (ReflectionUtil.classExists("com.mojang.brigadier.CommandDispatcher")) {
this.commandHandler = new CommodoreHandler(this);
} else {
this.commandHandler = new BukkitBasicCommandHandler(this);
}
super.enable();
// Modules
@ -120,4 +132,9 @@ public class BukkitDiscordSRVImpl extends BukkitDiscordSRV {
public BukkitConsole console() {
return console;
}
@Override
public ICommandHandler commandHandler() {
return commandHandler;
}
}

View File

@ -19,6 +19,7 @@
package com.discordsrv.bukkit.command.game.handler;
import com.discordsrv.bukkit.BukkitDiscordSRV;
import com.discordsrv.bukkit.command.game.PaperCommandMap;
import com.discordsrv.bukkit.command.game.sender.BukkitCommandSender;
import com.discordsrv.common.command.game.abstraction.command.GameCommand;
import com.discordsrv.common.command.game.abstraction.handler.BasicCommandHandler;
@ -30,9 +31,11 @@ import org.bukkit.command.*;
import org.bukkit.entity.Player;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
public class BukkitBasicCommandHandler extends BasicCommandHandler implements TabExecutor, ICommandHandler {
public class BukkitBasicCommandHandler extends BasicCommandHandler implements ICommandHandler, TabExecutor {
protected final BukkitDiscordSRV discordSRV;
protected final Logger logger;
@ -52,32 +55,46 @@ public class BukkitBasicCommandHandler extends BasicCommandHandler implements Ta
}
}
protected PluginCommand command(GameCommand gameCommand) {
protected Command command(GameCommand gameCommand) {
String label = gameCommand.getLabel();
return discordSRV.plugin().getCommand(label);
PluginCommand pluginCommand = discordSRV.plugin().getCommand(label);
if (pluginCommand != null) {
pluginCommand.setExecutor(this);
pluginCommand.setTabCompleter(this);
return pluginCommand;
}
if (PaperCommandMap.IS_SUPPORTED) {
BukkitCommand bukkitCommand = new BukkitCommand(label);
PaperCommandMap.getCommandMap(discordSRV).register(label, bukkitCommand);
return bukkitCommand;
}
return null;
}
protected void registerPluginCommand(PluginCommand pluginCommand, GameCommand gameCommand) {
protected void registerPluginCommand(Command command, GameCommand gameCommand) {
logger.debug("Registering command " + gameCommand.getLabel() + " with basic handler");
pluginCommand.setExecutor(this);
pluginCommand.setTabCompleter(this);
}
@Override
public void registerCommand(GameCommand command) {
super.registerCommand(command);
discordSRV.scheduler().runOnMainThread(() -> {
PluginCommand pluginCommand = command(command);
if (pluginCommand == null) {
Command bukkitCommand = command(command);
if (bukkitCommand == null) {
logger.error("Failed to create command " + command.getLabel());
return;
}
registerPluginCommand(pluginCommand, command);
registerPluginCommand(bukkitCommand, command);
});
}
private static List<String> aliases(BukkitDiscordSRV discordSRV, String name) {
return Collections.singletonList(discordSRV.plugin().getName().toLowerCase(Locale.ROOT) + ":" + name);
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
execute(sender(sender), label, Arrays.asList(args));
@ -88,4 +105,21 @@ public class BukkitBasicCommandHandler extends BasicCommandHandler implements Ta
public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
return suggest(sender(sender), alias, Arrays.asList(args));
}
public class BukkitCommand extends Command {
protected BukkitCommand(String name) {
super(name, null, null, aliases(discordSRV, name));
}
@Override
public boolean execute(CommandSender sender, String label, String[] args) {
return BukkitBasicCommandHandler.this.onCommand(sender, this, label, args);
}
@Override
public List<String> tabComplete(CommandSender sender, String alias, String[] args) throws IllegalArgumentException {
return BukkitBasicCommandHandler.this.onTabComplete(sender, this, alias, args);
}
}
}

View File

@ -25,7 +25,7 @@ import com.discordsrv.common.command.game.abstraction.handler.util.BrigadierUtil
import com.mojang.brigadier.tree.LiteralCommandNode;
import me.lucko.commodore.Commodore;
import me.lucko.commodore.CommodoreProvider;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.Command;
public class CommodoreHandler extends BukkitBasicCommandHandler implements ICommandHandler {
@ -37,10 +37,10 @@ public class CommodoreHandler extends BukkitBasicCommandHandler implements IComm
}
@Override
protected void registerPluginCommand(PluginCommand pluginCommand, GameCommand gameCommand) {
super.registerPluginCommand(pluginCommand, gameCommand);
protected void registerPluginCommand(Command command, GameCommand gameCommand) {
super.registerPluginCommand(command, gameCommand);
LiteralCommandNode<?> commandNode = BrigadierUtil.convertToBrigadier(gameCommand, null);
commodore.register(pluginCommand, commandNode);
commodore.register(command, commandNode);
}
}

View File

@ -549,7 +549,6 @@ public abstract class AbstractDiscordSRV<
eventBus().publish(new DiscordSRVConnectedEvent());
if (beenReady.compareAndSet(false, true)) {
eventBus.publish(new DiscordSRVReadyEvent());
runReload(Collections.singleton(ReloadFlag.DISCORD_COMMANDS));
}
}
}
@ -907,8 +906,7 @@ public abstract class AbstractDiscordSRV<
}
if (flags.contains(ReloadFlag.DISCORD_COMMANDS) && isReady()) {
discordAPI().commandRegistry().registerCommandsFromEvent();
discordAPI().commandRegistry().registerCommandsToDiscord();
discordAPI().commandRegistry().reloadCommands();
}
if (!initial) {

View File

@ -30,18 +30,25 @@ import com.discordsrv.common.core.paste.Paste;
import com.discordsrv.common.core.paste.PasteService;
import com.discordsrv.common.core.paste.service.AESEncryptedPasteService;
import com.discordsrv.common.core.paste.service.BytebinPasteService;
import com.discordsrv.common.feature.debug.DebugObservabilityEvent;
import com.discordsrv.common.feature.debug.DebugReport;
import com.discordsrv.common.permission.game.Permission;
import com.discordsrv.common.util.ExceptionUtil;
import net.kyori.adventure.text.format.NamedTextColor;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Arrays;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.stream.Collectors;
public class DebugCommand extends CombinedCommand {
private static final List<String> SUBCOMMANDS = Arrays.asList("start", "stop", "upload", "zip");
private static DebugCommand INSTANCE;
private static GameCommand GAME;
private static DiscordCommand DISCORD;
@ -57,10 +64,12 @@ public class DebugCommand extends CombinedCommand {
.requiredPermission(Permission.COMMAND_DEBUG)
.executor(command)
.then(
GameCommand.stringWord("format")
GameCommand.stringWord("subcommand")
.suggester((sender, previousArguments, currentInput) ->
"zip".startsWith(currentInput.toLowerCase(Locale.ROOT))
? Collections.singletonList("zip") : Collections.emptyList())
SUBCOMMANDS.stream()
.filter(cmd -> cmd.startsWith(currentInput.toLowerCase(Locale.ROOT)))
.collect(Collectors.toList())
)
.executor(command)
);
}
@ -71,13 +80,17 @@ public class DebugCommand extends CombinedCommand {
public static DiscordCommand getDiscord(DiscordSRV discordSRV) {
if (DISCORD == null) {
DebugCommand command = getInstance(discordSRV);
CommandOption.Builder optionBuilder = CommandOption.builder(
CommandOption.Type.STRING,
"subcommand",
String.join("/", SUBCOMMANDS)
).setRequired(false);
for (String subCommand : SUBCOMMANDS) {
optionBuilder = optionBuilder.addChoice(subCommand, subCommand);
}
DISCORD = DiscordCommand.chatInput(ComponentIdentifier.of("DiscordSRV", "debug"), "debug", "Create a debug report")
.addOption(
CommandOption.builder(CommandOption.Type.STRING, "format", "The format to generate the debug report")
.addChoice(".zip", "zip")
.setRequired(false)
.build()
)
.addOption(optionBuilder.build())
.setEventHandler(command)
.build();
}
@ -89,6 +102,7 @@ public class DebugCommand extends CombinedCommand {
public static final Base64.Encoder KEY_ENCODER = Base64.getUrlEncoder().withoutPadding();
private final PasteService pasteService;
private final AtomicBoolean debugObserving = new AtomicBoolean(false);
public DebugCommand(DiscordSRV discordSRV) {
super(discordSRV);
@ -97,37 +111,59 @@ public class DebugCommand extends CombinedCommand {
@Override
public void execute(CommandExecution execution) {
boolean usePaste = !"zip".equals(execution.getArgument("format"));
String argument = execution.getArgument("subcommand");
String subCommand = argument != null ? argument.toLowerCase(Locale.ROOT) : null;
if (subCommand != null && !SUBCOMMANDS.contains(subCommand)) {
execution.send(new Text("Unknown subcommand").withGameColor(NamedTextColor.RED));
return;
}
execution.runAsync(() -> {
DebugReport report = new DebugReport(discordSRV);
report.generate();
Throwable pasteError = usePaste ? paste(execution, report) : null;
if (usePaste && pasteError == null) {
// Success
return;
}
Throwable zipError = zip(execution, report);
if (zipError == null) {
// Success
if (usePaste) {
discordSRV.logger().warning("Failed to upload debug, zip generation succeeded", pasteError);
if ("start".equals(subCommand)) {
if (!debugObserving.compareAndSet(false, true)) {
execution.send(new Text("Already debugging").withGameColor(NamedTextColor.RED));
return;
}
discordSRV.eventBus().publish(new DebugObservabilityEvent(true));
execution.send(new Text("Debugging started").withGameColor(NamedTextColor.GREEN));
return;
}
if (pasteError != null) {
zipError.addSuppressed(pasteError);
boolean useUpload = subCommand == null || "upload".equals(subCommand);
boolean useZip = subCommand == null || "zip".equals(subCommand);
if (useUpload || useZip) {
DebugReport report = new DebugReport(discordSRV);
report.generate();
Throwable pasteError = useUpload ? paste(execution, report) : null;
if (useUpload && pasteError == null) {
useZip = false;
}
Throwable zipError = useZip ? zip(execution, report) : null;
if (pasteError != null || zipError != null) {
// Failed
RuntimeException exception = ExceptionUtil.minifyException(new RuntimeException("Failed to save debug"));
if (pasteError != null) {
exception.addSuppressed(pasteError);
}
if (zipError != null) {
exception.addSuppressed(zipError);
}
discordSRV.logger().error("Failed to save debug", exception);
execution.send(new Text("Failed to save debug").withGameColor(NamedTextColor.DARK_RED));
return;
}
}
if (debugObserving.compareAndSet(true, false)) {
discordSRV.eventBus().publish(new DebugObservabilityEvent(true));
execution.send(new Text("Debugging stopped").withGameColor(NamedTextColor.GREEN));
} else if ("stop".equals(subCommand)) {
execution.send(new Text("Not debugging").withGameColor(NamedTextColor.RED));
}
discordSRV.logger().error(usePaste ? "Failed to upload & zip debug" : "Failed to zip debug", zipError);
execution.send(
new Text(usePaste
? "Failed to upload debug report to paste & failed to generate zip"
: "Failed to create debug zip"
).withGameColor(NamedTextColor.DARK_RED)
);
});
}

View File

@ -21,7 +21,9 @@ package com.discordsrv.common.discord.api;
import com.discordsrv.api.discord.entity.JDAEntity;
import com.discordsrv.api.discord.entity.interaction.command.CommandType;
import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand;
import com.discordsrv.api.eventbus.Subscribe;
import com.discordsrv.api.events.discord.interaction.command.CommandRegisterEvent;
import com.discordsrv.api.events.lifecycle.DiscordSRVReadyEvent;
import com.discordsrv.common.DiscordSRV;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.entities.Guild;
@ -44,9 +46,20 @@ public class DiscordCommandRegistry {
public DiscordCommandRegistry(DiscordSRV discordSRV) {
this.discordSRV = discordSRV;
discordSRV.eventBus().subscribe(this);
}
public void registerCommandsFromEvent() {
@Subscribe
public void onDiscordSRVReady(DiscordSRVReadyEvent event) {
reloadCommands();
}
public void reloadCommands() {
registerCommandsFromEvent();
registerCommandsToDiscord();
}
private void registerCommandsFromEvent() {
CommandRegisterEvent event = new CommandRegisterEvent();
discordSRV.eventBus().publish(event);
@ -100,7 +113,7 @@ public class DiscordCommandRegistry {
return registry.getActive(name);
}
public void registerCommandsToDiscord() {
private void registerCommandsToDiscord() {
JDA jda = discordSRV.jda();
if (jda == null) {
return;

View File

@ -28,7 +28,7 @@ public final class ExceptionUtil {
* @param throwable the throwable
* @return the same throwable with the stacktrace removed
*/
public static Throwable minifyException(Throwable throwable) {
public static <T extends Throwable> T minifyException(T throwable) {
throwable.setStackTrace(new StackTraceElement[0]);
return throwable;
}