diff --git a/.gitignore b/.gitignore index 0ce9cdb2ce..563dbf8375 100644 --- a/.gitignore +++ b/.gitignore @@ -158,3 +158,6 @@ logviewer/types.d.ts logviewer/pnpm-lock.yaml logviewer/webpack.config.js logviewer/webpack.generated.js + +### Mac Patch ### +.DS_Store diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java index ed1d4ab8bc..568ef4b3aa 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -3,6 +3,7 @@ import org.jetbrains.annotations.NotNull; import org.togetherjava.tjbot.commands.basic.DatabaseCommand; import org.togetherjava.tjbot.commands.basic.PingCommand; +import org.togetherjava.tjbot.commands.moderation.*; import org.togetherjava.tjbot.commands.basic.VcActivityCommand; import org.togetherjava.tjbot.commands.mathcommands.TeXCommand; import org.togetherjava.tjbot.commands.tags.TagCommand; @@ -42,6 +43,7 @@ public enum Commands { // available. return List.of(new PingCommand(), new DatabaseCommand(database), new TeXCommand(), new TagCommand(tagSystem), new TagManageCommand(tagSystem), - new TagsCommand(tagSystem), new VcActivityCommand()); + new TagsCommand(tagSystem), new BanCommand(), new UnbanCommand(), new KickCommand(), + new VcActivityCommand()); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java new file mode 100644 index 0000000000..e3776ea3c6 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -0,0 +1,143 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.commands.OptionMapping; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; + +import java.util.Objects; + +/** + * This command can ban users and optionally remove their messages from the past days. Banning can + * also be paired with a ban reason. The command will also try to DM the user to inform them about + * the action and the reason. + *

+ * The command fails if the user triggering it is lacking permissions to either ban other users or + * to ban the specific given user (for example a moderator attempting to ban an admin). + */ +public final class BanCommand extends SlashCommandAdapter { + private static final String USER_OPTION = "user"; + private static final String DELETE_HISTORY_OPTION = "delete-history"; + private static final String REASON_OPTION = "reason"; + private static final Logger logger = LoggerFactory.getLogger(BanCommand.class); + + /** + * Constructs an instance. + */ + public BanCommand() { + super("ban", "Bans the given user from the server", SlashCommandVisibility.GUILD); + + getData().addOption(OptionType.USER, USER_OPTION, "The user who you want to ban", true) + .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be banned", true) + .addOptions(new OptionData(OptionType.INTEGER, DELETE_HISTORY_OPTION, + "the amount of days of the message history to delete, none means no messages are deleted.", + true).addChoice("none", 0).addChoice("recent", 1).addChoice("all", 7)); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + OptionMapping userOption = + Objects.requireNonNull(event.getOption(USER_OPTION), "The target is null"); + Member target = userOption.getAsMember(); + Member author = Objects.requireNonNull(event.getMember(), "The author is null"); + + String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") + .getAsString(); + + Guild guild = Objects.requireNonNull(event.getGuild()); + Member bot = guild.getSelfMember(); + + // Member doesn't exist if attempting to ban a user who is not part of the guild. + if (target != null && !handleCanInteractWithTarget(target, bot, author, event)) { + return; + } + + if (!handleHasPermissions(author, bot, event, guild)) { + return; + } + + int deleteHistoryDays = Math + .toIntExact(Objects.requireNonNull(event.getOption(DELETE_HISTORY_OPTION)).getAsLong()); + + if (!ModerationUtils.handleReason(reason, event)) { + return; + } + + banUser(userOption.getAsUser(), author, reason, deleteHistoryDays, guild, event); + } + + private static void banUser(@NotNull User target, @NotNull Member author, + @NotNull String reason, int deleteHistoryDays, @NotNull Guild guild, + @NotNull SlashCommandEvent event) { + event.getJDA() + .openPrivateChannelById(target.getIdLong()) + .flatMap(channel -> channel.sendMessage( + """ + Hey there, sorry to tell you but unfortunately you have been banned from the server %s. + If you think this was a mistake, please contact a moderator or admin of the server. + The reason for the ban is: %s + """ + .formatted(guild.getName(), reason))) + .mapToResult() + .flatMap(result -> guild.ban(target, deleteHistoryDays, reason)) + .flatMap(v -> event.reply(target.getAsTag() + " was banned by " + + author.getUser().getAsTag() + " for: " + reason)) + .queue(); + + logger.info( + " '{} ({})' banned the user '{} ({})' and deleted their message history of the last '{}' days. Reason being'{}'", + author.getUser().getAsTag(), author.getIdLong(), target.getAsTag(), + target.getIdLong(), deleteHistoryDays, reason); + } + + private static boolean handleCanInteractWithTarget(@NotNull Member target, @NotNull Member bot, + @NotNull Member author, @NotNull SlashCommandEvent event) { + String targetTag = target.getUser().getAsTag(); + if (!author.canInteract(target)) { + event.reply("The user " + targetTag + " is too powerful for you to ban.") + .setEphemeral(true) + .queue(); + return false; + } + + if (!bot.canInteract(target)) { + event.reply("The user " + targetTag + " is too powerful for me to ban.") + .setEphemeral(true) + .queue(); + return false; + } + return true; + } + + private static boolean handleHasPermissions(@NotNull Member author, @NotNull Member bot, + @NotNull SlashCommandEvent event, @NotNull Guild guild) { + if (!author.hasPermission(Permission.BAN_MEMBERS)) { + event.reply( + "You can not ban users in this guild since you do not have the BAN_MEMBERS permission.") + .setEphemeral(true) + .queue(); + return false; + } + + if (!bot.hasPermission(Permission.BAN_MEMBERS)) { + event.reply( + "I can not ban users in this guild since I do not have the BAN_MEMBERS permission.") + .setEphemeral(true) + .queue(); + + logger.error("The bot does not have BAN_MEMBERS permission on the server '{}' ", + guild.getName()); + return false; + } + return true; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java new file mode 100644 index 0000000000..d887bb8472 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java @@ -0,0 +1,116 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.commands.OptionMapping; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import java.util.Objects; + + +/** + * This command can kicks users. Kicking can also be paired with a kick reason. The command will + * also try to DM the user to inform them about the action and the reason. + *

+ * The command fails if the user triggering it is lacking permissions to either kick other users or + * to kick the specific given user (for example a moderator attempting to kick an admin). + * + */ +public final class KickCommand extends SlashCommandAdapter { + private static final Logger logger = LoggerFactory.getLogger(KickCommand.class); + private static final String USER_OPTION = "user"; + private static final String REASON_OPTION = "reason"; + + /** + * Constructs an instance. + */ + public KickCommand() { + super("kick", "Kicks the given user from the server", SlashCommandVisibility.GUILD); + + getData().addOption(OptionType.USER, USER_OPTION, "The user who you want to kick", true) + .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be kicked", true); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + OptionMapping userOption = + Objects.requireNonNull(event.getOption(USER_OPTION), "The target is null"); + Member target = userOption.getAsMember(); + Member author = Objects.requireNonNull(event.getMember(), "The author is null"); + + String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") + .getAsString(); + + + Guild guild = event.getGuild(); + Member bot = guild.getSelfMember(); + + if (!author.hasPermission(Permission.KICK_MEMBERS)) { + event.reply( + "You can not kick users in this guild since you do not have the KICK_MEMBERS permission.") + .setEphemeral(true) + .queue(); + return; + } + + String userTag = userOption.getAsUser().getAsTag(); + if (!author.canInteract(target)) { + event.reply("The user " + userTag + " is too powerful for you to kick.") + .setEphemeral(true) + .queue(); + return; + } + + if (!bot.hasPermission(Permission.KICK_MEMBERS)) { + event.reply( + "I can not kick users in this guild since I do not have the KICK_MEMBERS permission.") + .setEphemeral(true) + .queue(); + + logger.error("The bot does not have KICK_MEMBERS permission on the server '{}' ", + event.getGuild().getName()); + return; + } + + if (!bot.canInteract(target)) { + event.reply("The user " + userTag + " is too powerful for me to kick.") + .setEphemeral(true) + .queue(); + return; + } + + if (!ModerationUtils.handleReason(reason, event)) { + return; + } + + kickUser(target, author, reason, guild, event); + } + + private static void kickUser(@NotNull Member target, @NotNull Member author, + @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { + event.getJDA() + .openPrivateChannelById(target.getUser().getId()) + .flatMap(channel -> channel.sendMessage( + """ + Hey there, sorry to tell you but unfortunately you have been kicked from the server %s. + If you think this was a mistake, please contact a moderator or admin of the server. + The reason for the kick is: %s + """ + .formatted(guild.getName(), reason))) + .mapToResult() + .flatMap(result -> guild.kick(target, reason).reason(reason)) + .flatMap(v -> event.reply(target.getUser().getAsTag() + " was kicked by " + + author.getUser().getAsTag() + " for: " + reason)) + .queue(); + + logger.info(" '{} ({})' kicked the user '{} ({})' due to reason being '{}'", + author.getUser().getAsTag(), author.getIdLong(), target.getUser().getAsTag(), + target.getUser().getId(), reason); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java new file mode 100644 index 0000000000..d35963b9b3 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -0,0 +1,42 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import org.jetbrains.annotations.NotNull; + +/** + * Utility class offering helpers revolving around user moderation, such as banning or kicking. + */ +public enum ModerationUtils { + ; + + /** + * As stated in {@link Guild#ban(User, int, String)}
+ * The reason can be only 512 characters. + */ + private static final int REASON_MAX_LENGTH = 512; + + /** + * This boolean checks if the reason that the user has entered violates the max character length + * or not.
+ * If it does the bot will tell the user they have violated the mex character length and will + * terminate the command
+ * If it does bot the bot will be allowed to continue running the command. + * + * @param reason the reason of the action such as banning. + * @param event This is used to be able to use slash command actions such as event.reply(); + * @throws IllegalArgumentException if the reason is over 512 characters. + * + */ + public static boolean handleReason(@NotNull String reason, @NotNull SlashCommandEvent event) { + if (reason.length() <= REASON_MAX_LENGTH) { + return true; + } + + event.reply("The reason can not be over " + REASON_MAX_LENGTH + " characters") + .setEphemeral(true) + .queue(); + return false; + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java new file mode 100644 index 0000000000..c11e6474c0 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnbanCommand.java @@ -0,0 +1,100 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.Permission; +import net.dv8tion.jda.api.entities.Member; +import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.exceptions.ErrorResponseException; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.requests.ErrorResponse; +import org.jetbrains.annotations.NotNull; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; + +import java.util.Objects; + +/** + * This command allows you to unban a user. The unban command requires the user to input the user + * who is subject to get unbanned. Unbanning can also be paired with a reason for unbanning the + * user. The command fails if the user is currently not banned already. + */ +public final class UnbanCommand extends SlashCommandAdapter { + private static final Logger logger = LoggerFactory.getLogger(UnbanCommand.class); + private static final String USER_OPTION = "user"; + private static final String REASON_OPTION = "reason"; + + /** + * Constructs an instance. + */ + public UnbanCommand() { + super("unban", "Unbans a given user", SlashCommandVisibility.GUILD); + + getData().addOption(OptionType.USER, USER_OPTION, "The user who you want to unban", true) + .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be unbanned", true); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + User target = Objects.requireNonNull(event.getOption(USER_OPTION), "The user is null") + .getAsUser(); + Member author = Objects.requireNonNull(event.getMember(), "The author is null"); + + if (!author.hasPermission(Permission.BAN_MEMBERS)) { + event.reply( + "You can not unban users in this guild since you do not have the BAN_MEMBERS permission.") + .setEphemeral(true) + .queue(); + return; + } + + Member bot = Objects.requireNonNull(event.getGuild(), "The guild is null").getSelfMember(); + if (!bot.hasPermission(Permission.BAN_MEMBERS)) { + event.reply( + "I can not unban users in this guild since I do not have the BAN_MEMBERS permission.") + .setEphemeral(true) + .queue(); + + logger.error("The bot does not have BAN_MEMBERS permission on the server '{}' ", + event.getGuild().getName()); + return; + } + + String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") + .getAsString(); + + if (!ModerationUtils.handleReason(reason, event)) { + return; + } + + unban(target, reason, author, event); + } + + private static void unban(@NotNull User target, @NotNull String reason, @NotNull Member author, + @NotNull SlashCommandEvent event) { + event.getGuild().unban(target).reason(reason).queue(v -> { + event + .reply("The user " + author.getUser().getAsTag() + " unbanned the user " + + target.getAsTag() + " for: " + reason) + .queue(); + + logger.info(" {} ({}) unbanned the user '{}' for: '{}'", author.getUser().getAsTag(), + author.getIdLong(), target.getAsTag(), reason); + }, throwable -> { + if (throwable instanceof ErrorResponseException errorResponseException + && errorResponseException.getErrorResponse() == ErrorResponse.UNKNOWN_USER) { + + event.reply("The specified user doesn't exist").setEphemeral(true).queue(); + + logger.debug("I could not unban the user '{}' because they do not exist", + target.getAsTag()); + } else { + event.reply("Sorry, but something went wrong.").setEphemeral(true).queue(); + + logger.warn("Something went wrong during the process of unbanning the user ", + throwable); + } + }); + } +} diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/package-info.java new file mode 100644 index 0000000000..399fc1fa1f --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/package-info.java @@ -0,0 +1,5 @@ +/** + * This package offers all the moderation commands from the application such as banning and kicking + * users. + */ +package org.togetherjava.tjbot.commands.moderation;