|
| 1 | +package org.togetherjava.tjbot.commands.system; |
| 2 | + |
| 3 | +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; |
| 4 | +import net.dv8tion.jda.api.interactions.commands.OptionType; |
| 5 | +import net.dv8tion.jda.api.interactions.commands.build.OptionData; |
| 6 | +import org.apache.logging.log4j.Level; |
| 7 | +import org.apache.logging.log4j.LogManager; |
| 8 | +import org.apache.logging.log4j.core.config.Configurator; |
| 9 | +import org.jetbrains.annotations.NotNull; |
| 10 | +import org.togetherjava.tjbot.commands.SlashCommandAdapter; |
| 11 | +import org.togetherjava.tjbot.commands.SlashCommandVisibility; |
| 12 | + |
| 13 | +import java.util.stream.Stream; |
| 14 | + |
| 15 | +/** |
| 16 | + * Implements the '/set-log-level' command which can be used to change the log level used by the |
| 17 | + * bot, while it is running. |
| 18 | + * <p> |
| 19 | + * Example usage: |
| 20 | + * |
| 21 | + * <pre> |
| 22 | + * {@code |
| 23 | + * /set-log-level level: INFO |
| 24 | + * } |
| 25 | + * </pre> |
| 26 | + */ |
| 27 | +public final class LogLevelCommand extends SlashCommandAdapter { |
| 28 | + private static final String LOG_LEVEL_OPTION = "level"; |
| 29 | + |
| 30 | + /** |
| 31 | + * Creates a new instance. |
| 32 | + */ |
| 33 | + public LogLevelCommand() { |
| 34 | + super("set-log-level", "Changes the log level of the bot while it is running.", |
| 35 | + SlashCommandVisibility.GUILD); |
| 36 | + |
| 37 | + OptionData option = |
| 38 | + new OptionData(OptionType.STRING, LOG_LEVEL_OPTION, "the log level to set", true); |
| 39 | + Stream.of(Level.values()).map(Level::name).forEach(level -> option.addChoice(level, level)); |
| 40 | + |
| 41 | + getData().addOptions(option); |
| 42 | + } |
| 43 | + |
| 44 | + // Security warning about changing log configs. We only change the level, that is safe. |
| 45 | + @SuppressWarnings("squid:S4792") |
| 46 | + @Override |
| 47 | + public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { |
| 48 | + String levelText = event.getOption(LOG_LEVEL_OPTION).getAsString(); |
| 49 | + Level level = Level.getLevel(levelText); |
| 50 | + |
| 51 | + if (level == null) { |
| 52 | + event.reply("The selected log level '%s' is unknown.".formatted(levelText)) |
| 53 | + .setEphemeral(true) |
| 54 | + .queue(); |
| 55 | + return; |
| 56 | + } |
| 57 | + |
| 58 | + Configurator.setAllLevels(LogManager.getRootLogger().getName(), level); |
| 59 | + event.reply("Set the log level to '%s'.".formatted(levelText)).queue(); |
| 60 | + } |
| 61 | +} |
0 commit comments