From fd439d93e79d747a8155ea2eb41b47ab0ed1248c Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 5 Nov 2021 20:57:33 +0000 Subject: [PATCH 01/50] Started work --- .../tjbot/moderation/WarnCommand.java | 43 +++++++++++++++++++ 1 file changed, 43 insertions(+) create mode 100644 application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java diff --git a/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java new file mode 100644 index 0000000000..faddfe0218 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java @@ -0,0 +1,43 @@ +package org.togetherjava.tjbot.moderation; + +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; +import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.db.Database; + +public class WarnCommand extends SlashCommandAdapter { + private static final String WARN_USER = "warn_user"; + private static final String WARN_USER_OPTION = "user"; + private static final String WARN_REASON_OPTION = "reason"; + private static final String RETRIEVE_WARNS_OPTION = "retrieve_warns"; + private static final String RETRIEVE_USER_OPTION = "user"; + private final Database database; + + /** + * Creates a new adapter with the given data. + * + *@param database the database to store the key-value pairs in + */ + public WarnCommand(@NotNull Database database) { + super("warn", "warns the user", SlashCommandVisibility.GUILD); + this.database = database; + + getData().addSubcommands( + new SubcommandData(WARN_USER, + "Used to warn the user").addOption( + OptionType.USER, WARN_USER_OPTION, "The user to warn", + true) + .addOption(OptionType.STRING, WARN_REASON_OPTION, "The reason for the warning", + true), + new SubcommandData(RETRIEVE_WARNS_OPTION, "Uses to retrieve a warn for a member") + .addOption(OptionType.USER, RETRIEVE_USER_OPTION, + "The warns for the user you want", true)); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + } +} From f1279643e7deb13630bf72faeb8b6dfff40ed68e Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 5 Nov 2021 21:13:04 +0000 Subject: [PATCH 02/50] Working on it --- .../tjbot/moderation/WarnCommand.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java index faddfe0218..b8cab94182 100644 --- a/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java @@ -1,6 +1,8 @@ package org.togetherjava.tjbot.moderation; +import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.commands.CommandInteraction; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import org.jetbrains.annotations.NotNull; @@ -8,6 +10,8 @@ import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.db.Database; +import java.util.Objects; + public class WarnCommand extends SlashCommandAdapter { private static final String WARN_USER = "warn_user"; private static final String WARN_USER_OPTION = "user"; @@ -39,5 +43,18 @@ public WarnCommand(@NotNull Database database) { @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { + switch (Objects.requireNonNull(event.getSubcommandName())) { + case WARN_USER -> handleWarnCommand(event); + case RETRIEVE_WARNS_OPTION -> handleRetrieveWarnCommand(event); + default -> throw new AssertionError(); + } + } + + private void handleWarnCommand(@NotNull CommandInteraction event) { + User user = Objects.requireNonNull(event.getOption(WARN_USER_OPTION)).getAsUser(); + } + + private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { + } } From 43a477dbbb3720456d120ad26102c61c6ff56943 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 5 Nov 2021 21:33:47 +0000 Subject: [PATCH 03/50] Update WarnCommand.java --- .../tjbot/moderation/WarnCommand.java | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java index b8cab94182..51034cd514 100644 --- a/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.moderation; +import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.commands.CommandInteraction; @@ -9,6 +10,8 @@ import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.Storage; +import org.togetherjava.tjbot.db.generated.tables.records.StorageRecord; import java.util.Objects; @@ -51,7 +54,19 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { } private void handleWarnCommand(@NotNull CommandInteraction event) { - User user = Objects.requireNonNull(event.getOption(WARN_USER_OPTION)).getAsUser(); + // To prevent people from using warn content, only users with + // elevated permissions are allowed to use this command + if (!Objects.requireNonNull(event.getMember()).hasPermission(Permission.KICK_MEMBERS)) { + event.reply("You need the MESSAGE_MANAGE permission to use this command") + .setEphemeral(true) + .queue(); + return; + } + + // /warn warn_user @Zabuzard who knows + User target = Objects.requireNonNull(event.getOption(WARN_USER_OPTION)).getAsUser(); + String reason = Objects.requireNonNull(event.getOption(WARN_REASON_OPTION)).getAsString(); + } private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { From 5d83e6e05d9235596ed72cfbed58a3d2b4ff90b0 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 12:53:42 +0000 Subject: [PATCH 04/50] added the sql --- .../moderation/WarnCommand.java | 45 ++++++++++++------- .../main/resources/db/V2_Add_Warn_System.sql | 6 +++ 2 files changed, 35 insertions(+), 16 deletions(-) rename application/src/main/java/org/togetherjava/tjbot/{ => commands}/moderation/WarnCommand.java (62%) create mode 100644 application/src/main/resources/db/V2_Add_Warn_System.sql diff --git a/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java similarity index 62% rename from application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java rename to application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 51034cd514..7b14b71a0f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -1,4 +1,4 @@ -package org.togetherjava.tjbot.moderation; +package org.togetherjava.tjbot.commands.moderation; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.User; @@ -7,15 +7,16 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; 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 org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.db.generated.tables.Storage; -import org.togetherjava.tjbot.db.generated.tables.records.StorageRecord; import java.util.Objects; public class WarnCommand extends SlashCommandAdapter { + private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); private static final String WARN_USER = "warn_user"; private static final String WARN_USER_OPTION = "user"; private static final String WARN_REASON_OPTION = "reason"; @@ -26,22 +27,18 @@ public class WarnCommand extends SlashCommandAdapter { /** * Creates a new adapter with the given data. * - *@param database the database to store the key-value pairs in + * @param database the database to store the key-value pairs in */ public WarnCommand(@NotNull Database database) { super("warn", "warns the user", SlashCommandVisibility.GUILD); this.database = database; - getData().addSubcommands( - new SubcommandData(WARN_USER, - "Used to warn the user").addOption( - OptionType.USER, WARN_USER_OPTION, "The user to warn", - true) - .addOption(OptionType.STRING, WARN_REASON_OPTION, "The reason for the warning", - true), + getData().addSubcommands(new SubcommandData(WARN_USER, "Used to warn the user") + .addOption(OptionType.USER, WARN_USER_OPTION, "The user to warn", true) + .addOption(OptionType.STRING, WARN_REASON_OPTION, "The reason for the warning", true), new SubcommandData(RETRIEVE_WARNS_OPTION, "Uses to retrieve a warn for a member") - .addOption(OptionType.USER, RETRIEVE_USER_OPTION, - "The warns for the user you want", true)); + .addOption(OptionType.USER, RETRIEVE_USER_OPTION, + "The warns for the user you want", true)); } @Override @@ -56,17 +53,33 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { private void handleWarnCommand(@NotNull CommandInteraction event) { // To prevent people from using warn content, only users with // elevated permissions are allowed to use this command - if (!Objects.requireNonNull(event.getMember()).hasPermission(Permission.KICK_MEMBERS)) { + if (!Objects.requireNonNull(event.getMember()).hasPermission(Permission.BAN_MEMBERS)) { event.reply("You need the MESSAGE_MANAGE permission to use this command") - .setEphemeral(true) - .queue(); + .setEphemeral(true) + .queue(); return; } + if (!Objects.requireNonNull(event.getMember()).hasPermission(Permission.BAN_MEMBERS)) { + event.reply("You need the MESSAGE_MANAGE permission to use this command") + .setEphemeral(true) + .queue(); + return; + } + + // /warn warn_user @Zabuzard who knows User target = Objects.requireNonNull(event.getOption(WARN_USER_OPTION)).getAsUser(); String reason = Objects.requireNonNull(event.getOption(WARN_REASON_OPTION)).getAsString(); + + /* + * try { database.write(context -> { WarnsRecord warnRecord = + * context.newRecord(Warns.STORAGE).setKey(key).setValue(value); if (warnRecord.update() == + * 0) { warnRecord.insert(); } }); } catch (DatabaseException e) { + * logger.error("Failed to put message", e); + * event.reply("Sorry, something went wrong.").setEphemeral(true).queue(); } + */ } private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { diff --git a/application/src/main/resources/db/V2_Add_Warn_System.sql b/application/src/main/resources/db/V2_Add_Warn_System.sql new file mode 100644 index 0000000000..413080b1c4 --- /dev/null +++ b/application/src/main/resources/db/V2_Add_Warn_System.sql @@ -0,0 +1,6 @@ +CREATE TABLE warns +( + userid TEXT NOT NULL PRIMARY KEY, + guildid TEXT NOT NULL, + times TEXT NOT NULL +) \ No newline at end of file From 0d35061e039ef290981a7b4e857991d2f519a5ec Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 14:07:52 +0000 Subject: [PATCH 05/50] save --- .../commands/moderation/WarnCommand.java | 144 +++++++++++++++--- .../main/resources/db/V2_Add_Warn_System.sql | 6 +- 2 files changed, 128 insertions(+), 22 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 7b14b71a0f..4cbc24d8fb 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -1,9 +1,14 @@ package org.togetherjava.tjbot.commands.moderation; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.JDA; 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.CommandInteraction; +import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; import org.jetbrains.annotations.NotNull; @@ -12,8 +17,13 @@ import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.DatabaseException; +import org.togetherjava.tjbot.db.generated.tables.Warns; +import org.togetherjava.tjbot.db.generated.tables.records.WarnsRecord; +import java.awt.*; import java.util.Objects; +import java.util.Optional; public class WarnCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); @@ -50,39 +60,135 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { } } - private void handleWarnCommand(@NotNull CommandInteraction event) { - // To prevent people from using warn content, only users with + /** + * Handles {@code /warn retrieve_warns user} commands. Retrieves the timesWarned value and then + * sends that value to the user as an embed + * + * @param event the event of the command + */ + private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { + OptionMapping userOption = + Objects.requireNonNull(event.getOption(RETRIEVE_USER_OPTION), "The target is null"); + + Member author = userOption.getAsMember(); + + // To prevent people from get users warn, only users with // elevated permissions are allowed to use this command - if (!Objects.requireNonNull(event.getMember()).hasPermission(Permission.BAN_MEMBERS)) { - event.reply("You need the MESSAGE_MANAGE permission to use this command") - .setEphemeral(true) - .queue(); + if (handleHasPermissions(author, event, event.getGuild()).equals(false)) { return; } - if (!Objects.requireNonNull(event.getMember()).hasPermission(Permission.BAN_MEMBERS)) { - event.reply("You need the MESSAGE_MANAGE permission to use this command") - .setEphemeral(true) + User target = userOption.getAsUser(); + + try { + Optional value = database.read(context -> { + try (var select = context.selectFrom(Warns.WARNS)) { + return Optional + .ofNullable(select.where(Warns.WARNS.USERID.eq(target.getId())).fetchOne()) + .map(WarnsRecord::getTimes); + } + }); + + if (value.isEmpty()) { + event + .replyEmbeds(new EmbedBuilder().setTitle("404 Error") + .setDescription( + "No warns can be found for the user " + target.getAsTag() + ".") + .setColor(Color.magenta) + .build()) + .queue(); + return; + } + + event + .replyEmbeds(new EmbedBuilder() + .setAuthor("This command was created by " + author.getEffectiveName(), null, + author.getEffectiveAvatarUrl()) + .setTitle("The User " + target.getAsTag() + " warns") + .setDescription("They have " + value.orElseThrow() + " number of warns") + .setColor(Color.magenta) + .build()) .queue(); - return; + } catch (DatabaseException e) { + logger.error("Failed to get the number of warns ", e); + event.reply("Sorry, something went wrong.").setEphemeral(true).queue(); } + } + /** + * Handles {@code /warn warn_user user reason} command. Saves the value under the given user, + * given guild and add +1 to the number of warns the user has. + *

+ * This command can only be used by users with the {@code BAN_MEMBERS} permission. + * + * @param event the event of the command + */ + private void handleWarnCommand(@NotNull CommandInteraction event) { + OptionMapping userOption = + Objects.requireNonNull(event.getOption(WARN_USER_OPTION), "The target is null"); + + Member author = userOption.getAsMember(); + Guild guild = Objects.requireNonNull(event.getGuild()); + + // To prevent people from using warn content, only users with + // elevated permissions are allowed to use this command + if (handleHasPermissions(author, event, guild).equals(false)) { + return; + } // /warn warn_user @Zabuzard who knows - User target = Objects.requireNonNull(event.getOption(WARN_USER_OPTION)).getAsUser(); + User target = userOption.getAsUser(); String reason = Objects.requireNonNull(event.getOption(WARN_REASON_OPTION)).getAsString(); + // TODO double check this part + int times = +1; + String userId = target.getId(); + dmUser(event.getJDA(), userId, reason, guild); - /* - * try { database.write(context -> { WarnsRecord warnRecord = - * context.newRecord(Warns.STORAGE).setKey(key).setValue(value); if (warnRecord.update() == - * 0) { warnRecord.insert(); } }); } catch (DatabaseException e) { - * logger.error("Failed to put message", e); - * event.reply("Sorry, something went wrong.").setEphemeral(true).queue(); } - */ + try { + database.write(context -> { + WarnsRecord warnRecord = context.newRecord(Warns.WARNS) + .setUserid(userId) + .setGuildid(guild.getId()) + .setTimes(Integer.toString(times)); + logger.info("The user '{}' ({}) warned the user '{}' ({}) for the reason '{}'", + author.getUser().getAsTag(), author.getId(), target.getAsTag(), + target.getId(), reason); + if (warnRecord.update() == 0) { + warnRecord.insert(); + } + }); + } catch (DatabaseException e) { + logger.error("Failed to put message", e); + event.reply("Sorry, something went wrong.").setEphemeral(true).queue(); + } } - private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { + private static void dmUser(JDA jda, String userId, String reason, Guild guild) { + jda.openPrivateChannelById(userId) + .flatMap(channel -> channel.sendMessage( + """ + Hey there, sorry to tell you but unfortunately you have been warned by the server %s. + The reason for the warn is: %s + """ + .formatted(guild.getName(), reason))) + .queue(); + } + private static Boolean handleHasPermissions(Member author, CommandInteraction event, + Guild guild) { + if (!author.hasPermission(Permission.BAN_MEMBERS)) { + event.reply("You need the MESSAGE_MANAGE permission to use this command") + .setEphemeral(true) + .queue(); + return false; + } + if (!guild.getSelfMember().hasPermission(Permission.BAN_MEMBERS)) { + event.reply("You need the MESSAGE_MANAGE permission to use this command") + .setEphemeral(true) + .queue(); + return false; + } + return true; } } diff --git a/application/src/main/resources/db/V2_Add_Warn_System.sql b/application/src/main/resources/db/V2_Add_Warn_System.sql index 413080b1c4..d696ae80cc 100644 --- a/application/src/main/resources/db/V2_Add_Warn_System.sql +++ b/application/src/main/resources/db/V2_Add_Warn_System.sql @@ -1,6 +1,6 @@ CREATE TABLE warns ( - userid TEXT NOT NULL PRIMARY KEY, - guildid TEXT NOT NULL, - times TEXT NOT NULL + userId TEXT NOT NULL PRIMARY KEY, + guildId TEXT NOT NULL, + timesWarned TEXT NOT NULL ) \ No newline at end of file From c72d082248ed6fff3f2735669638f3de6dc21a6b Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 14:33:43 +0000 Subject: [PATCH 06/50] Finished making warn command --- .../org/togetherjava/tjbot/commands/Commands.java | 3 ++- .../tjbot/commands/moderation/WarnCommand.java | 15 +++++++-------- .../src/main/resources/db/V2_Add_Warn_System.sql | 6 +++--- 3 files changed, 12 insertions(+), 12 deletions(-) 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..96adac8b00 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -5,6 +5,7 @@ import org.togetherjava.tjbot.commands.basic.PingCommand; import org.togetherjava.tjbot.commands.basic.VcActivityCommand; import org.togetherjava.tjbot.commands.mathcommands.TeXCommand; +import org.togetherjava.tjbot.commands.moderation.WarnCommand; import org.togetherjava.tjbot.commands.tags.TagCommand; import org.togetherjava.tjbot.commands.tags.TagManageCommand; import org.togetherjava.tjbot.commands.tags.TagSystem; @@ -42,6 +43,6 @@ 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 VcActivityCommand(), new WarnCommand(database)); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 4cbc24d8fb..923b7760fc 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -62,14 +62,15 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { /** * Handles {@code /warn retrieve_warns user} commands. Retrieves the timesWarned value and then - * sends that value to the user as an embed + * sends that value to the user as an embed. + *

+ * This command can only be used by users with the {@code BAN_MEMBERS} permission. * * @param event the event of the command */ private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(RETRIEVE_USER_OPTION), "The target is null"); - Member author = userOption.getAsMember(); // To prevent people from get users warn, only users with @@ -79,19 +80,18 @@ private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { } User target = userOption.getAsUser(); - try { Optional value = database.read(context -> { try (var select = context.selectFrom(Warns.WARNS)) { return Optional .ofNullable(select.where(Warns.WARNS.USERID.eq(target.getId())).fetchOne()) - .map(WarnsRecord::getTimes); + .map(WarnsRecord::getTimeswarned); } }); if (value.isEmpty()) { event - .replyEmbeds(new EmbedBuilder().setTitle("404 Error") + .replyEmbeds(new EmbedBuilder().setTitle("A Good User") .setDescription( "No warns can be found for the user " + target.getAsTag() + ".") .setColor(Color.magenta) @@ -126,7 +126,6 @@ private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { private void handleWarnCommand(@NotNull CommandInteraction event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(WARN_USER_OPTION), "The target is null"); - Member author = userOption.getAsMember(); Guild guild = Objects.requireNonNull(event.getGuild()); @@ -150,8 +149,8 @@ private void handleWarnCommand(@NotNull CommandInteraction event) { WarnsRecord warnRecord = context.newRecord(Warns.WARNS) .setUserid(userId) .setGuildid(guild.getId()) - .setTimes(Integer.toString(times)); - logger.info("The user '{}' ({}) warned the user '{}' ({}) for the reason '{}'", + .setTimeswarned(Integer.toString(times)); + logger.info("The member '{}' ({}) warned the user '{}' ({}) for the reason '{}'", author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), reason); if (warnRecord.update() == 0) { diff --git a/application/src/main/resources/db/V2_Add_Warn_System.sql b/application/src/main/resources/db/V2_Add_Warn_System.sql index d696ae80cc..6c881cdda6 100644 --- a/application/src/main/resources/db/V2_Add_Warn_System.sql +++ b/application/src/main/resources/db/V2_Add_Warn_System.sql @@ -1,6 +1,6 @@ CREATE TABLE warns ( - userId TEXT NOT NULL PRIMARY KEY, - guildId TEXT NOT NULL, - timesWarned TEXT NOT NULL + userid TEXT NOT NULL PRIMARY KEY, + guildid TEXT NOT NULL, + timeswarned TEXT NOT NULL ) \ No newline at end of file From 15ee5860ccbe405169f263dbf923250762793988 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 14:38:59 +0000 Subject: [PATCH 07/50] Update WarnCommand.java --- .../org/togetherjava/tjbot/commands/moderation/WarnCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 923b7760fc..fdc3d00683 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -91,7 +91,7 @@ private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { if (value.isEmpty()) { event - .replyEmbeds(new EmbedBuilder().setTitle("A Good User") + .replyEmbeds(new EmbedBuilder().setTitle("A behaved user") .setDescription( "No warns can be found for the user " + target.getAsTag() + ".") .setColor(Color.magenta) From d2bf005d6a5b3a38d90fd60b9acf979abf3dee72 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 16:23:54 +0000 Subject: [PATCH 08/50] Trying to fix an error --- .../commands/moderation/WarnCommand.java | 97 ++++--------------- .../main/resources/db/V2_Add_Warn_System.sql | 6 -- .../main/resources/db/V3_Add_Warn_System.sql | 6 ++ 3 files changed, 26 insertions(+), 83 deletions(-) delete mode 100644 application/src/main/resources/db/V2_Add_Warn_System.sql create mode 100644 application/src/main/resources/db/V3_Add_Warn_System.sql diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index fdc3d00683..95248b699f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -18,13 +18,12 @@ import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.db.Database; import org.togetherjava.tjbot.db.DatabaseException; -import org.togetherjava.tjbot.db.generated.tables.Warns; -import org.togetherjava.tjbot.db.generated.tables.records.WarnsRecord; import java.awt.*; import java.util.Objects; import java.util.Optional; + public class WarnCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); private static final String WARN_USER = "warn_user"; @@ -43,21 +42,9 @@ public WarnCommand(@NotNull Database database) { super("warn", "warns the user", SlashCommandVisibility.GUILD); this.database = database; - getData().addSubcommands(new SubcommandData(WARN_USER, "Used to warn the user") - .addOption(OptionType.USER, WARN_USER_OPTION, "The user to warn", true) - .addOption(OptionType.STRING, WARN_REASON_OPTION, "The reason for the warning", true), - new SubcommandData(RETRIEVE_WARNS_OPTION, "Uses to retrieve a warn for a member") - .addOption(OptionType.USER, RETRIEVE_USER_OPTION, - "The warns for the user you want", true)); - } - - @Override - public void onSlashCommand(@NotNull SlashCommandEvent event) { - switch (Objects.requireNonNull(event.getSubcommandName())) { - case WARN_USER -> handleWarnCommand(event); - case RETRIEVE_WARNS_OPTION -> handleRetrieveWarnCommand(event); - default -> throw new AssertionError(); - } + getData() + .addOption(OptionType.USER, WARN_USER_OPTION, "The user to warn", true) + .addOption(OptionType.STRING, WARN_REASON_OPTION, "The reason for the warning", true); } /** @@ -68,52 +55,6 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { * * @param event the event of the command */ - private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { - OptionMapping userOption = - Objects.requireNonNull(event.getOption(RETRIEVE_USER_OPTION), "The target is null"); - Member author = userOption.getAsMember(); - - // To prevent people from get users warn, only users with - // elevated permissions are allowed to use this command - if (handleHasPermissions(author, event, event.getGuild()).equals(false)) { - return; - } - - User target = userOption.getAsUser(); - try { - Optional value = database.read(context -> { - try (var select = context.selectFrom(Warns.WARNS)) { - return Optional - .ofNullable(select.where(Warns.WARNS.USERID.eq(target.getId())).fetchOne()) - .map(WarnsRecord::getTimeswarned); - } - }); - - if (value.isEmpty()) { - event - .replyEmbeds(new EmbedBuilder().setTitle("A behaved user") - .setDescription( - "No warns can be found for the user " + target.getAsTag() + ".") - .setColor(Color.magenta) - .build()) - .queue(); - return; - } - - event - .replyEmbeds(new EmbedBuilder() - .setAuthor("This command was created by " + author.getEffectiveName(), null, - author.getEffectiveAvatarUrl()) - .setTitle("The User " + target.getAsTag() + " warns") - .setDescription("They have " + value.orElseThrow() + " number of warns") - .setColor(Color.magenta) - .build()) - .queue(); - } catch (DatabaseException e) { - logger.error("Failed to get the number of warns ", e); - event.reply("Sorry, something went wrong.").setEphemeral(true).queue(); - } - } /** * Handles {@code /warn warn_user user reason} command. Saves the value under the given user, @@ -123,7 +64,8 @@ private void handleRetrieveWarnCommand(@NotNull CommandInteraction event) { * * @param event the event of the command */ - private void handleWarnCommand(@NotNull CommandInteraction event) { + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(WARN_USER_OPTION), "The target is null"); Member author = userOption.getAsMember(); @@ -139,17 +81,17 @@ private void handleWarnCommand(@NotNull CommandInteraction event) { User target = userOption.getAsUser(); String reason = Objects.requireNonNull(event.getOption(WARN_REASON_OPTION)).getAsString(); // TODO double check this part - int times = +1; + int warningAmount = 1; String userId = target.getId(); dmUser(event.getJDA(), userId, reason, guild); + /** try { database.write(context -> { - WarnsRecord warnRecord = context.newRecord(Warns.WARNS) - .setUserid(userId) - .setGuildid(guild.getId()) - .setTimeswarned(Integer.toString(times)); + WarnsRecord warnRecord = + context.newRecord(Warns.WARNS).setUserid(userId).setGuildid(guild.getId()); + // .setTimeswarned(warningAmount); logger.info("The member '{}' ({}) warned the user '{}' ({}) for the reason '{}'", author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), reason); @@ -157,13 +99,14 @@ private void handleWarnCommand(@NotNull CommandInteraction event) { warnRecord.insert(); } }); - } catch (DatabaseException e) { - logger.error("Failed to put message", e); - event.reply("Sorry, something went wrong.").setEphemeral(true).queue(); + } finally { + event.reply("Warned " + target.getAsMention() + " for " + reason).queue(); } + */ } - private static void dmUser(JDA jda, String userId, String reason, Guild guild) { + private static void dmUser(@NotNull JDA jda, @NotNull String userId, @NotNull String reason, + @NotNull Guild guild) { jda.openPrivateChannelById(userId) .flatMap(channel -> channel.sendMessage( """ @@ -174,16 +117,16 @@ private static void dmUser(JDA jda, String userId, String reason, Guild guild) { .queue(); } - private static Boolean handleHasPermissions(Member author, CommandInteraction event, - Guild guild) { + private static Boolean handleHasPermissions(@NotNull Member author, + @NotNull CommandInteraction event, @NotNull Guild guild) { if (!author.hasPermission(Permission.BAN_MEMBERS)) { - event.reply("You need the MESSAGE_MANAGE permission to use this command") + event.reply("You need the BAN_MEMBERS permission to use this command") .setEphemeral(true) .queue(); return false; } if (!guild.getSelfMember().hasPermission(Permission.BAN_MEMBERS)) { - event.reply("You need the MESSAGE_MANAGE permission to use this command") + event.reply("You need the BAN_MEMBERS permission to use this command") .setEphemeral(true) .queue(); return false; diff --git a/application/src/main/resources/db/V2_Add_Warn_System.sql b/application/src/main/resources/db/V2_Add_Warn_System.sql deleted file mode 100644 index 6c881cdda6..0000000000 --- a/application/src/main/resources/db/V2_Add_Warn_System.sql +++ /dev/null @@ -1,6 +0,0 @@ -CREATE TABLE warns -( - userid TEXT NOT NULL PRIMARY KEY, - guildid TEXT NOT NULL, - timeswarned TEXT NOT NULL -) \ No newline at end of file diff --git a/application/src/main/resources/db/V3_Add_Warn_System.sql b/application/src/main/resources/db/V3_Add_Warn_System.sql new file mode 100644 index 0000000000..5897eb0d39 --- /dev/null +++ b/application/src/main/resources/db/V3_Add_Warn_System.sql @@ -0,0 +1,6 @@ +CREATE TABLE warns +( + user_id BIGINT NOT NULL PRIMARY KEY, + guild_id BIGINT NOT NULL, + warning_amount INTEGER NOT NULL +) \ No newline at end of file From 1c6d65e843cbcabcb29dc6a999e6f9cbd65309f4 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 16:31:38 +0000 Subject: [PATCH 09/50] TODO fix --- .../commands/moderation/WarnCommand.java | 30 ++++++------------- .../main/resources/db/V3_Add_Warn_System.sql | 2 +- 2 files changed, 10 insertions(+), 22 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 95248b699f..a08002836d 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -26,11 +26,8 @@ public class WarnCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); - private static final String WARN_USER = "warn_user"; private static final String WARN_USER_OPTION = "user"; private static final String WARN_REASON_OPTION = "reason"; - private static final String RETRIEVE_WARNS_OPTION = "retrieve_warns"; - private static final String RETRIEVE_USER_OPTION = "user"; private final Database database; /** @@ -42,9 +39,8 @@ public WarnCommand(@NotNull Database database) { super("warn", "warns the user", SlashCommandVisibility.GUILD); this.database = database; - getData() - .addOption(OptionType.USER, WARN_USER_OPTION, "The user to warn", true) - .addOption(OptionType.STRING, WARN_REASON_OPTION, "The reason for the warning", true); + getData().addOption(OptionType.USER, WARN_USER_OPTION, "The user to warn", true) + .addOption(OptionType.STRING, WARN_REASON_OPTION, "The reason for the warning", true); } /** @@ -87,21 +83,13 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { dmUser(event.getJDA(), userId, reason, guild); /** - try { - database.write(context -> { - WarnsRecord warnRecord = - context.newRecord(Warns.WARNS).setUserid(userId).setGuildid(guild.getId()); - // .setTimeswarned(warningAmount); - logger.info("The member '{}' ({}) warned the user '{}' ({}) for the reason '{}'", - author.getUser().getAsTag(), author.getId(), target.getAsTag(), - target.getId(), reason); - if (warnRecord.update() == 0) { - warnRecord.insert(); - } - }); - } finally { - event.reply("Warned " + target.getAsMention() + " for " + reason).queue(); - } + * try { database.write(context -> { WarnsRecord warnRecord = + * context.newRecord(Warns.WARNS).setUserid(userId).setGuildid(guild.getId()); // + * .setTimeswarned(warningAmount); logger.info("The member '{}' ({}) warned the user '{}' + * ({}) for the reason '{}'", author.getUser().getAsTag(), author.getId(), + * target.getAsTag(), target.getId(), reason); if (warnRecord.update() == 0) { + * warnRecord.insert(); } }); } finally { event.reply("Warned " + target.getAsMention() + " + * for " + reason).queue(); } */ } diff --git a/application/src/main/resources/db/V3_Add_Warn_System.sql b/application/src/main/resources/db/V3_Add_Warn_System.sql index 5897eb0d39..2175b09f19 100644 --- a/application/src/main/resources/db/V3_Add_Warn_System.sql +++ b/application/src/main/resources/db/V3_Add_Warn_System.sql @@ -1,6 +1,6 @@ CREATE TABLE warns ( - user_id BIGINT NOT NULL PRIMARY KEY, + userid BIGINT NOT NULL PRIMARY KEY, guild_id BIGINT NOT NULL, warning_amount INTEGER NOT NULL ) \ No newline at end of file From 156beff053f767bbb3fee790d3893c7f63450246 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 16:34:18 +0000 Subject: [PATCH 10/50] Fixed --- .../db/{V3_Add_Warn_System.sql => V3__Add_Warn_System.sql} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename application/src/main/resources/db/{V3_Add_Warn_System.sql => V3__Add_Warn_System.sql} (100%) diff --git a/application/src/main/resources/db/V3_Add_Warn_System.sql b/application/src/main/resources/db/V3__Add_Warn_System.sql similarity index 100% rename from application/src/main/resources/db/V3_Add_Warn_System.sql rename to application/src/main/resources/db/V3__Add_Warn_System.sql From 3bb4bd0e3703553bfba9aa6112344f7b828674e1 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 16:37:09 +0000 Subject: [PATCH 11/50] spotlessApply --- .../commands/moderation/WarnCommand.java | 40 +++++++++++-------- 1 file changed, 23 insertions(+), 17 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index a08002836d..44060fd198 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -1,6 +1,5 @@ package org.togetherjava.tjbot.commands.moderation; -import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; @@ -10,18 +9,16 @@ import net.dv8tion.jda.api.interactions.commands.CommandInteraction; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; -import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; 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 org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.db.DatabaseException; +import org.togetherjava.tjbot.db.generated.tables.Warns; +import org.togetherjava.tjbot.db.generated.tables.records.WarnsRecord; -import java.awt.*; import java.util.Objects; -import java.util.Optional; public class WarnCommand extends SlashCommandAdapter { @@ -79,18 +76,27 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { // TODO double check this part int warningAmount = 1; - String userId = target.getId(); - dmUser(event.getJDA(), userId, reason, guild); - - /** - * try { database.write(context -> { WarnsRecord warnRecord = - * context.newRecord(Warns.WARNS).setUserid(userId).setGuildid(guild.getId()); // - * .setTimeswarned(warningAmount); logger.info("The member '{}' ({}) warned the user '{}' - * ({}) for the reason '{}'", author.getUser().getAsTag(), author.getId(), - * target.getAsTag(), target.getId(), reason); if (warnRecord.update() == 0) { - * warnRecord.insert(); } }); } finally { event.reply("Warned " + target.getAsMention() + " - * for " + reason).queue(); } - */ + Long userId = target.getIdLong(); + dmUser(event.getJDA(), target.getId(), reason, guild); + + + try { + database.write(context -> { + WarnsRecord warnRecord = context.newRecord(Warns.WARNS) + .setUserid(userId) + .setGuildId(guild.getIdLong()) + .setWarningAmount(warningAmount); + logger.info("The member '{}' ({}) warned the user '{}' ({}) for the reason '{}'", + author.getUser().getAsTag(), author.getId(), target.getAsTag(), + target.getId(), reason); + if (warnRecord.update() == 0) { + warnRecord.insert(); + } + }); + } finally { + event.reply("Warned " + target.getAsMention() + " for " + reason).queue(); + } + } private static void dmUser(@NotNull JDA jda, @NotNull String userId, @NotNull String reason, From 428ceca187936d93a6ce2193fbc82f43552f4dae Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 16:45:15 +0000 Subject: [PATCH 12/50] Removed TODO --- .../commands/moderation/WarnCommand.java | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 44060fd198..405cc51e9e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -23,21 +23,19 @@ public class WarnCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); - private static final String WARN_USER_OPTION = "user"; - private static final String WARN_REASON_OPTION = "reason"; + private static final String USER_OPTION = "user"; + private static final String REASON_OPTION = "reason"; private final Database database; /** - * Creates a new adapter with the given data. - * - * @param database the database to store the key-value pairs in + * Creates a new Instance. */ public WarnCommand(@NotNull Database database) { super("warn", "warns the user", SlashCommandVisibility.GUILD); this.database = database; - getData().addOption(OptionType.USER, WARN_USER_OPTION, "The user to warn", true) - .addOption(OptionType.STRING, WARN_REASON_OPTION, "The reason for the warning", true); + getData().addOption(OptionType.USER, USER_OPTION, "The user to warn", true) + .addOption(OptionType.STRING, REASON_OPTION, "The reason for the warning", true); } /** @@ -60,20 +58,19 @@ public WarnCommand(@NotNull Database database) { @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping userOption = - Objects.requireNonNull(event.getOption(WARN_USER_OPTION), "The target is null"); + Objects.requireNonNull(event.getOption(USER_OPTION), "The user is null"); Member author = userOption.getAsMember(); Guild guild = Objects.requireNonNull(event.getGuild()); // To prevent people from using warn content, only users with // elevated permissions are allowed to use this command - if (handleHasPermissions(author, event, guild).equals(false)) { + if (!handleHasPermissions(author, event, guild)) { return; } // /warn warn_user @Zabuzard who knows User target = userOption.getAsUser(); - String reason = Objects.requireNonNull(event.getOption(WARN_REASON_OPTION)).getAsString(); - // TODO double check this part + String reason = Objects.requireNonNull(event.getOption(REASON_OPTION)).getAsString(); int warningAmount = 1; Long userId = target.getIdLong(); From 4381ab75d188187353412649bef38968f9694fe9 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 17:04:30 +0000 Subject: [PATCH 13/50] fixed Javadoc --- .../tjbot/commands/moderation/WarnCommand.java | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 405cc51e9e..6af89f391e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -38,15 +38,6 @@ public WarnCommand(@NotNull Database database) { .addOption(OptionType.STRING, REASON_OPTION, "The reason for the warning", true); } - /** - * Handles {@code /warn retrieve_warns user} commands. Retrieves the timesWarned value and then - * sends that value to the user as an embed. - *

- * This command can only be used by users with the {@code BAN_MEMBERS} permission. - * - * @param event the event of the command - */ - /** * Handles {@code /warn warn_user user reason} command. Saves the value under the given user, * given guild and add +1 to the number of warns the user has. @@ -82,7 +73,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { WarnsRecord warnRecord = context.newRecord(Warns.WARNS) .setUserid(userId) .setGuildId(guild.getIdLong()) - .setWarningAmount(warningAmount); + .setWarningAmount(warningAmount i++); logger.info("The member '{}' ({}) warned the user '{}' ({}) for the reason '{}'", author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), reason); From a5341c91d29852e669bb1c62b7939123f39412dd Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 6 Nov 2021 17:51:00 +0000 Subject: [PATCH 14/50] Ready for testing --- .../commands/moderation/WarnCommand.java | 38 +++++++++++++------ .../main/resources/db/V3__Add_Warn_System.sql | 5 ++- 2 files changed, 29 insertions(+), 14 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 6af89f391e..f7b97abeee 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.commands.moderation; +import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; @@ -18,7 +19,9 @@ import org.togetherjava.tjbot.db.generated.tables.Warns; import org.togetherjava.tjbot.db.generated.tables.records.WarnsRecord; +import java.awt.*; import java.util.Objects; +import java.util.Optional; public class WarnCommand extends SlashCommandAdapter { @@ -61,28 +64,41 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { // /warn warn_user @Zabuzard who knows User target = userOption.getAsUser(); + Long userId = target.getIdLong(); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION)).getAsString(); - int warningAmount = 1; + Optional currentWarningAmount = database.read(context -> { + try (var select = context.selectFrom(Warns.WARNS)) { + return Optional.ofNullable(select.where(Warns.WARNS.USERID.eq(userId)).fetchOne()) + .map(WarnsRecord::getWarningAmount); + } + }); - Long userId = target.getIdLong(); - dmUser(event.getJDA(), target.getId(), reason, guild); + Optional newWarningAmount = currentWarningAmount.map(amount -> amount + 1); + dmUser(event.getJDA(), target.getId(), reason, guild); try { database.write(context -> { WarnsRecord warnRecord = context.newRecord(Warns.WARNS) .setUserid(userId) .setGuildId(guild.getIdLong()) - .setWarningAmount(warningAmount i++); + .setWarnReason(reason) + .setWarningAmount(newWarningAmount.get()); logger.info("The member '{}' ({}) warned the user '{}' ({}) for the reason '{}'", author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), reason); + if (warnRecord.update() == 0) { warnRecord.insert(); } }); } finally { - event.reply("Warned " + target.getAsMention() + " for " + reason).queue(); + event + .replyEmbeds(new EmbedBuilder().setTitle("Success") + .setDescription("Warned " + target.getAsMention() + " for " + reason) + .setColor(Color.MAGENTA) + .build()) + .queue(); } } @@ -90,16 +106,14 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { private static void dmUser(@NotNull JDA jda, @NotNull String userId, @NotNull String reason, @NotNull Guild guild) { jda.openPrivateChannelById(userId) - .flatMap(channel -> channel.sendMessage( - """ - Hey there, sorry to tell you but unfortunately you have been warned by the server %s. - The reason for the warn is: %s - """ - .formatted(guild.getName(), reason))) + .flatMap(channel -> channel.sendMessageEmbeds(new EmbedBuilder().setTitle("Warn") + .setDescription("You have been warned in " + guild.getName() + " for " + reason) + .setColor(Color.MAGENTA) + .build())) .queue(); } - private static Boolean handleHasPermissions(@NotNull Member author, + private static boolean handleHasPermissions(@NotNull Member author, @NotNull CommandInteraction event, @NotNull Guild guild) { if (!author.hasPermission(Permission.BAN_MEMBERS)) { event.reply("You need the BAN_MEMBERS permission to use this command") diff --git a/application/src/main/resources/db/V3__Add_Warn_System.sql b/application/src/main/resources/db/V3__Add_Warn_System.sql index 2175b09f19..79d855c712 100644 --- a/application/src/main/resources/db/V3__Add_Warn_System.sql +++ b/application/src/main/resources/db/V3__Add_Warn_System.sql @@ -1,6 +1,7 @@ CREATE TABLE warns ( - userid BIGINT NOT NULL PRIMARY KEY, - guild_id BIGINT NOT NULL, + userid BIGINT NOT NULL PRIMARY KEY, + guild_id BIGINT NOT NULL, + warn_reason TEXT NOT NULL, warning_amount INTEGER NOT NULL ) \ No newline at end of file From fcdf21b6c0d9d148f111341dd68d0c9632dfd674 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Tue, 16 Nov 2021 19:54:10 +0000 Subject: [PATCH 15/50] add the database for the ban and kick command --- .../togetherjava/tjbot/commands/Commands.java | 6 +-- .../commands/moderation/AuditCommand.java | 20 ++++++++ .../tjbot/commands/moderation/BanCommand.java | 26 +++++++++- .../commands/moderation/KickCommand.java | 25 +++++++++- .../commands/moderation/WarnCommand.java | 50 ------------------- .../main/resources/db/V3__Add_Warn_System.sql | 7 --- .../main/resources/db/V5__Add_Warn_System.sql | 10 ++++ .../main/resources/db/V6__Add_Ban_System.sql | 10 ++++ .../main/resources/db/V7__Add_Kick_System.sql | 10 ++++ 9 files changed, 102 insertions(+), 62 deletions(-) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java delete mode 100644 application/src/main/resources/db/V3__Add_Warn_System.sql create mode 100644 application/src/main/resources/db/V5__Add_Warn_System.sql create mode 100644 application/src/main/resources/db/V6__Add_Ban_System.sql create mode 100644 application/src/main/resources/db/V7__Add_Kick_System.sql 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 91fe98fd63..d44ca8e869 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -53,10 +53,10 @@ public enum Commands { commands.add(new TagManageCommand(tagSystem)); commands.add(new TagsCommand(tagSystem)); commands.add(new VcActivityCommand()); - commands.add(new KickCommand()); - commands.add(new BanCommand()); + commands.add(new KickCommand(database)); + commands.add(new BanCommand(database)); commands.add(new UnbanCommand()); - commands.add(database)); + commands.add(new WarnCommand(database)); return commands; } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java new file mode 100644 index 0000000000..f4767d42a7 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -0,0 +1,20 @@ +package org.togetherjava.tjbot.commands.moderation; + +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; + +public class AuditCommand extends SlashCommandAdapter { + /** + * Creates a new adapter with the given data. + */ + protected AuditCommand() { + super("audit", "get the audit for the commands", SlashCommandVisibility.GUILD); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandEvent event) { + event.getChannel().sendMessage("In creation").queue(); + } +} 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 index 427eb63ee4..a0871202a5 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -21,6 +21,9 @@ import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; +import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.BanSystem; +import org.togetherjava.tjbot.db.generated.tables.records.BanSystemRecord; import java.util.Objects; import java.util.Optional; @@ -42,13 +45,17 @@ public final class BanCommand extends SlashCommandAdapter { private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "ban"; private static final String ACTION_VERB = "ban"; + private final Database database; private final Predicate hasRequiredRole; /** * Constructs an instance. + * + * @param database used to store the bans in the database */ - public BanCommand() { + public BanCommand(Database database) { super(COMMAND_NAME, "Bans the given user from the server", SlashCommandVisibility.GUILD); + this.database = database; getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to ban", true) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be banned", true) @@ -163,6 +170,7 @@ private boolean handleChecks(@NotNull Member bot, @NotNull Member author, return ModerationUtils.handleReason(reason, event); } + @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping targetOption = @@ -192,5 +200,21 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { .requireNonNull(alreadyBanned.getFailure()), event, guild, target).orElseGet( () -> banUserFlow(target, author, reason, deleteHistoryDays, guild, event)); }).queue(); + + try { + database.write(context -> { + BanSystemRecord banSystemRecord = context.newRecord(BanSystem.BAN_SYSTEM) + .setUserid(target.getIdLong()) + .setAuthorId(author.getIdLong()) + .setGuildId(guild.getIdLong()) + .setBanReason(reason); + if (banSystemRecord.update() == 0) { + banSystemRecord.insert(); + } + }); + logger.info("Saved the user '{}' to the ban system.", target.getAsTag()); + } catch (Exception exception) { + exception.printStackTrace(); + } } } 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 index 27f81c3501..be4fd82448 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java @@ -16,6 +16,9 @@ import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; +import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.KickSystem; +import org.togetherjava.tjbot.db.generated.tables.records.KickSystemRecord; import java.util.Objects; import java.util.function.Predicate; @@ -35,13 +38,17 @@ public final class KickCommand extends SlashCommandAdapter { private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "kick"; private static final String ACTION_VERB = "kick"; + private final Database database; private final Predicate hasRequiredRole; /** * Constructs an instance. + * + * @param database used to store the kicks in the database */ - public KickCommand() { + public KickCommand(Database database) { super(COMMAND_NAME, "Kicks the given user from the server", SlashCommandVisibility.GUILD); + this.database = database; getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to kick", true) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be kicked", true); @@ -141,5 +148,21 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { return; } kickUserFlow(Objects.requireNonNull(target), author, reason, guild, event); + + try { + database.write(context -> { + KickSystemRecord kickSystemRecord = context.newRecord(KickSystem.KICK_SYSTEM) + .setUserid(target.getUser().getIdLong()) + .setAuthorId(author.getIdLong()) + .setGuildId(guild.getIdLong()) + .setKickReason(reason); + if (kickSystemRecord.update() == 0) { + kickSystemRecord.insert(); + } + }); + logger.info("Saved the user '{}' to the kick system.", target.getUser().getAsTag()); + } catch (Exception exception) { + exception.printStackTrace(); + } } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index f7b97abeee..25b73bb6e2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -5,7 +5,6 @@ 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.CommandInteraction; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -16,12 +15,9 @@ import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.db.generated.tables.Warns; -import org.togetherjava.tjbot.db.generated.tables.records.WarnsRecord; import java.awt.*; import java.util.Objects; -import java.util.Optional; public class WarnCommand extends SlashCommandAdapter { @@ -55,52 +51,6 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Objects.requireNonNull(event.getOption(USER_OPTION), "The user is null"); Member author = userOption.getAsMember(); Guild guild = Objects.requireNonNull(event.getGuild()); - - // To prevent people from using warn content, only users with - // elevated permissions are allowed to use this command - if (!handleHasPermissions(author, event, guild)) { - return; - } - - // /warn warn_user @Zabuzard who knows - User target = userOption.getAsUser(); - Long userId = target.getIdLong(); - String reason = Objects.requireNonNull(event.getOption(REASON_OPTION)).getAsString(); - Optional currentWarningAmount = database.read(context -> { - try (var select = context.selectFrom(Warns.WARNS)) { - return Optional.ofNullable(select.where(Warns.WARNS.USERID.eq(userId)).fetchOne()) - .map(WarnsRecord::getWarningAmount); - } - }); - - Optional newWarningAmount = currentWarningAmount.map(amount -> amount + 1); - - dmUser(event.getJDA(), target.getId(), reason, guild); - - try { - database.write(context -> { - WarnsRecord warnRecord = context.newRecord(Warns.WARNS) - .setUserid(userId) - .setGuildId(guild.getIdLong()) - .setWarnReason(reason) - .setWarningAmount(newWarningAmount.get()); - logger.info("The member '{}' ({}) warned the user '{}' ({}) for the reason '{}'", - author.getUser().getAsTag(), author.getId(), target.getAsTag(), - target.getId(), reason); - - if (warnRecord.update() == 0) { - warnRecord.insert(); - } - }); - } finally { - event - .replyEmbeds(new EmbedBuilder().setTitle("Success") - .setDescription("Warned " + target.getAsMention() + " for " + reason) - .setColor(Color.MAGENTA) - .build()) - .queue(); - } - } private static void dmUser(@NotNull JDA jda, @NotNull String userId, @NotNull String reason, diff --git a/application/src/main/resources/db/V3__Add_Warn_System.sql b/application/src/main/resources/db/V3__Add_Warn_System.sql deleted file mode 100644 index 79d855c712..0000000000 --- a/application/src/main/resources/db/V3__Add_Warn_System.sql +++ /dev/null @@ -1,7 +0,0 @@ -CREATE TABLE warns -( - userid BIGINT NOT NULL PRIMARY KEY, - guild_id BIGINT NOT NULL, - warn_reason TEXT NOT NULL, - warning_amount INTEGER NOT NULL -) \ No newline at end of file diff --git a/application/src/main/resources/db/V5__Add_Warn_System.sql b/application/src/main/resources/db/V5__Add_Warn_System.sql new file mode 100644 index 0000000000..6a6cce05da --- /dev/null +++ b/application/src/main/resources/db/V5__Add_Warn_System.sql @@ -0,0 +1,10 @@ +CREATE TABLE warn_system +( + /** + This was taken from Yusuf's Moderation bot. I the owner allow this. + */ + userid BIGINT NOT NULL PRIMARY KEY, + guild_id BIGINT NOT NULL, + warn_reason TEXT DEFAULT 'This user has been warned for breaking one of the rules.', + warning_amount INTEGER DEFAULT 0 +) \ No newline at end of file diff --git a/application/src/main/resources/db/V6__Add_Ban_System.sql b/application/src/main/resources/db/V6__Add_Ban_System.sql new file mode 100644 index 0000000000..be169f52a3 --- /dev/null +++ b/application/src/main/resources/db/V6__Add_Ban_System.sql @@ -0,0 +1,10 @@ +CREATE TABLE ban_system +( + /** + This was taken from Yusuf's Moderation bot. I the owner allow this. + */ + userid BIGINT NOT NULL PRIMARY KEY, + guild_id BIGINT NOT NULL, + author_id BIGINT NOT NULL, + ban_reason TEXT DEFAULT 'This user has been banned for breaking one of the rules.' +) \ No newline at end of file diff --git a/application/src/main/resources/db/V7__Add_Kick_System.sql b/application/src/main/resources/db/V7__Add_Kick_System.sql new file mode 100644 index 0000000000..ccb6fea018 --- /dev/null +++ b/application/src/main/resources/db/V7__Add_Kick_System.sql @@ -0,0 +1,10 @@ +CREATE TABLE kick_system +( + /** + This was taken from Yusuf's Moderation bot. I the owner allow this. + */ + userid BIGINT NOT NULL PRIMARY KEY, + guild_id BIGINT NOT NULL, + author_id BIGINT NOT NULL, + kick_reason TEXT DEFAULT 'This user has been kicked for breaking one of the rules.' +) \ No newline at end of file From ad37972d9db0d8bcea2935a3cdc8be0c32c7c7b8 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Tue, 16 Nov 2021 20:40:51 +0000 Subject: [PATCH 16/50] To be continued --- .../commands/moderation/WarnCommand.java | 29 +++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 25b73bb6e2..6121459549 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -5,6 +5,7 @@ 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.CommandInteraction; import net.dv8tion.jda.api.interactions.commands.OptionMapping; @@ -15,6 +16,8 @@ import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.WarnSystem; +import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; import java.awt.*; import java.util.Objects; @@ -49,8 +52,34 @@ public WarnCommand(@NotNull Database database) { public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(USER_OPTION), "The user is null"); + User target = userOption.getAsUser(); Member author = userOption.getAsMember(); Guild guild = Objects.requireNonNull(event.getGuild()); + String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") + .getAsString(); + + if (!handleHasPermissions(author, event, guild)) { + return; + } + + dmUser(event.getJDA(), target.getId(), reason, guild); + + try { + database.write(context -> { + WarnSystemRecord warnSystemRecord = context.newRecord(WarnSystem.WARN_SYSTEM) + .setUserid(target.getIdLong()) + .setGuildId(guild.getIdLong()) + .setWarnReason(reason) + // TODO change this + .setWarningAmount(1); + if (warnSystemRecord.update() == 0) { + warnSystemRecord.insert(); + } + }); + logger.info("Saved the user '{}' to the ban system.", target.getAsTag()); + } catch (Exception exception) { + exception.printStackTrace(); + } } private static void dmUser(@NotNull JDA jda, @NotNull String userId, @NotNull String reason, From bbf8a23197925a69c98d86a3fd7913f949237291 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Tue, 16 Nov 2021 21:22:19 +0000 Subject: [PATCH 17/50] Cleaning the warn command up --- .../commands/moderation/WarnCommand.java | 74 ++++++++++++++----- 1 file changed, 54 insertions(+), 20 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 6121459549..16a9480b31 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -7,27 +7,42 @@ 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.Interaction; import net.dv8tion.jda.api.interactions.commands.CommandInteraction; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.db.Database; import org.togetherjava.tjbot.db.generated.tables.WarnSystem; import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; import java.awt.*; import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.regex.Pattern; +/** + * This command allows a moderator to warn a user. This moderator will need to have ban permission + * and well need to type {@code /warn @user reason}. If the command is successful the user will be + * warned and will receive a dm telling them why there were warned. After that all the data will be + * added to the database. + */ public class WarnCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); private static final String USER_OPTION = "user"; private static final String REASON_OPTION = "reason"; + private static final String ACTION_VERB = "warn"; private final Database database; + private final Predicate hasRequiredRole; + /** * Creates a new Instance. @@ -38,13 +53,16 @@ public WarnCommand(@NotNull Database database) { getData().addOption(OptionType.USER, USER_OPTION, "The user to warn", true) .addOption(OptionType.STRING, REASON_OPTION, "The reason for the warning", true); + + hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) + .asMatchPredicate(); } /** - * Handles {@code /warn warn_user user reason} command. Saves the value under the given user, - * given guild and add +1 to the number of warns the user has. + * Handles {@code /warn user reason} command. Saves the value under the given user, given guild, + * given reason and add +1 to the number of warns the user has. *

- * This command can only be used by users with the {@code BAN_MEMBERS} permission. + * This command can only be used by users with the {@code KICK_MEMBERS} permission. * * @param event the event of the command */ @@ -53,25 +71,37 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(USER_OPTION), "The user is null"); User target = userOption.getAsUser(); + Member targetMember = userOption.getAsMember(); Member author = userOption.getAsMember(); Guild guild = Objects.requireNonNull(event.getGuild()); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") .getAsString(); - if (!handleHasPermissions(author, event, guild)) { + if (!handleChecks(guild.getSelfMember(), author, targetMember, reason, guild, event)) { return; } - dmUser(event.getJDA(), target.getId(), reason, guild); + long userId = target.getIdLong(); + dmUser(event.getJDA(), userId, reason, guild); + long guildId = guild.getIdLong(); + Optional oldWarnAmount = database.read(context -> { + try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { + return Optional + .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USERID.eq(target.getIdLong()) + .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(WarnSystemRecord::getWarningAmount); + } + }); + + int newWarnAmount = oldWarnAmount.orElse(0) + 1; try { database.write(context -> { WarnSystemRecord warnSystemRecord = context.newRecord(WarnSystem.WARN_SYSTEM) .setUserid(target.getIdLong()) - .setGuildId(guild.getIdLong()) + .setGuildId(guildId) .setWarnReason(reason) - // TODO change this - .setWarningAmount(1); + .setWarningAmount(newWarnAmount); if (warnSystemRecord.update() == 0) { warnSystemRecord.insert(); } @@ -82,7 +112,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { } } - private static void dmUser(@NotNull JDA jda, @NotNull String userId, @NotNull String reason, + private static void dmUser(@NotNull JDA jda, long userId, @NotNull String reason, @NotNull Guild guild) { jda.openPrivateChannelById(userId) .flatMap(channel -> channel.sendMessageEmbeds(new EmbedBuilder().setTitle("Warn") @@ -92,20 +122,24 @@ private static void dmUser(@NotNull JDA jda, @NotNull String userId, @NotNull St .queue(); } - private static boolean handleHasPermissions(@NotNull Member author, - @NotNull CommandInteraction event, @NotNull Guild guild) { - if (!author.hasPermission(Permission.BAN_MEMBERS)) { - event.reply("You need the BAN_MEMBERS permission to use this command") - .setEphemeral(true) - .queue(); + private boolean handleChecks(@NotNull Member bot, @NotNull Member author, + @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, + @NotNull Interaction event) { + // Member doesn't exist if attempting to kick a user who is not part of the guild anymore. + if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, event)) { + return false; + } + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { + return false; + } + if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.KICK_MEMBERS, bot, + guild, event)) { return false; } - if (!guild.getSelfMember().hasPermission(Permission.BAN_MEMBERS)) { - event.reply("You need the BAN_MEMBERS permission to use this command") - .setEphemeral(true) - .queue(); + if (!ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, Permission.KICK_MEMBERS, + author, guild, event)) { return false; } - return true; + return ModerationUtils.handleReason(reason, event); } } From 3c791868816542994f3751e707ab8fbc9e3e9642 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 07:37:23 +0000 Subject: [PATCH 18/50] Update WarnCommand.java --- .../togetherjava/tjbot/commands/moderation/WarnCommand.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 16a9480b31..ef47ffd67f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -8,7 +8,6 @@ import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.Interaction; -import net.dv8tion.jda.api.interactions.commands.CommandInteraction; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import org.jetbrains.annotations.NotNull; @@ -106,7 +105,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { warnSystemRecord.insert(); } }); - logger.info("Saved the user '{}' to the ban system.", target.getAsTag()); + logger.info("Saved the user '{}' to the warn system.", target.getAsTag()); } catch (Exception exception) { exception.printStackTrace(); } From aca211003681940d5e549299e68a86f941fa1086 Mon Sep 17 00:00:00 2001 From: Yusuf Arfan Ismail Date: Wed, 17 Nov 2021 10:09:54 +0000 Subject: [PATCH 19/50] Workflow should pass now --- .../tjbot/commands/moderation/ModerationUtils.java | 6 +++++- .../tjbot/commands/moderation/WarnCommand.java | 14 +++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) 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 index 4070c3dfa5..335e25783c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -215,7 +215,11 @@ enum Action { /** * When a user kicks another user. */ - KICK("kicked"); + KICK("kicked"), + /** + * When a user warns another user + */ + WARN("warned"); private final String verb; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index ef47ffd67f..6d58dbe84d 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -42,7 +42,6 @@ public class WarnCommand extends SlashCommandAdapter { private final Database database; private final Predicate hasRequiredRole; - /** * Creates a new Instance. */ @@ -71,12 +70,14 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Objects.requireNonNull(event.getOption(USER_OPTION), "The user is null"); User target = userOption.getAsUser(); Member targetMember = userOption.getAsMember(); - Member author = userOption.getAsMember(); + Member author = Objects.requireNonNull(event.getMember(), "The author is null"); Guild guild = Objects.requireNonNull(event.getGuild()); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") .getAsString(); - if (!handleChecks(guild.getSelfMember(), author, targetMember, reason, guild, event)) { + Member bot = guild.getSelfMember(); + + if (!handleChecks(bot, author, targetMember, reason, guild, event)) { return; } @@ -124,10 +125,13 @@ private static void dmUser(@NotNull JDA jda, long userId, @NotNull String reason private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { - // Member doesn't exist if attempting to kick a user who is not part of the guild anymore. - if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, event)) { + + // Member doesn't exist if attempting to ban a user who is not part of the guild. + if (target != null && !ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, + target, event)) { return false; } + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { return false; } From dfb6646331878187f52e233080e5b79b3cd41b05 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 17:42:33 +0000 Subject: [PATCH 20/50] Thats it for now --- .../togetherjava/tjbot/commands/Commands.java | 6 +- .../commands/moderation/AuditCommand.java | 176 +++++++++++++++++- .../tjbot/commands/moderation/BanCommand.java | 1 + .../commands/moderation/KickCommand.java | 1 + .../commands/moderation/WarnCommand.java | 94 ++++++---- .../tjbot/commands/utils/MessageUtils.java | 30 +++ .../main/resources/db/V5__Add_Warn_System.sql | 9 +- .../main/resources/db/V6__Add_Ban_System.sql | 7 +- .../main/resources/db/V7__Add_Kick_System.sql | 7 +- 9 files changed, 276 insertions(+), 55 deletions(-) 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 d44ca8e869..7013d15a4c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -5,10 +5,7 @@ import org.togetherjava.tjbot.commands.basic.PingCommand; import org.togetherjava.tjbot.commands.basic.VcActivityCommand; import org.togetherjava.tjbot.commands.mathcommands.TeXCommand; -import org.togetherjava.tjbot.commands.moderation.WarnCommand; -import org.togetherjava.tjbot.commands.moderation.BanCommand; -import org.togetherjava.tjbot.commands.moderation.KickCommand; -import org.togetherjava.tjbot.commands.moderation.UnbanCommand; +import org.togetherjava.tjbot.commands.moderation.*; import org.togetherjava.tjbot.commands.tags.TagCommand; import org.togetherjava.tjbot.commands.tags.TagManageCommand; import org.togetherjava.tjbot.commands.tags.TagSystem; @@ -57,6 +54,7 @@ public enum Commands { commands.add(new BanCommand(database)); commands.add(new UnbanCommand()); commands.add(new WarnCommand(database)); + commands.add(new AuditCommand(database)); return commands; } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index f4767d42a7..92b27397db 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -1,20 +1,190 @@ package org.togetherjava.tjbot.commands.moderation; +import net.dv8tion.jda.api.EmbedBuilder; +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.Interaction; +import net.dv8tion.jda.api.interactions.commands.CommandInteraction; +import net.dv8tion.jda.api.interactions.commands.OptionMapping; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; 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 org.togetherjava.tjbot.config.Config; +import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.WarnSystem; +import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; +import java.awt.*; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +import static org.togetherjava.tjbot.commands.utils.MessageUtils.replyEphemeral; + +//TODO add javadoc public class AuditCommand extends SlashCommandAdapter { + private static final Logger logger = LoggerFactory.getLogger(AuditCommand.class); + private static final String ACTION_VERB = "audit"; + private static final String COMMAND_WARN = "warn"; + private static final String WARN_USER_OPTION = "user"; + private static final String COMMAND_KICK = "kick"; + private static final String KICK_USER_OPTION = "user"; + private static final String COMMAND_BAN = "ban"; + private static final String BAN_USER_OPTION = "user"; + private static final String DESCRIPTION = "The user who you want to get the values for"; + private static final String USER_IS_NULL = "The user is null"; + private final Database database; + private final Predicate hasRequiredRole; + /** * Creates a new adapter with the given data. + * + * @param database used to retrieve the user data for the moderation commands */ - protected AuditCommand() { - super("audit", "get the audit for the commands", SlashCommandVisibility.GUILD); + public AuditCommand(Database database) { + super(ACTION_VERB, "get the audit for the commands", SlashCommandVisibility.GUILD); + this.database = database; + + getData().addSubcommands( + new SubcommandData(COMMAND_WARN, "Gets the warn values for that user") + .addOption(OptionType.USER, WARN_USER_OPTION, DESCRIPTION, true), + new SubcommandData(COMMAND_KICK, "Gets the kick values for that user") + .addOption(OptionType.USER, KICK_USER_OPTION, DESCRIPTION, true), + new SubcommandData(COMMAND_BAN, "Gets the ban values for that user") + .addOption(OptionType.USER, BAN_USER_OPTION, DESCRIPTION, true)); + + hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) + .asMatchPredicate(); } @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { - event.getChannel().sendMessage("In creation").queue(); + switch (Objects.requireNonNull(event.getSubcommandName())) { + case COMMAND_WARN -> handleWarnCommand(event); + case COMMAND_KICK -> handleKickCommand(event); + case COMMAND_BAN -> handleBanCommand(event); + default -> throw new AssertionError(); + } + } + + private static boolean noValueFound(Optional value, @NotNull User target, String commandName, + @NotNull CommandInteraction event) { + if (value.isEmpty()) { + event + .replyEmbeds(new EmbedBuilder().setTitle("Null") + .setDescription( + "The user " + target.getAsTag() + " has never been " + commandName) + .setColor(Color.decode("#895FE8")) + .build()) + .setEphemeral(true) + .queue(); + return false; + } + return true; + } + + //TODO add javadoc + private void handleWarnCommand(@NotNull CommandInteraction event) { + OptionMapping userOption = + Objects.requireNonNull(event.getOption(WARN_USER_OPTION), USER_IS_NULL; + User target = userOption.getAsUser(); + Guild guild = Objects.requireNonNull(event.getGuild()); + + Member bot = guild.getSelfMember(); + Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); + + if (!handleChecks(bot, author, guild, event)) { + return; + } + + Long guildId = guild.getIdLong(); + Long userId = target.getIdLong(); + Optional amountOfWarns = database.read(context -> { + try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { + return Optional + .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USERID.eq(userId) + .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(WarnSystemRecord::getWarningAmount); + } + }); + + Optional warnReason = database.read(context -> { + try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { + return Optional + .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USERID.eq(userId) + .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(WarnSystemRecord::getWarnReason); + } + }); + + String warned = "warned"; + try { + Optional isWarned = database.read(context -> { + try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { + return Optional + .ofNullable( + select + .where(WarnSystem.WARN_SYSTEM.USERID.eq(userId) + .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))) + .fetchOne()) + .map(WarnSystemRecord::getIsWarned); + } + }); + if (!noValueFound(isWarned, target, warned, event) + && !noValueFound(amountOfWarns, target, warned, event) + && !noValueFound(warnReason, target, warned, event)) { + return; + } + + event + .replyEmbeds(new EmbedBuilder().setTitle("Null") + .setDescription("The user " + target.getAsTag() + " has " + amountOfWarns + + "for the reasons " + warnReason) + .setColor(Color.decode("#895FE8")) + .build()) + .setEphemeral(true) + .queue(); + } catch (Exception exception) { + logger.error("Failed to check if the user is warned", exception); + replyEphemeral("Failed to check if the user is warned", event); + } + } + + //TODO add javadoc + private void handleKickCommand(@NotNull CommandInteraction event) { + OptionMapping userOption = + Objects.requireNonNull(event.getOption(KICK_USER_OPTION), USER_IS_NULL); + User target = userOption.getAsUser(); + Guild guild = Objects.requireNonNull(event.getGuild()); + } + + //TODO add javadoc + private void handleBanCommand(@NotNull CommandInteraction event) { + OptionMapping userOption = + Objects.requireNonNull(event.getOption(BAN_USER_OPTION), USER_IS_NULL); + User target = userOption.getAsUser(); + Guild guild = Objects.requireNonNull(event.getGuild()); + } + + private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @NotNull Guild guild, + @NotNull Interaction event) { + + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { + return false; + } + if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.KICK_MEMBERS, bot, + guild, event)) { + return false; + } + return ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, Permission.KICK_MEMBERS, + author, guild, event); } } 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 index a0871202a5..f4daf25a63 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -207,6 +207,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { .setUserid(target.getIdLong()) .setAuthorId(author.getIdLong()) .setGuildId(guild.getIdLong()) + .setIsBanned(true) .setBanReason(reason); if (banSystemRecord.update() == 0) { banSystemRecord.insert(); 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 index be4fd82448..f3eaa88713 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java @@ -155,6 +155,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { .setUserid(target.getUser().getIdLong()) .setAuthorId(author.getIdLong()) .setGuildId(guild.getIdLong()) + .setIsKicked(true) .setKickReason(reason); if (kickSystemRecord.update() == 0) { kickSystemRecord.insert(); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 6d58dbe84d..cf827fcbc6 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -1,15 +1,17 @@ package org.togetherjava.tjbot.commands.moderation; import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.JDA; 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.MessageEmbed; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; import net.dv8tion.jda.api.interactions.Interaction; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.requests.RestAction; +import net.dv8tion.jda.api.utils.Result; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -56,9 +58,55 @@ public WarnCommand(@NotNull Database database) { .asMatchPredicate(); } + private static RestAction dmUser(long userId, @NotNull String reason, + @NotNull Guild guild, @NotNull SlashCommandEvent event) { + return event.getJDA() + .openPrivateChannelById(userId) + .flatMap(channel -> channel.sendMessageEmbeds(new EmbedBuilder().setTitle("Warn") + .setDescription("You have been warned in " + guild.getName() + " for " + reason) + .setColor(Color.decode("#895FE8")) + .build())) + .mapToResult() + .map(Result::isSuccess); + } + + private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull User target, + @NotNull Member author, @NotNull String reason) { + String dmNoticeText = ""; + if (!hasSentDm) { + dmNoticeText = "(Unable to send them a DM.)"; + } + return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.BAN, + target, dmNoticeText, reason); + } + + private boolean handleChecks(@NotNull Member bot, @NotNull Member author, + @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, + @NotNull Interaction event) { + + // Member doesn't exist if attempting to ban a user who is not part of the guild. + if (target != null && !ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, + target, event)) { + return false; + } + + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { + return false; + } + if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.KICK_MEMBERS, bot, + guild, event)) { + return false; + } + if (!ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, Permission.KICK_MEMBERS, + author, guild, event)) { + return false; + } + return ModerationUtils.handleReason(reason, event); + } + /** * Handles {@code /warn user reason} command. Saves the value under the given user, given guild, - * given reason and add +1 to the number of warns the user has. + * given reason and adds one to the number of warns the user has. *

* This command can only be used by users with the {@code KICK_MEMBERS} permission. * @@ -82,13 +130,16 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { } long userId = target.getIdLong(); - dmUser(event.getJDA(), userId, reason, guild); + dmUser(userId, reason, guild, event) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) + .flatMap(event::replyEmbeds) + .queue(); long guildId = guild.getIdLong(); Optional oldWarnAmount = database.read(context -> { try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { return Optional - .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USERID.eq(target.getIdLong()) + .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USERID.eq(userId) .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) .map(WarnSystemRecord::getWarningAmount); } @@ -101,6 +152,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { .setUserid(target.getIdLong()) .setGuildId(guildId) .setWarnReason(reason) + .setIsWarned(true) .setWarningAmount(newWarnAmount); if (warnSystemRecord.update() == 0) { warnSystemRecord.insert(); @@ -111,38 +163,4 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { exception.printStackTrace(); } } - - private static void dmUser(@NotNull JDA jda, long userId, @NotNull String reason, - @NotNull Guild guild) { - jda.openPrivateChannelById(userId) - .flatMap(channel -> channel.sendMessageEmbeds(new EmbedBuilder().setTitle("Warn") - .setDescription("You have been warned in " + guild.getName() + " for " + reason) - .setColor(Color.MAGENTA) - .build())) - .queue(); - } - - private boolean handleChecks(@NotNull Member bot, @NotNull Member author, - @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, - @NotNull Interaction event) { - - // Member doesn't exist if attempting to ban a user who is not part of the guild. - if (target != null && !ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, - target, event)) { - return false; - } - - if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { - return false; - } - if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.KICK_MEMBERS, bot, - guild, event)) { - return false; - } - if (!ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, Permission.KICK_MEMBERS, - author, guild, event)) { - return false; - } - return ModerationUtils.handleReason(reason, event); - } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java index ce35d8789d..8c18a8fcb1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java @@ -4,6 +4,8 @@ import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; +import net.dv8tion.jda.api.interactions.commands.CommandInteraction; import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.Button; import net.dv8tion.jda.api.utils.MarkdownSanitizer; @@ -77,4 +79,32 @@ public static void disableButtons(@NotNull Message message) { return MarkdownSanitizer.escape(text.replace("\\", "\\\\")); } + /** + * Instead of always queuing the reply message you can just make a method which queues + * automatically. + * + * @param message the message that you want to send + */ + public static void reply(String message, @NotNull SlashCommandEvent event) { + event.reply(message).queue(); + } + + public static void reply(String message, @NotNull CommandInteraction event) { + event.reply(message).queue(); + } + + /** + * Instead of always setting ephemeral as true making one method and using it makes life easier. + * + * @param message the message that you want to send + * @param event The slash command event + */ + public static void replyEphemeral(String message, @NotNull SlashCommandEvent event) { + event.reply(message).setEphemeral(true).queue(); + } + + public static void replyEphemeral(String message, @NotNull CommandInteraction event) { + event.reply(message).setEphemeral(true).queue(); + } + } diff --git a/application/src/main/resources/db/V5__Add_Warn_System.sql b/application/src/main/resources/db/V5__Add_Warn_System.sql index 6a6cce05da..c7f39d9958 100644 --- a/application/src/main/resources/db/V5__Add_Warn_System.sql +++ b/application/src/main/resources/db/V5__Add_Warn_System.sql @@ -1,10 +1,11 @@ CREATE TABLE warn_system ( /** - This was taken from Yusuf's Moderation bot. I the owner allow this. - */ - userid BIGINT NOT NULL PRIMARY KEY, + * This was taken from https://github.com/YusufsDiscordbot/Yusuf-s-Moderation-Bot and changed. + */ + userid BIGINT NOT NULL UNIQUE PRIMARY KEY, guild_id BIGINT NOT NULL, - warn_reason TEXT DEFAULT 'This user has been warned for breaking one of the rules.', + warn_reason TEXT DEFAULT 'This user has been warned for breaking the rules.', + is_warned BIT DEFAULT FALSE, warning_amount INTEGER DEFAULT 0 ) \ No newline at end of file diff --git a/application/src/main/resources/db/V6__Add_Ban_System.sql b/application/src/main/resources/db/V6__Add_Ban_System.sql index be169f52a3..9a0b6e9081 100644 --- a/application/src/main/resources/db/V6__Add_Ban_System.sql +++ b/application/src/main/resources/db/V6__Add_Ban_System.sql @@ -1,10 +1,11 @@ CREATE TABLE ban_system ( /** - This was taken from Yusuf's Moderation bot. I the owner allow this. + * This was taken from https://github.com/YusufsDiscordbot/Yusuf-s-Moderation-Bot and changed. */ - userid BIGINT NOT NULL PRIMARY KEY, + userid BIGINT NOT NULL UNIQUE PRIMARY KEY, guild_id BIGINT NOT NULL, author_id BIGINT NOT NULL, - ban_reason TEXT DEFAULT 'This user has been banned for breaking one of the rules.' + is_banned BIT DEFAULT FALSE, + ban_reason TEXT DEFAULT 'This user has been banned for breaking the rules.' ) \ No newline at end of file diff --git a/application/src/main/resources/db/V7__Add_Kick_System.sql b/application/src/main/resources/db/V7__Add_Kick_System.sql index ccb6fea018..d4b16d07fb 100644 --- a/application/src/main/resources/db/V7__Add_Kick_System.sql +++ b/application/src/main/resources/db/V7__Add_Kick_System.sql @@ -1,10 +1,11 @@ CREATE TABLE kick_system ( /** - This was taken from Yusuf's Moderation bot. I the owner allow this. + * This was taken from https://github.com/YusufsDiscordbot/Yusuf-s-Moderation-Bot and changed. */ - userid BIGINT NOT NULL PRIMARY KEY, + userid BIGINT NOT NULL UNIQUE PRIMARY KEY, guild_id BIGINT NOT NULL, author_id BIGINT NOT NULL, - kick_reason TEXT DEFAULT 'This user has been kicked for breaking one of the rules.' + is_kicked BIT DEFAULT FALSE, + kick_reason TEXT DEFAULT 'This user has been kicked for breaking the rules.' ) \ No newline at end of file From 3282f9b4867345931ae16264d2c6cba8f5582006 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 18:05:16 +0000 Subject: [PATCH 21/50] Update AuditCommand.java --- .../commands/moderation/AuditCommand.java | 74 ++++++++++++++++++- 1 file changed, 73 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index 92b27397db..6f4e07185b 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -18,7 +18,9 @@ import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.BanSystem; import org.togetherjava.tjbot.db.generated.tables.WarnSystem; +import org.togetherjava.tjbot.db.generated.tables.records.BanSystemRecord; import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; import java.awt.*; @@ -94,7 +96,7 @@ private static boolean noValueFound(Optional value, @NotNull User target, Str //TODO add javadoc private void handleWarnCommand(@NotNull CommandInteraction event) { OptionMapping userOption = - Objects.requireNonNull(event.getOption(WARN_USER_OPTION), USER_IS_NULL; + Objects.requireNonNull(event.getOption(WARN_USER_OPTION), USER_IS_NULL); User target = userOption.getAsUser(); Guild guild = Objects.requireNonNull(event.getGuild()); @@ -164,6 +166,16 @@ private void handleKickCommand(@NotNull CommandInteraction event) { Objects.requireNonNull(event.getOption(KICK_USER_OPTION), USER_IS_NULL); User target = userOption.getAsUser(); Guild guild = Objects.requireNonNull(event.getGuild()); + + Member bot = guild.getSelfMember(); + Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); + + if (!handleChecks(bot, author, guild, event)) { + return; + } + + Long guildId = guild.getIdLong(); + Long userId = target.getIdLong(); } //TODO add javadoc @@ -172,8 +184,68 @@ private void handleBanCommand(@NotNull CommandInteraction event) { Objects.requireNonNull(event.getOption(BAN_USER_OPTION), USER_IS_NULL); User target = userOption.getAsUser(); Guild guild = Objects.requireNonNull(event.getGuild()); + + Member bot = guild.getSelfMember(); + Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); + + if (!handleChecks(bot, author, guild, event)) { + return; + } + + Long guildId = guild.getIdLong(); + Long userId = target.getIdLong(); + Optional banReason = database.read(context -> { + try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { + return Optional + .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) + .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(BanSystemRecord::getBanReason); + } + }); + + Optional AuthorId = database.read(context -> { + try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { + return Optional + .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) + .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(BanSystemRecord::getAuthorId); + } + }); + + String banned = "banned"; + try { + Optional isBanned = database.read(context -> { + try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { + return Optional + .ofNullable( + select + .where(BanSystem.BAN_SYSTEM.USERID.eq(userId) + .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))) + .fetchOne()) + .map(BanSystemRecord::getIsBanned); + } + }); + if (!noValueFound(isBanned, target, banned, event) + && !noValueFound(banReason, target, banned, event) + && !noValueFound(AuthorId, target, banned, event)) { + return; + } + + event + .replyEmbeds(new EmbedBuilder().setTitle("Null") + .setDescription("The user " + target.getAsTag() + " was banned for the reason" + banReason + + " by " + AuthorId) + .setColor(Color.decode("#895FE8")) + .build()) + .setEphemeral(true) + .queue(); + } catch (Exception exception) { + logger.error("Failed to check if the user is warned", exception); + replyEphemeral("Failed to check if the user is warned", event); + } } + private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @NotNull Guild guild, @NotNull Interaction event) { From c39aeb153a5a1aac4a2763a81f541c57a03f1c9b Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 18:37:12 +0000 Subject: [PATCH 22/50] finished the making of the audit command --- .../commands/moderation/AuditCommand.java | 173 +++++++++++++----- 1 file changed, 129 insertions(+), 44 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index 6f4e07185b..1cf354c692 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -19,8 +19,10 @@ import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.db.Database; import org.togetherjava.tjbot.db.generated.tables.BanSystem; +import org.togetherjava.tjbot.db.generated.tables.KickSystem; import org.togetherjava.tjbot.db.generated.tables.WarnSystem; import org.togetherjava.tjbot.db.generated.tables.records.BanSystemRecord; +import org.togetherjava.tjbot.db.generated.tables.records.KickSystemRecord; import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; import java.awt.*; @@ -31,7 +33,10 @@ import static org.togetherjava.tjbot.commands.utils.MessageUtils.replyEphemeral; -//TODO add javadoc +/** + * This command can be used to retrieve data for moderation commands. For example this command + * allows you to retrieve how many warns a certain user has. + */ public class AuditCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(AuditCommand.class); private static final String ACTION_VERB = "audit"; @@ -43,8 +48,12 @@ public class AuditCommand extends SlashCommandAdapter { private static final String BAN_USER_OPTION = "user"; private static final String DESCRIPTION = "The user who you want to get the values for"; private static final String USER_IS_NULL = "The user is null"; + private static final String THE_USER = "the user "; + private static final String COLOR_CODE = "#895FE8"; private final Database database; - private final Predicate hasRequiredRole; + private final Predicate hasKickANDWarnRequiredRole; + private final Predicate hasBanRequiredRole; + /** * Creates a new adapter with the given data. @@ -63,7 +72,11 @@ public AuditCommand(Database database) { new SubcommandData(COMMAND_BAN, "Gets the ban values for that user") .addOption(OptionType.USER, BAN_USER_OPTION, DESCRIPTION, true)); - hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) + hasKickANDWarnRequiredRole = + Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) + .asMatchPredicate(); + + hasBanRequiredRole = Pattern.compile(Config.getInstance().getHeavyModerationRolePattern()) .asMatchPredicate(); } @@ -77,14 +90,13 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { } } - private static boolean noValueFound(Optional value, @NotNull User target, String commandName, - @NotNull CommandInteraction event) { + private static boolean noValueFound(@NotNull Optional value, @NotNull User target, + String commandName, @NotNull CommandInteraction event) { if (value.isEmpty()) { event .replyEmbeds(new EmbedBuilder().setTitle("Null") - .setDescription( - "The user " + target.getAsTag() + " has never been " + commandName) - .setColor(Color.decode("#895FE8")) + .setDescription(THE_USER + target.getAsTag() + " has never been " + commandName) + .setColor(Color.decode(COLOR_CODE)) .build()) .setEphemeral(true) .queue(); @@ -93,7 +105,14 @@ private static boolean noValueFound(Optional value, @NotNull User target, Str return true; } - //TODO add javadoc + /** + * This command allows you to retrieve the amount of warns a user has and the reason for the + * warns. This command only requires you to input the user as seen here + * {@code /audit warn @user}. To be able to use this command you need to have the role + * {@code @softModerationRolePattern} or have the permissions to be able to kick members. + * + * @param event the event of the command + */ private void handleWarnCommand(@NotNull CommandInteraction event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(WARN_USER_OPTION), USER_IS_NULL); @@ -103,7 +122,8 @@ private void handleWarnCommand(@NotNull CommandInteraction event) { Member bot = guild.getSelfMember(); Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); - if (!handleChecks(bot, author, guild, event)) { + if (!handleChecks(bot, author, guild, event, Permission.KICK_MEMBERS, + hasKickANDWarnRequiredRole)) { return; } @@ -148,9 +168,9 @@ private void handleWarnCommand(@NotNull CommandInteraction event) { event .replyEmbeds(new EmbedBuilder().setTitle("Null") - .setDescription("The user " + target.getAsTag() + " has " + amountOfWarns + .setDescription(THE_USER + target.getAsTag() + " has " + amountOfWarns + "for the reasons " + warnReason) - .setColor(Color.decode("#895FE8")) + .setColor(Color.decode(COLOR_CODE)) .build()) .setEphemeral(true) .queue(); @@ -160,7 +180,16 @@ private void handleWarnCommand(@NotNull CommandInteraction event) { } } - //TODO add javadoc + /** + * This command gives you the ability to retrieve the reason why the user was kicked and who the + * user was kicked by. To uses this command all you have to do is input the user as seen here + * {@code /audit kick @user}. + * + * To be able to use this command you need to have the role {@code @softModerationRolePattern} + * or have the permissions to be able to kick members. + * + * @param event the event of the command + */ private void handleKickCommand(@NotNull CommandInteraction event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(KICK_USER_OPTION), USER_IS_NULL); @@ -170,15 +199,74 @@ private void handleKickCommand(@NotNull CommandInteraction event) { Member bot = guild.getSelfMember(); Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); - if (!handleChecks(bot, author, guild, event)) { + if (!handleChecks(bot, author, guild, event, Permission.KICK_MEMBERS, + hasKickANDWarnRequiredRole)) { return; } Long guildId = guild.getIdLong(); Long userId = target.getIdLong(); + Optional kickReason = database.read(context -> { + try (var select = context.selectFrom(KickSystem.KICK_SYSTEM)) { + return Optional + .ofNullable(select.where(KickSystem.KICK_SYSTEM.USERID.eq(userId) + .and(KickSystem.KICK_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(KickSystemRecord::getKickReason); + } + }); + + Optional kickAuthorId = database.read(context -> { + try (var select = context.selectFrom(KickSystem.KICK_SYSTEM)) { + return Optional + .ofNullable(select.where(KickSystem.KICK_SYSTEM.USERID.eq(userId) + .and(KickSystem.KICK_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(KickSystemRecord::getAuthorId); + } + }); + + String kicked = "kicked"; + try { + Optional isKicked = database.read(context -> { + try (var select = context.selectFrom(KickSystem.KICK_SYSTEM)) { + return Optional + .ofNullable( + select + .where(KickSystem.KICK_SYSTEM.USERID.eq(userId) + .and(KickSystem.KICK_SYSTEM.GUILD_ID.eq(guildId))) + .fetchOne()) + .map(KickSystemRecord::getIsKicked); + } + }); + if (!noValueFound(isKicked, target, kicked, event) + && !noValueFound(kickReason, target, kicked, event) + && !noValueFound(kickAuthorId, target, kicked, event)) { + return; + } + + event + .replyEmbeds(new EmbedBuilder().setTitle("Null") + .setDescription("The user " + target.getAsTag() + " was kicked for the reason" + + kickReason + " by " + kickAuthorId) + .setColor(Color.decode(COLOR_CODE)) + .build()) + .setEphemeral(true) + .queue(); + } catch (Exception exception) { + logger.error("Failed to check if the user is kicked", exception); + replyEphemeral("Failed to check if the user is kicked", event); + } } - //TODO add javadoc + /** + * This command gives you the ability to retrieve the reason why the user was banned and who the + * user was banned by. To uses this command all you have to do is input the user as seen here + * {@code /audit ban @user}. + * + * To be able to use this command you need to have the role {@code @heavyModerationRolePattern} + * or have the permissions to be able to ban members. + * + * @param event the event of the command + */ private void handleBanCommand(@NotNull CommandInteraction event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(BAN_USER_OPTION), USER_IS_NULL); @@ -188,7 +276,7 @@ private void handleBanCommand(@NotNull CommandInteraction event) { Member bot = guild.getSelfMember(); Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); - if (!handleChecks(bot, author, guild, event)) { + if (!handleChecks(bot, author, guild, event, Permission.BAN_MEMBERS, hasBanRequiredRole)) { return; } @@ -197,18 +285,18 @@ private void handleBanCommand(@NotNull CommandInteraction event) { Optional banReason = database.read(context -> { try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { return Optional - .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) - .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(BanSystemRecord::getBanReason); + .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) + .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(BanSystemRecord::getBanReason); } }); - Optional AuthorId = database.read(context -> { + Optional banAuthorId = database.read(context -> { try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { return Optional - .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) - .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(BanSystemRecord::getAuthorId); + .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) + .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(BanSystemRecord::getAuthorId); } }); @@ -217,46 +305,43 @@ private void handleBanCommand(@NotNull CommandInteraction event) { Optional isBanned = database.read(context -> { try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { return Optional - .ofNullable( - select - .where(BanSystem.BAN_SYSTEM.USERID.eq(userId) - .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))) - .fetchOne()) - .map(BanSystemRecord::getIsBanned); + .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) + .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) + .map(BanSystemRecord::getIsBanned); } }); if (!noValueFound(isBanned, target, banned, event) && !noValueFound(banReason, target, banned, event) - && !noValueFound(AuthorId, target, banned, event)) { + && !noValueFound(banAuthorId, target, banned, event)) { return; } event - .replyEmbeds(new EmbedBuilder().setTitle("Null") - .setDescription("The user " + target.getAsTag() + " was banned for the reason" + banReason - + " by " + AuthorId) - .setColor(Color.decode("#895FE8")) - .build()) - .setEphemeral(true) - .queue(); + .replyEmbeds(new EmbedBuilder().setTitle("Null") + .setDescription("The user " + target.getAsTag() + " was banned for the reason" + + banReason + " by " + banAuthorId) + .setColor(Color.decode(COLOR_CODE)) + .build()) + .setEphemeral(true) + .queue(); } catch (Exception exception) { - logger.error("Failed to check if the user is warned", exception); - replyEphemeral("Failed to check if the user is warned", event); + logger.error("Failed to check if the user is banned", exception); + replyEphemeral("Failed to check if the user is banned", event); } } private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @NotNull Guild guild, - @NotNull Interaction event) { + @NotNull Interaction event, Permission permission, + @NotNull Predicate hasRequiredRole) { if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { return false; } - if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.KICK_MEMBERS, bot, - guild, event)) { + if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, permission, bot, guild, event)) { return false; } - return ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, Permission.KICK_MEMBERS, - author, guild, event); + return ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, permission, author, guild, + event); } } From 9f7fc1cf316e50373065d7a6f34b36f683ec973e Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 18:42:28 +0000 Subject: [PATCH 23/50] Some minor changes --- .../commands/moderation/AuditCommand.java | 45 ++++++++++--------- .../commands/moderation/WarnCommand.java | 4 +- 2 files changed, 25 insertions(+), 24 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index 1cf354c692..f1528ca786 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -40,14 +40,15 @@ public class AuditCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(AuditCommand.class); private static final String ACTION_VERB = "audit"; - private static final String COMMAND_WARN = "warn"; + private static final String WARN_SUBCOMMAND = "warn"; private static final String WARN_USER_OPTION = "user"; - private static final String COMMAND_KICK = "kick"; + private static final String KICK_SUBCOMMAND = "kick"; private static final String KICK_USER_OPTION = "user"; - private static final String COMMAND_BAN = "ban"; + private static final String BAN_SUBCOMMAND = "ban"; private static final String BAN_USER_OPTION = "user"; private static final String DESCRIPTION = "The user who you want to get the values for"; - private static final String USER_IS_NULL = "The user is null"; + private static final String OPTION_IS_NULL = "The option is null"; + private static final String GUILD_IS_NULL = "he guild is null"; private static final String THE_USER = "the user "; private static final String COLOR_CODE = "#895FE8"; private final Database database; @@ -65,11 +66,11 @@ public AuditCommand(Database database) { this.database = database; getData().addSubcommands( - new SubcommandData(COMMAND_WARN, "Gets the warn values for that user") + new SubcommandData(WARN_SUBCOMMAND, "Gets the warn values for that user") .addOption(OptionType.USER, WARN_USER_OPTION, DESCRIPTION, true), - new SubcommandData(COMMAND_KICK, "Gets the kick values for that user") + new SubcommandData(KICK_SUBCOMMAND, "Gets the kick values for that user") .addOption(OptionType.USER, KICK_USER_OPTION, DESCRIPTION, true), - new SubcommandData(COMMAND_BAN, "Gets the ban values for that user") + new SubcommandData(BAN_SUBCOMMAND, "Gets the ban values for that user") .addOption(OptionType.USER, BAN_USER_OPTION, DESCRIPTION, true)); hasKickANDWarnRequiredRole = @@ -83,9 +84,9 @@ public AuditCommand(Database database) { @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { switch (Objects.requireNonNull(event.getSubcommandName())) { - case COMMAND_WARN -> handleWarnCommand(event); - case COMMAND_KICK -> handleKickCommand(event); - case COMMAND_BAN -> handleBanCommand(event); + case WARN_SUBCOMMAND -> handleWarnSubCommand(event); + case KICK_SUBCOMMAND -> handleKickSubCommand(event); + case BAN_SUBCOMMAND -> handleBanSubCommand(event); default -> throw new AssertionError(); } } @@ -113,14 +114,14 @@ private static boolean noValueFound(@NotNull Optional value, @NotNull Use * * @param event the event of the command */ - private void handleWarnCommand(@NotNull CommandInteraction event) { + private void handleWarnSubCommand(@NotNull CommandInteraction event) { OptionMapping userOption = - Objects.requireNonNull(event.getOption(WARN_USER_OPTION), USER_IS_NULL); + Objects.requireNonNull(event.getOption(WARN_USER_OPTION), OPTION_IS_NULL); User target = userOption.getAsUser(); - Guild guild = Objects.requireNonNull(event.getGuild()); + Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); Member bot = guild.getSelfMember(); - Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); + Member author = Objects.requireNonNull(event.getMember(), OPTION_IS_NULL); if (!handleChecks(bot, author, guild, event, Permission.KICK_MEMBERS, hasKickANDWarnRequiredRole)) { @@ -190,14 +191,14 @@ private void handleWarnCommand(@NotNull CommandInteraction event) { * * @param event the event of the command */ - private void handleKickCommand(@NotNull CommandInteraction event) { + private void handleKickSubCommand(@NotNull CommandInteraction event) { OptionMapping userOption = - Objects.requireNonNull(event.getOption(KICK_USER_OPTION), USER_IS_NULL); + Objects.requireNonNull(event.getOption(KICK_USER_OPTION), OPTION_IS_NULL); User target = userOption.getAsUser(); - Guild guild = Objects.requireNonNull(event.getGuild()); + Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); Member bot = guild.getSelfMember(); - Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); + Member author = Objects.requireNonNull(event.getMember(), OPTION_IS_NULL); if (!handleChecks(bot, author, guild, event, Permission.KICK_MEMBERS, hasKickANDWarnRequiredRole)) { @@ -267,14 +268,14 @@ private void handleKickCommand(@NotNull CommandInteraction event) { * * @param event the event of the command */ - private void handleBanCommand(@NotNull CommandInteraction event) { + private void handleBanSubCommand(@NotNull CommandInteraction event) { OptionMapping userOption = - Objects.requireNonNull(event.getOption(BAN_USER_OPTION), USER_IS_NULL); + Objects.requireNonNull(event.getOption(BAN_USER_OPTION), OPTION_IS_NULL); User target = userOption.getAsUser(); - Guild guild = Objects.requireNonNull(event.getGuild()); + Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); Member bot = guild.getSelfMember(); - Member author = Objects.requireNonNull(event.getMember(), USER_IS_NULL); + Member author = Objects.requireNonNull(event.getMember(), OPTION_IS_NULL); if (!handleChecks(bot, author, guild, event, Permission.BAN_MEMBERS, hasBanRequiredRole)) { return; diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index cf827fcbc6..df14cf5c8b 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -115,11 +115,11 @@ private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping userOption = - Objects.requireNonNull(event.getOption(USER_OPTION), "The user is null"); + Objects.requireNonNull(event.getOption(USER_OPTION), "The option is null"); User target = userOption.getAsUser(); Member targetMember = userOption.getAsMember(); Member author = Objects.requireNonNull(event.getMember(), "The author is null"); - Guild guild = Objects.requireNonNull(event.getGuild()); + Guild guild = Objects.requireNonNull(event.getGuild(), "The guild is null"); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") .getAsString(); From 199f57e4080a0bb7d08058dab524d69205679431 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 18:47:01 +0000 Subject: [PATCH 24/50] trying to fix the duplicates --- .../tjbot/commands/moderation/AuditCommand.java | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index f1528ca786..e8e0e0170e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -115,9 +115,9 @@ private static boolean noValueFound(@NotNull Optional value, @NotNull Use * @param event the event of the command */ private void handleWarnSubCommand(@NotNull CommandInteraction event) { - OptionMapping userOption = + OptionMapping warnUserOption = Objects.requireNonNull(event.getOption(WARN_USER_OPTION), OPTION_IS_NULL); - User target = userOption.getAsUser(); + User target = warnUserOption.getAsUser(); Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); Member bot = guild.getSelfMember(); @@ -192,9 +192,9 @@ private void handleWarnSubCommand(@NotNull CommandInteraction event) { * @param event the event of the command */ private void handleKickSubCommand(@NotNull CommandInteraction event) { - OptionMapping userOption = + OptionMapping kickUserOption = Objects.requireNonNull(event.getOption(KICK_USER_OPTION), OPTION_IS_NULL); - User target = userOption.getAsUser(); + User target = kickUserOption.getAsUser(); Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); Member bot = guild.getSelfMember(); @@ -269,9 +269,9 @@ private void handleKickSubCommand(@NotNull CommandInteraction event) { * @param event the event of the command */ private void handleBanSubCommand(@NotNull CommandInteraction event) { - OptionMapping userOption = + OptionMapping banUserOption = Objects.requireNonNull(event.getOption(BAN_USER_OPTION), OPTION_IS_NULL); - User target = userOption.getAsUser(); + User target = banUserOption.getAsUser(); Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); Member bot = guild.getSelfMember(); From baaee680ae76693e2ace7b8571f5cb3e01de6d9f Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 19:16:24 +0000 Subject: [PATCH 25/50] tweaked the dm for the warn command --- .../commands/moderation/AuditCommand.java | 29 +++++++++---------- .../commands/moderation/WarnCommand.java | 2 +- 2 files changed, 15 insertions(+), 16 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index e8e0e0170e..cad4f63075 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -106,6 +106,20 @@ private static boolean noValueFound(@NotNull Optional value, @NotNull Use return true; } + private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @NotNull Guild guild, + @NotNull Interaction event, Permission permission, + @NotNull Predicate hasRequiredRole) { + + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { + return false; + } + if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, permission, bot, guild, event)) { + return false; + } + return ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, permission, author, guild, + event); + } + /** * This command allows you to retrieve the amount of warns a user has and the reason for the * warns. This command only requires you to input the user as seen here @@ -330,19 +344,4 @@ private void handleBanSubCommand(@NotNull CommandInteraction event) { replyEphemeral("Failed to check if the user is banned", event); } } - - - private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @NotNull Guild guild, - @NotNull Interaction event, Permission permission, - @NotNull Predicate hasRequiredRole) { - - if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { - return false; - } - if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, permission, bot, guild, event)) { - return false; - } - return ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, permission, author, guild, - event); - } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index df14cf5c8b..72e1db3d25 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -62,7 +62,7 @@ private static RestAction dmUser(long userId, @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { return event.getJDA() .openPrivateChannelById(userId) - .flatMap(channel -> channel.sendMessageEmbeds(new EmbedBuilder().setTitle("Warn") + .flatMap(privateChannel -> event.replyEmbeds(new EmbedBuilder().setTitle("Warned") .setDescription("You have been warned in " + guild.getName() + " for " + reason) .setColor(Color.decode("#895FE8")) .build())) From f65895140212d51dd63375cabc0acf9dccda4812 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 19:24:52 +0000 Subject: [PATCH 26/50] added a missing @NotNull --- .../togetherjava/tjbot/commands/moderation/WarnCommand.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 72e1db3d25..4a94d8de03 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -58,8 +58,8 @@ public WarnCommand(@NotNull Database database) { .asMatchPredicate(); } - private static RestAction dmUser(long userId, @NotNull String reason, - @NotNull Guild guild, @NotNull SlashCommandEvent event) { + private static @NotNull RestAction dmUser(long userId, @NotNull String reason, + @NotNull Guild guild, @NotNull SlashCommandEvent event) { return event.getJDA() .openPrivateChannelById(userId) .flatMap(privateChannel -> event.replyEmbeds(new EmbedBuilder().setTitle("Warned") From af69a9ffbb69e0208ccde1b214abdf86c6f0a338 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 19:41:15 +0000 Subject: [PATCH 27/50] spotlessApply --- .../org/togetherjava/tjbot/commands/moderation/WarnCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 4a94d8de03..ebbdddf712 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -59,7 +59,7 @@ public WarnCommand(@NotNull Database database) { } private static @NotNull RestAction dmUser(long userId, @NotNull String reason, - @NotNull Guild guild, @NotNull SlashCommandEvent event) { + @NotNull Guild guild, @NotNull SlashCommandEvent event) { return event.getJDA() .openPrivateChannelById(userId) .flatMap(privateChannel -> event.replyEmbeds(new EmbedBuilder().setTitle("Warned") From d1251226676f84f1d63ebbe827939ebf4db19149 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Wed, 17 Nov 2021 20:49:50 +0000 Subject: [PATCH 28/50] Some minor changes --- .../commands/moderation/AuditCommand.java | 25 ++++++++++--------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index cad4f63075..24e7537474 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -42,10 +42,13 @@ public class AuditCommand extends SlashCommandAdapter { private static final String ACTION_VERB = "audit"; private static final String WARN_SUBCOMMAND = "warn"; private static final String WARN_USER_OPTION = "user"; + private static final String WARNED = "warned"; private static final String KICK_SUBCOMMAND = "kick"; private static final String KICK_USER_OPTION = "user"; + private static final String KICKED = "kicked"; private static final String BAN_SUBCOMMAND = "ban"; private static final String BAN_USER_OPTION = "user"; + private static final String BANNED = "banned"; private static final String DESCRIPTION = "The user who you want to get the values for"; private static final String OPTION_IS_NULL = "The option is null"; private static final String GUILD_IS_NULL = "he guild is null"; @@ -162,7 +165,6 @@ private void handleWarnSubCommand(@NotNull CommandInteraction event) { } }); - String warned = "warned"; try { Optional isWarned = database.read(context -> { try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { @@ -175,9 +177,10 @@ private void handleWarnSubCommand(@NotNull CommandInteraction event) { .map(WarnSystemRecord::getIsWarned); } }); - if (!noValueFound(isWarned, target, warned, event) - && !noValueFound(amountOfWarns, target, warned, event) - && !noValueFound(warnReason, target, warned, event)) { + + if (!noValueFound(isWarned, target, WARNED, event) + && !noValueFound(amountOfWarns, target, WARNED, event) + && !noValueFound(warnReason, target, WARNED, event)) { return; } @@ -239,7 +242,6 @@ private void handleKickSubCommand(@NotNull CommandInteraction event) { } }); - String kicked = "kicked"; try { Optional isKicked = database.read(context -> { try (var select = context.selectFrom(KickSystem.KICK_SYSTEM)) { @@ -252,9 +254,9 @@ private void handleKickSubCommand(@NotNull CommandInteraction event) { .map(KickSystemRecord::getIsKicked); } }); - if (!noValueFound(isKicked, target, kicked, event) - && !noValueFound(kickReason, target, kicked, event) - && !noValueFound(kickAuthorId, target, kicked, event)) { + if (!noValueFound(isKicked, target, KICKED, event) + && !noValueFound(kickReason, target, KICKED, event) + && !noValueFound(kickAuthorId, target, KICKED, event)) { return; } @@ -315,7 +317,6 @@ private void handleBanSubCommand(@NotNull CommandInteraction event) { } }); - String banned = "banned"; try { Optional isBanned = database.read(context -> { try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { @@ -325,9 +326,9 @@ private void handleBanSubCommand(@NotNull CommandInteraction event) { .map(BanSystemRecord::getIsBanned); } }); - if (!noValueFound(isBanned, target, banned, event) - && !noValueFound(banReason, target, banned, event) - && !noValueFound(banAuthorId, target, banned, event)) { + if (!noValueFound(isBanned, target, BANNED, event) + && !noValueFound(banReason, target, BANNED, event) + && !noValueFound(banAuthorId, target, BANNED, event)) { return; } From 73383460aabf5835d07346e50c40f1cf41ca87d1 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Thu, 18 Nov 2021 07:25:43 +0000 Subject: [PATCH 29/50] minor change --- .../togetherjava/tjbot/commands/moderation/WarnCommand.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index ebbdddf712..82e0aea594 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -145,7 +145,6 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { } }); - int newWarnAmount = oldWarnAmount.orElse(0) + 1; try { database.write(context -> { WarnSystemRecord warnSystemRecord = context.newRecord(WarnSystem.WARN_SYSTEM) @@ -153,7 +152,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { .setGuildId(guildId) .setWarnReason(reason) .setIsWarned(true) - .setWarningAmount(newWarnAmount); + .setWarningAmount(oldWarnAmount.orElse(0) + 1); if (warnSystemRecord.update() == 0) { warnSystemRecord.insert(); } From 377e8ed8866faafac5758232d8dea9855988d11c Mon Sep 17 00:00:00 2001 From: Yusuf Date: Thu, 2 Dec 2021 21:14:15 +0000 Subject: [PATCH 30/50] bug --- .../commands/moderation/AuditCommand.java | 4 +-- .../tjbot/commands/moderation/BanCommand.java | 10 ++++---- .../commands/moderation/KickCommand.java | 2 +- .../commands/moderation/ModerationUtils.java | 25 +++++++++++++++++++ .../commands/moderation/WarnCommand.java | 7 +++--- .../main/resources/db/V5__Add_Ban_System.sql | 9 +++++++ .../main/resources/db/V5__Add_Kick_System.sql | 9 +++++++ .../main/resources/db/V5__Add_Warn_System.sql | 9 +++---- .../main/resources/db/V6__Add_Ban_System.sql | 11 -------- .../main/resources/db/V7__Add_Kick_System.sql | 11 -------- 10 files changed, 58 insertions(+), 39 deletions(-) create mode 100644 application/src/main/resources/db/V5__Add_Ban_System.sql create mode 100644 application/src/main/resources/db/V5__Add_Kick_System.sql delete mode 100644 application/src/main/resources/db/V6__Add_Ban_System.sql delete mode 100644 application/src/main/resources/db/V7__Add_Kick_System.sql diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java index 24e7537474..369b41b657 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java @@ -64,7 +64,7 @@ public class AuditCommand extends SlashCommandAdapter { * * @param database used to retrieve the user data for the moderation commands */ - public AuditCommand(Database database) { + public AuditCommand(@NotNull Database database) { super(ACTION_VERB, "get the audit for the commands", SlashCommandVisibility.GUILD); this.database = database; @@ -150,7 +150,7 @@ private void handleWarnSubCommand(@NotNull CommandInteraction event) { Optional amountOfWarns = database.read(context -> { try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { return Optional - .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USERID.eq(userId) + .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USER_ID.eq(userId) .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) .map(WarnSystemRecord::getWarningAmount); } 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 index f4daf25a63..929c3a1f6f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -53,7 +53,7 @@ public final class BanCommand extends SlashCommandAdapter { * * @param database used to store the bans in the database */ - public BanCommand(Database database) { + public BanCommand(@NotNull Database database) { super(COMMAND_NAME, "Bans the given user from the server", SlashCommandVisibility.GUILD); this.database = database; @@ -204,11 +204,11 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { try { database.write(context -> { BanSystemRecord banSystemRecord = context.newRecord(BanSystem.BAN_SYSTEM) - .setUserid(target.getIdLong()) - .setAuthorId(author.getIdLong()) + .setCaseId(1) + .setUserId(target.getIdLong()) .setGuildId(guild.getIdLong()) - .setIsBanned(true) - .setBanReason(reason); + .setBanReason(reason) + .setActionType(ModerationUtils.Action.BAN.getVerb()); if (banSystemRecord.update() == 0) { banSystemRecord.insert(); } 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 index f3eaa88713..19378f198f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java @@ -46,7 +46,7 @@ public final class KickCommand extends SlashCommandAdapter { * * @param database used to store the kicks in the database */ - public KickCommand(Database database) { + public KickCommand(@NotNull Database database) { super(COMMAND_NAME, "Kicks the given user from the server", SlashCommandVisibility.GUILD); this.database = database; 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 index 335e25783c..3ae413246b 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -6,8 +6,13 @@ import net.dv8tion.jda.api.interactions.Interaction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import org.jooq.UpdatableRecord; +import org.jooq.impl.UpdatableRecordImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.db.Database; +import org.togetherjava.tjbot.db.generated.tables.BanSystem; +import org.togetherjava.tjbot.db.generated.tables.records.BanSystemRecord; import java.awt.*; import java.time.Instant; @@ -49,6 +54,26 @@ static boolean handleReason(@NotNull CharSequence reason, @NotNull Interaction e return false; } + static void setModerationData(@NotNull Database database, User target, Guild guild, int CaseId, String reason, + Action action, UpdatableRecordImpl updateTableRecord, String commandName) { + try { + database.write(context -> { + UpdatableRecordImpl updatableRecordImpl = context.newRecord(updatableRecord.action) + .setCaseId(CaseId) + .setUserId(target.getIdLong()) + .setGuildId(guild.getIdLong()) + .setBanReason(reason) + .setActionType(action.getVerb()); + if (updatableRecordImpl.update() == 0) { + updatableRecordImpl.insert(); + } + }); + logger.info("Saved the user '{}' to the '{}' system.", target.getAsTag(), commandName); + } catch (Exception exception) { + exception.printStackTrace(); + } + } + /** * Checks whether the given author and bot can interact with the target user. For example * whether they have enough permissions to ban the user. diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 82e0aea594..c733b250ec 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -76,7 +76,7 @@ public WarnCommand(@NotNull Database database) { if (!hasSentDm) { dmNoticeText = "(Unable to send them a DM.)"; } - return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.BAN, + return ModerationUtils.createActionResponse(author.getUser(), ModerationUtils.Action.WARN, target, dmNoticeText, reason); } @@ -139,7 +139,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Optional oldWarnAmount = database.read(context -> { try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { return Optional - .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USERID.eq(userId) + .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USER_ID .eq(userId) .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) .map(WarnSystemRecord::getWarningAmount); } @@ -148,10 +148,9 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { try { database.write(context -> { WarnSystemRecord warnSystemRecord = context.newRecord(WarnSystem.WARN_SYSTEM) - .setUserid(target.getIdLong()) + .setUserId(target.getIdLong()) .setGuildId(guildId) .setWarnReason(reason) - .setIsWarned(true) .setWarningAmount(oldWarnAmount.orElse(0) + 1); if (warnSystemRecord.update() == 0) { warnSystemRecord.insert(); diff --git a/application/src/main/resources/db/V5__Add_Ban_System.sql b/application/src/main/resources/db/V5__Add_Ban_System.sql new file mode 100644 index 0000000000..74b5606de9 --- /dev/null +++ b/application/src/main/resources/db/V5__Add_Ban_System.sql @@ -0,0 +1,9 @@ +CREATE TABLE ban_system +( + case_id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id BIGINT NOT NULL, + guild_id BIGINT NOT NULL, + reason TEXT DEFAULT 'This user has been banned for breaking the rules.', + action_type TEXT DEFAULT 'warned', + timestamp TIMESTAMP NOT NULL +) \ No newline at end of file diff --git a/application/src/main/resources/db/V5__Add_Kick_System.sql b/application/src/main/resources/db/V5__Add_Kick_System.sql new file mode 100644 index 0000000000..63f7b68b88 --- /dev/null +++ b/application/src/main/resources/db/V5__Add_Kick_System.sql @@ -0,0 +1,9 @@ +CREATE TABLE kick_system +( + case_id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id BIGINT NOT NULL, + guild_id BIGINT NOT NULL, + reason TEXT DEFAULT 'This user has been kicked for breaking the rules.', + action_type TEXT DEFAULT 'warned', + timestamp TIMESTAMP NOT NULL +) \ No newline at end of file diff --git a/application/src/main/resources/db/V5__Add_Warn_System.sql b/application/src/main/resources/db/V5__Add_Warn_System.sql index c7f39d9958..1ff6fdcf7b 100644 --- a/application/src/main/resources/db/V5__Add_Warn_System.sql +++ b/application/src/main/resources/db/V5__Add_Warn_System.sql @@ -1,11 +1,10 @@ CREATE TABLE warn_system ( - /** - * This was taken from https://github.com/YusufsDiscordbot/Yusuf-s-Moderation-Bot and changed. - */ - userid BIGINT NOT NULL UNIQUE PRIMARY KEY, + case_id INTEGER PRIMARY KEY AUTOINCREMENT, + user_id BIGINT NOT NULL, guild_id BIGINT NOT NULL, warn_reason TEXT DEFAULT 'This user has been warned for breaking the rules.', - is_warned BIT DEFAULT FALSE, + action_type TEXT DEFAULT 'warned', + timestamp TIMESTAMP NOT NULL, warning_amount INTEGER DEFAULT 0 ) \ No newline at end of file diff --git a/application/src/main/resources/db/V6__Add_Ban_System.sql b/application/src/main/resources/db/V6__Add_Ban_System.sql deleted file mode 100644 index 9a0b6e9081..0000000000 --- a/application/src/main/resources/db/V6__Add_Ban_System.sql +++ /dev/null @@ -1,11 +0,0 @@ -CREATE TABLE ban_system -( - /** - * This was taken from https://github.com/YusufsDiscordbot/Yusuf-s-Moderation-Bot and changed. - */ - userid BIGINT NOT NULL UNIQUE PRIMARY KEY, - guild_id BIGINT NOT NULL, - author_id BIGINT NOT NULL, - is_banned BIT DEFAULT FALSE, - ban_reason TEXT DEFAULT 'This user has been banned for breaking the rules.' -) \ No newline at end of file diff --git a/application/src/main/resources/db/V7__Add_Kick_System.sql b/application/src/main/resources/db/V7__Add_Kick_System.sql deleted file mode 100644 index d4b16d07fb..0000000000 --- a/application/src/main/resources/db/V7__Add_Kick_System.sql +++ /dev/null @@ -1,11 +0,0 @@ -CREATE TABLE kick_system -( - /** - * This was taken from https://github.com/YusufsDiscordbot/Yusuf-s-Moderation-Bot and changed. - */ - userid BIGINT NOT NULL UNIQUE PRIMARY KEY, - guild_id BIGINT NOT NULL, - author_id BIGINT NOT NULL, - is_kicked BIT DEFAULT FALSE, - kick_reason TEXT DEFAULT 'This user has been kicked for breaking the rules.' -) \ No newline at end of file From 3bab6bbdd027875d603a46cd34253183719ee668 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 3 Dec 2021 13:18:22 +0000 Subject: [PATCH 31/50] removed audit command + fixed flywayMigrate error --- .../togetherjava/tjbot/commands/Commands.java | 1 - .../commands/moderation/AuditCommand.java | 348 ------------------ ...ick_System.sql => V6__Add_Kick_System.sql} | 0 ..._Ban_System.sql => V7__Add_Ban_System.sql} | 0 4 files changed, 349 deletions(-) delete mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java rename application/src/main/resources/db/{V5__Add_Kick_System.sql => V6__Add_Kick_System.sql} (100%) rename application/src/main/resources/db/{V5__Add_Ban_System.sql => V7__Add_Ban_System.sql} (100%) 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 7013d15a4c..5df25e3256 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -54,7 +54,6 @@ public enum Commands { commands.add(new BanCommand(database)); commands.add(new UnbanCommand()); commands.add(new WarnCommand(database)); - commands.add(new AuditCommand(database)); return commands; } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java deleted file mode 100644 index 369b41b657..0000000000 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/AuditCommand.java +++ /dev/null @@ -1,348 +0,0 @@ -package org.togetherjava.tjbot.commands.moderation; - -import net.dv8tion.jda.api.EmbedBuilder; -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.Interaction; -import net.dv8tion.jda.api.interactions.commands.CommandInteraction; -import net.dv8tion.jda.api.interactions.commands.OptionMapping; -import net.dv8tion.jda.api.interactions.commands.OptionType; -import net.dv8tion.jda.api.interactions.commands.build.SubcommandData; -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 org.togetherjava.tjbot.config.Config; -import org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.db.generated.tables.BanSystem; -import org.togetherjava.tjbot.db.generated.tables.KickSystem; -import org.togetherjava.tjbot.db.generated.tables.WarnSystem; -import org.togetherjava.tjbot.db.generated.tables.records.BanSystemRecord; -import org.togetherjava.tjbot.db.generated.tables.records.KickSystemRecord; -import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; - -import java.awt.*; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.regex.Pattern; - -import static org.togetherjava.tjbot.commands.utils.MessageUtils.replyEphemeral; - -/** - * This command can be used to retrieve data for moderation commands. For example this command - * allows you to retrieve how many warns a certain user has. - */ -public class AuditCommand extends SlashCommandAdapter { - private static final Logger logger = LoggerFactory.getLogger(AuditCommand.class); - private static final String ACTION_VERB = "audit"; - private static final String WARN_SUBCOMMAND = "warn"; - private static final String WARN_USER_OPTION = "user"; - private static final String WARNED = "warned"; - private static final String KICK_SUBCOMMAND = "kick"; - private static final String KICK_USER_OPTION = "user"; - private static final String KICKED = "kicked"; - private static final String BAN_SUBCOMMAND = "ban"; - private static final String BAN_USER_OPTION = "user"; - private static final String BANNED = "banned"; - private static final String DESCRIPTION = "The user who you want to get the values for"; - private static final String OPTION_IS_NULL = "The option is null"; - private static final String GUILD_IS_NULL = "he guild is null"; - private static final String THE_USER = "the user "; - private static final String COLOR_CODE = "#895FE8"; - private final Database database; - private final Predicate hasKickANDWarnRequiredRole; - private final Predicate hasBanRequiredRole; - - - /** - * Creates a new adapter with the given data. - * - * @param database used to retrieve the user data for the moderation commands - */ - public AuditCommand(@NotNull Database database) { - super(ACTION_VERB, "get the audit for the commands", SlashCommandVisibility.GUILD); - this.database = database; - - getData().addSubcommands( - new SubcommandData(WARN_SUBCOMMAND, "Gets the warn values for that user") - .addOption(OptionType.USER, WARN_USER_OPTION, DESCRIPTION, true), - new SubcommandData(KICK_SUBCOMMAND, "Gets the kick values for that user") - .addOption(OptionType.USER, KICK_USER_OPTION, DESCRIPTION, true), - new SubcommandData(BAN_SUBCOMMAND, "Gets the ban values for that user") - .addOption(OptionType.USER, BAN_USER_OPTION, DESCRIPTION, true)); - - hasKickANDWarnRequiredRole = - Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) - .asMatchPredicate(); - - hasBanRequiredRole = Pattern.compile(Config.getInstance().getHeavyModerationRolePattern()) - .asMatchPredicate(); - } - - @Override - public void onSlashCommand(@NotNull SlashCommandEvent event) { - switch (Objects.requireNonNull(event.getSubcommandName())) { - case WARN_SUBCOMMAND -> handleWarnSubCommand(event); - case KICK_SUBCOMMAND -> handleKickSubCommand(event); - case BAN_SUBCOMMAND -> handleBanSubCommand(event); - default -> throw new AssertionError(); - } - } - - private static boolean noValueFound(@NotNull Optional value, @NotNull User target, - String commandName, @NotNull CommandInteraction event) { - if (value.isEmpty()) { - event - .replyEmbeds(new EmbedBuilder().setTitle("Null") - .setDescription(THE_USER + target.getAsTag() + " has never been " + commandName) - .setColor(Color.decode(COLOR_CODE)) - .build()) - .setEphemeral(true) - .queue(); - return false; - } - return true; - } - - private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @NotNull Guild guild, - @NotNull Interaction event, Permission permission, - @NotNull Predicate hasRequiredRole) { - - if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { - return false; - } - if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, permission, bot, guild, event)) { - return false; - } - return ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, permission, author, guild, - event); - } - - /** - * This command allows you to retrieve the amount of warns a user has and the reason for the - * warns. This command only requires you to input the user as seen here - * {@code /audit warn @user}. To be able to use this command you need to have the role - * {@code @softModerationRolePattern} or have the permissions to be able to kick members. - * - * @param event the event of the command - */ - private void handleWarnSubCommand(@NotNull CommandInteraction event) { - OptionMapping warnUserOption = - Objects.requireNonNull(event.getOption(WARN_USER_OPTION), OPTION_IS_NULL); - User target = warnUserOption.getAsUser(); - Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); - - Member bot = guild.getSelfMember(); - Member author = Objects.requireNonNull(event.getMember(), OPTION_IS_NULL); - - if (!handleChecks(bot, author, guild, event, Permission.KICK_MEMBERS, - hasKickANDWarnRequiredRole)) { - return; - } - - Long guildId = guild.getIdLong(); - Long userId = target.getIdLong(); - Optional amountOfWarns = database.read(context -> { - try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { - return Optional - .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USER_ID.eq(userId) - .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(WarnSystemRecord::getWarningAmount); - } - }); - - Optional warnReason = database.read(context -> { - try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { - return Optional - .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USERID.eq(userId) - .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(WarnSystemRecord::getWarnReason); - } - }); - - try { - Optional isWarned = database.read(context -> { - try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { - return Optional - .ofNullable( - select - .where(WarnSystem.WARN_SYSTEM.USERID.eq(userId) - .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))) - .fetchOne()) - .map(WarnSystemRecord::getIsWarned); - } - }); - - if (!noValueFound(isWarned, target, WARNED, event) - && !noValueFound(amountOfWarns, target, WARNED, event) - && !noValueFound(warnReason, target, WARNED, event)) { - return; - } - - event - .replyEmbeds(new EmbedBuilder().setTitle("Null") - .setDescription(THE_USER + target.getAsTag() + " has " + amountOfWarns - + "for the reasons " + warnReason) - .setColor(Color.decode(COLOR_CODE)) - .build()) - .setEphemeral(true) - .queue(); - } catch (Exception exception) { - logger.error("Failed to check if the user is warned", exception); - replyEphemeral("Failed to check if the user is warned", event); - } - } - - /** - * This command gives you the ability to retrieve the reason why the user was kicked and who the - * user was kicked by. To uses this command all you have to do is input the user as seen here - * {@code /audit kick @user}. - * - * To be able to use this command you need to have the role {@code @softModerationRolePattern} - * or have the permissions to be able to kick members. - * - * @param event the event of the command - */ - private void handleKickSubCommand(@NotNull CommandInteraction event) { - OptionMapping kickUserOption = - Objects.requireNonNull(event.getOption(KICK_USER_OPTION), OPTION_IS_NULL); - User target = kickUserOption.getAsUser(); - Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); - - Member bot = guild.getSelfMember(); - Member author = Objects.requireNonNull(event.getMember(), OPTION_IS_NULL); - - if (!handleChecks(bot, author, guild, event, Permission.KICK_MEMBERS, - hasKickANDWarnRequiredRole)) { - return; - } - - Long guildId = guild.getIdLong(); - Long userId = target.getIdLong(); - Optional kickReason = database.read(context -> { - try (var select = context.selectFrom(KickSystem.KICK_SYSTEM)) { - return Optional - .ofNullable(select.where(KickSystem.KICK_SYSTEM.USERID.eq(userId) - .and(KickSystem.KICK_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(KickSystemRecord::getKickReason); - } - }); - - Optional kickAuthorId = database.read(context -> { - try (var select = context.selectFrom(KickSystem.KICK_SYSTEM)) { - return Optional - .ofNullable(select.where(KickSystem.KICK_SYSTEM.USERID.eq(userId) - .and(KickSystem.KICK_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(KickSystemRecord::getAuthorId); - } - }); - - try { - Optional isKicked = database.read(context -> { - try (var select = context.selectFrom(KickSystem.KICK_SYSTEM)) { - return Optional - .ofNullable( - select - .where(KickSystem.KICK_SYSTEM.USERID.eq(userId) - .and(KickSystem.KICK_SYSTEM.GUILD_ID.eq(guildId))) - .fetchOne()) - .map(KickSystemRecord::getIsKicked); - } - }); - if (!noValueFound(isKicked, target, KICKED, event) - && !noValueFound(kickReason, target, KICKED, event) - && !noValueFound(kickAuthorId, target, KICKED, event)) { - return; - } - - event - .replyEmbeds(new EmbedBuilder().setTitle("Null") - .setDescription("The user " + target.getAsTag() + " was kicked for the reason" - + kickReason + " by " + kickAuthorId) - .setColor(Color.decode(COLOR_CODE)) - .build()) - .setEphemeral(true) - .queue(); - } catch (Exception exception) { - logger.error("Failed to check if the user is kicked", exception); - replyEphemeral("Failed to check if the user is kicked", event); - } - } - - /** - * This command gives you the ability to retrieve the reason why the user was banned and who the - * user was banned by. To uses this command all you have to do is input the user as seen here - * {@code /audit ban @user}. - * - * To be able to use this command you need to have the role {@code @heavyModerationRolePattern} - * or have the permissions to be able to ban members. - * - * @param event the event of the command - */ - private void handleBanSubCommand(@NotNull CommandInteraction event) { - OptionMapping banUserOption = - Objects.requireNonNull(event.getOption(BAN_USER_OPTION), OPTION_IS_NULL); - User target = banUserOption.getAsUser(); - Guild guild = Objects.requireNonNull(event.getGuild(), GUILD_IS_NULL); - - Member bot = guild.getSelfMember(); - Member author = Objects.requireNonNull(event.getMember(), OPTION_IS_NULL); - - if (!handleChecks(bot, author, guild, event, Permission.BAN_MEMBERS, hasBanRequiredRole)) { - return; - } - - Long guildId = guild.getIdLong(); - Long userId = target.getIdLong(); - Optional banReason = database.read(context -> { - try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { - return Optional - .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) - .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(BanSystemRecord::getBanReason); - } - }); - - Optional banAuthorId = database.read(context -> { - try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { - return Optional - .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) - .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(BanSystemRecord::getAuthorId); - } - }); - - try { - Optional isBanned = database.read(context -> { - try (var select = context.selectFrom(BanSystem.BAN_SYSTEM)) { - return Optional - .ofNullable(select.where(BanSystem.BAN_SYSTEM.USERID.eq(userId) - .and(BanSystem.BAN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(BanSystemRecord::getIsBanned); - } - }); - if (!noValueFound(isBanned, target, BANNED, event) - && !noValueFound(banReason, target, BANNED, event) - && !noValueFound(banAuthorId, target, BANNED, event)) { - return; - } - - event - .replyEmbeds(new EmbedBuilder().setTitle("Null") - .setDescription("The user " + target.getAsTag() + " was banned for the reason" - + banReason + " by " + banAuthorId) - .setColor(Color.decode(COLOR_CODE)) - .build()) - .setEphemeral(true) - .queue(); - } catch (Exception exception) { - logger.error("Failed to check if the user is banned", exception); - replyEphemeral("Failed to check if the user is banned", event); - } - } -} diff --git a/application/src/main/resources/db/V5__Add_Kick_System.sql b/application/src/main/resources/db/V6__Add_Kick_System.sql similarity index 100% rename from application/src/main/resources/db/V5__Add_Kick_System.sql rename to application/src/main/resources/db/V6__Add_Kick_System.sql diff --git a/application/src/main/resources/db/V5__Add_Ban_System.sql b/application/src/main/resources/db/V7__Add_Ban_System.sql similarity index 100% rename from application/src/main/resources/db/V5__Add_Ban_System.sql rename to application/src/main/resources/db/V7__Add_Ban_System.sql From ccd07a6d38a01cd7d5f5d581bc5ec4b42becdd91 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 3 Dec 2021 13:31:59 +0000 Subject: [PATCH 32/50] spotless --- .../tjbot/commands/moderation/BanCommand.java | 4 ++-- .../commands/moderation/ModerationUtils.java | 18 ++++++++++-------- .../tjbot/commands/moderation/WarnCommand.java | 2 +- 3 files changed, 13 insertions(+), 11 deletions(-) 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 index 929c3a1f6f..5f7545b242 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -204,11 +204,11 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { try { database.write(context -> { BanSystemRecord banSystemRecord = context.newRecord(BanSystem.BAN_SYSTEM) - .setCaseId(1) + .setCaseId(1) .setUserId(target.getIdLong()) .setGuildId(guild.getIdLong()) .setBanReason(reason) - .setActionType(ModerationUtils.Action.BAN.getVerb()); + .setActionType(ModerationUtils.Action.BAN.getVerb()); if (banSystemRecord.update() == 0) { banSystemRecord.insert(); } 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 index 3ae413246b..8ac79c4993 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -54,16 +54,18 @@ static boolean handleReason(@NotNull CharSequence reason, @NotNull Interaction e return false; } - static void setModerationData(@NotNull Database database, User target, Guild guild, int CaseId, String reason, - Action action, UpdatableRecordImpl updateTableRecord, String commandName) { + static void setModerationData(@NotNull Database database, User target, Guild guild, + int CaseId, String reason, Action action, UpdatableRecordImpl updateTableRecord, + String commandName) { try { database.write(context -> { - UpdatableRecordImpl updatableRecordImpl = context.newRecord(updatableRecord.action) - .setCaseId(CaseId) - .setUserId(target.getIdLong()) - .setGuildId(guild.getIdLong()) - .setBanReason(reason) - .setActionType(action.getVerb()); + UpdatableRecordImpl updatableRecordImpl = + context.newRecord(updatableRecord.action) + .setCaseId(CaseId) + .setUserId(target.getIdLong()) + .setGuildId(guild.getIdLong()) + .setBanReason(reason) + .setActionType(action.getVerb()); if (updatableRecordImpl.update() == 0) { updatableRecordImpl.insert(); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index c733b250ec..0024181169 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -139,7 +139,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Optional oldWarnAmount = database.read(context -> { try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { return Optional - .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USER_ID .eq(userId) + .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USER_ID.eq(userId) .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) .map(WarnSystemRecord::getWarningAmount); } From 0de5cfa39b4cf77a19d4abcdbfd6dcbf38530000 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 3 Dec 2021 13:54:04 +0000 Subject: [PATCH 33/50] reverted the changes on the ban and kick command --- .../togetherjava/tjbot/commands/Commands.java | 4 +-- .../tjbot/commands/moderation/BanCommand.java | 27 +-------------- .../commands/moderation/KickCommand.java | 26 +------------- .../commands/moderation/ModerationUtils.java | 28 +-------------- .../commands/moderation/WarnCommand.java | 34 +++++++------------ .../main/resources/db/V6__Add_Kick_System.sql | 9 ----- .../main/resources/db/V7__Add_Ban_System.sql | 9 ----- 7 files changed, 17 insertions(+), 120 deletions(-) delete mode 100644 application/src/main/resources/db/V6__Add_Kick_System.sql delete mode 100644 application/src/main/resources/db/V7__Add_Ban_System.sql 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 5df25e3256..4e6368acef 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -50,8 +50,8 @@ public enum Commands { commands.add(new TagManageCommand(tagSystem)); commands.add(new TagsCommand(tagSystem)); commands.add(new VcActivityCommand()); - commands.add(new KickCommand(database)); - commands.add(new BanCommand(database)); + commands.add(new KickCommand()); + commands.add(new BanCommand()); commands.add(new UnbanCommand()); commands.add(new WarnCommand(database)); 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 index 5f7545b242..427eb63ee4 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/BanCommand.java @@ -21,9 +21,6 @@ import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; -import org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.db.generated.tables.BanSystem; -import org.togetherjava.tjbot.db.generated.tables.records.BanSystemRecord; import java.util.Objects; import java.util.Optional; @@ -45,17 +42,13 @@ public final class BanCommand extends SlashCommandAdapter { private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "ban"; private static final String ACTION_VERB = "ban"; - private final Database database; private final Predicate hasRequiredRole; /** * Constructs an instance. - * - * @param database used to store the bans in the database */ - public BanCommand(@NotNull Database database) { + public BanCommand() { super(COMMAND_NAME, "Bans the given user from the server", SlashCommandVisibility.GUILD); - this.database = database; getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to ban", true) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be banned", true) @@ -170,7 +163,6 @@ private boolean handleChecks(@NotNull Member bot, @NotNull Member author, return ModerationUtils.handleReason(reason, event); } - @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping targetOption = @@ -200,22 +192,5 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { .requireNonNull(alreadyBanned.getFailure()), event, guild, target).orElseGet( () -> banUserFlow(target, author, reason, deleteHistoryDays, guild, event)); }).queue(); - - try { - database.write(context -> { - BanSystemRecord banSystemRecord = context.newRecord(BanSystem.BAN_SYSTEM) - .setCaseId(1) - .setUserId(target.getIdLong()) - .setGuildId(guild.getIdLong()) - .setBanReason(reason) - .setActionType(ModerationUtils.Action.BAN.getVerb()); - if (banSystemRecord.update() == 0) { - banSystemRecord.insert(); - } - }); - logger.info("Saved the user '{}' to the ban system.", target.getAsTag()); - } catch (Exception exception) { - exception.printStackTrace(); - } } } 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 index 19378f198f..27f81c3501 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/KickCommand.java @@ -16,9 +16,6 @@ import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; -import org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.db.generated.tables.KickSystem; -import org.togetherjava.tjbot.db.generated.tables.records.KickSystemRecord; import java.util.Objects; import java.util.function.Predicate; @@ -38,17 +35,13 @@ public final class KickCommand extends SlashCommandAdapter { private static final String REASON_OPTION = "reason"; private static final String COMMAND_NAME = "kick"; private static final String ACTION_VERB = "kick"; - private final Database database; private final Predicate hasRequiredRole; /** * Constructs an instance. - * - * @param database used to store the kicks in the database */ - public KickCommand(@NotNull Database database) { + public KickCommand() { super(COMMAND_NAME, "Kicks the given user from the server", SlashCommandVisibility.GUILD); - this.database = database; getData().addOption(OptionType.USER, TARGET_OPTION, "The user who you want to kick", true) .addOption(OptionType.STRING, REASON_OPTION, "Why the user should be kicked", true); @@ -148,22 +141,5 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { return; } kickUserFlow(Objects.requireNonNull(target), author, reason, guild, event); - - try { - database.write(context -> { - KickSystemRecord kickSystemRecord = context.newRecord(KickSystem.KICK_SYSTEM) - .setUserid(target.getUser().getIdLong()) - .setAuthorId(author.getIdLong()) - .setGuildId(guild.getIdLong()) - .setIsKicked(true) - .setKickReason(reason); - if (kickSystemRecord.update() == 0) { - kickSystemRecord.insert(); - } - }); - logger.info("Saved the user '{}' to the kick system.", target.getUser().getAsTag()); - } catch (Exception exception) { - exception.printStackTrace(); - } } } 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 index 8ac79c4993..8d4a63edf3 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -6,13 +6,8 @@ import net.dv8tion.jda.api.interactions.Interaction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import org.jooq.UpdatableRecord; -import org.jooq.impl.UpdatableRecordImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.db.generated.tables.BanSystem; -import org.togetherjava.tjbot.db.generated.tables.records.BanSystemRecord; import java.awt.*; import java.time.Instant; @@ -54,28 +49,6 @@ static boolean handleReason(@NotNull CharSequence reason, @NotNull Interaction e return false; } - static void setModerationData(@NotNull Database database, User target, Guild guild, - int CaseId, String reason, Action action, UpdatableRecordImpl updateTableRecord, - String commandName) { - try { - database.write(context -> { - UpdatableRecordImpl updatableRecordImpl = - context.newRecord(updatableRecord.action) - .setCaseId(CaseId) - .setUserId(target.getIdLong()) - .setGuildId(guild.getIdLong()) - .setBanReason(reason) - .setActionType(action.getVerb()); - if (updatableRecordImpl.update() == 0) { - updatableRecordImpl.insert(); - } - }); - logger.info("Saved the user '{}' to the '{}' system.", target.getAsTag(), commandName); - } catch (Exception exception) { - exception.printStackTrace(); - } - } - /** * Checks whether the given author and bot can interact with the target user. For example * whether they have enough permissions to ban the user. @@ -248,6 +221,7 @@ enum Action { */ WARN("warned"); + private final String verb; /** diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 0024181169..ddf4302dcb 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -54,7 +54,7 @@ public WarnCommand(@NotNull Database database) { getData().addOption(OptionType.USER, USER_OPTION, "The user to warn", true) .addOption(OptionType.STRING, REASON_OPTION, "The reason for the warning", true); - hasRequiredRole = Pattern.compile(Config.getInstance().getSoftModerationRolePattern()) + hasRequiredRole = Pattern.compile(Config.getInstance().getHeavyModerationRolePattern()) .asMatchPredicate(); } @@ -62,10 +62,14 @@ public WarnCommand(@NotNull Database database) { @NotNull Guild guild, @NotNull SlashCommandEvent event) { return event.getJDA() .openPrivateChannelById(userId) - .flatMap(privateChannel -> event.replyEmbeds(new EmbedBuilder().setTitle("Warned") - .setDescription("You have been warned in " + guild.getName() + " for " + reason) - .setColor(Color.decode("#895FE8")) - .build())) + .flatMap(channel -> channel.sendMessage( + """ + Hey there, We are sorry to inform you that you have been warned for the following reason: %s + The repercussion of this warning depends on the severity of the warning or one the number of warnings you have received.\040 + The warn system works as follows: + + """ + .formatted(reason))) .mapToResult() .map(Result::isSuccess); } @@ -84,34 +88,20 @@ private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { - // Member doesn't exist if attempting to ban a user who is not part of the guild. - if (target != null && !ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, - target, event)) { - return false; - } - if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { return false; } - if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.KICK_MEMBERS, bot, + if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.BAN_MEMBERS, bot, guild, event)) { return false; } - if (!ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, Permission.KICK_MEMBERS, - author, guild, event)) { + if (!ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, Permission.BAN_MEMBERS, author, + guild, event)) { return false; } return ModerationUtils.handleReason(reason, event); } - /** - * Handles {@code /warn user reason} command. Saves the value under the given user, given guild, - * given reason and adds one to the number of warns the user has. - *

- * This command can only be used by users with the {@code KICK_MEMBERS} permission. - * - * @param event the event of the command - */ @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping userOption = diff --git a/application/src/main/resources/db/V6__Add_Kick_System.sql b/application/src/main/resources/db/V6__Add_Kick_System.sql deleted file mode 100644 index 63f7b68b88..0000000000 --- a/application/src/main/resources/db/V6__Add_Kick_System.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE kick_system -( - case_id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id BIGINT NOT NULL, - guild_id BIGINT NOT NULL, - reason TEXT DEFAULT 'This user has been kicked for breaking the rules.', - action_type TEXT DEFAULT 'warned', - timestamp TIMESTAMP NOT NULL -) \ No newline at end of file diff --git a/application/src/main/resources/db/V7__Add_Ban_System.sql b/application/src/main/resources/db/V7__Add_Ban_System.sql deleted file mode 100644 index 74b5606de9..0000000000 --- a/application/src/main/resources/db/V7__Add_Ban_System.sql +++ /dev/null @@ -1,9 +0,0 @@ -CREATE TABLE ban_system -( - case_id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id BIGINT NOT NULL, - guild_id BIGINT NOT NULL, - reason TEXT DEFAULT 'This user has been banned for breaking the rules.', - action_type TEXT DEFAULT 'warned', - timestamp TIMESTAMP NOT NULL -) \ No newline at end of file From c5e084bd8e5344a519280ea751ddbdd1955e42da Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 3 Dec 2021 13:55:04 +0000 Subject: [PATCH 34/50] Update MessageUtils.java --- .../tjbot/commands/utils/MessageUtils.java | 56 +++++-------------- 1 file changed, 15 insertions(+), 41 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java index 8c18a8fcb1..331feee5fa 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java @@ -4,8 +4,6 @@ import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.User; -import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; -import net.dv8tion.jda.api.interactions.commands.CommandInteraction; import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.interactions.components.Button; import net.dv8tion.jda.api.utils.MarkdownSanitizer; @@ -41,8 +39,8 @@ public static void disableButtons(@NotNull Message message) { } message - .editMessageComponents(ActionRow.of(buttons.stream().map(Button::asDisabled).toList())) - .queue(); + .editMessageComponents(ActionRow.of(buttons.stream().map(Button::asDisabled).toList())) + .queue(); } /** @@ -56,55 +54,31 @@ public static void disableButtons(@NotNull Message message) { * @return the generated embed */ public static @NotNull MessageEmbed generateEmbed(@Nullable String title, - @NotNull CharSequence content, @Nullable User user, @Nullable Color ambientColor) { + @NotNull CharSequence content, @Nullable User user, @Nullable Color ambientColor) { return new EmbedBuilder().setTitle(title) - .setDescription(content) - .setTimestamp(Instant.now()) - .setFooter(user == null ? null : user.getName()) - .setColor(ambientColor) - .build(); + .setDescription(content) + .setTimestamp(Instant.now()) + .setFooter(user == null ? null : user.getName()) + .setColor(ambientColor) + .build(); } /** * Escapes every markdown content in the given string. * * If the escaped message is sent to Discord, it will display the original message. - * + * * @param text the text to escape * @return the escaped text */ public static @NotNull String escapeMarkdown(@NotNull String text) { // NOTE Unfortunately the utility does not escape backslashes '\', so we have to do it // ourselves - return MarkdownSanitizer.escape(text.replace("\\", "\\\\")); - } - - /** - * Instead of always queuing the reply message you can just make a method which queues - * automatically. - * - * @param message the message that you want to send - */ - public static void reply(String message, @NotNull SlashCommandEvent event) { - event.reply(message).queue(); - } - - public static void reply(String message, @NotNull CommandInteraction event) { - event.reply(message).queue(); - } - - /** - * Instead of always setting ephemeral as true making one method and using it makes life easier. - * - * @param message the message that you want to send - * @param event The slash command event - */ - public static void replyEphemeral(String message, @NotNull SlashCommandEvent event) { - event.reply(message).setEphemeral(true).queue(); - } - - public static void replyEphemeral(String message, @NotNull CommandInteraction event) { - event.reply(message).setEphemeral(true).queue(); + // NOTE It also does not properly escape three backticks '```', it makes it '\```' but we + // need '\`\`\`' + String beforeEscape = text.replace("\\", "\\\\"); + String afterEscape = MarkdownSanitizer.escape(beforeEscape); + return afterEscape.replace("\\```", "\\`\\`\\`"); } -} +} \ No newline at end of file From c1555d720c2a24f23b4193104d6291ffe09ec205 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 3 Dec 2021 13:56:03 +0000 Subject: [PATCH 35/50] Reverted changes --- .../tjbot/commands/utils/MessageUtils.java | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java index 331feee5fa..a40ccdc572 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java @@ -39,8 +39,8 @@ public static void disableButtons(@NotNull Message message) { } message - .editMessageComponents(ActionRow.of(buttons.stream().map(Button::asDisabled).toList())) - .queue(); + .editMessageComponents(ActionRow.of(buttons.stream().map(Button::asDisabled).toList())) + .queue(); } /** @@ -54,13 +54,13 @@ public static void disableButtons(@NotNull Message message) { * @return the generated embed */ public static @NotNull MessageEmbed generateEmbed(@Nullable String title, - @NotNull CharSequence content, @Nullable User user, @Nullable Color ambientColor) { + @NotNull CharSequence content, @Nullable User user, @Nullable Color ambientColor) { return new EmbedBuilder().setTitle(title) - .setDescription(content) - .setTimestamp(Instant.now()) - .setFooter(user == null ? null : user.getName()) - .setColor(ambientColor) - .build(); + .setDescription(content) + .setTimestamp(Instant.now()) + .setFooter(user == null ? null : user.getName()) + .setColor(ambientColor) + .build(); } /** @@ -81,4 +81,4 @@ public static void disableButtons(@NotNull Message message) { return afterEscape.replace("\\```", "\\`\\`\\`"); } -} \ No newline at end of file +} From e5dfc298c00b7f79e9ccfc55c462325b32ed854f Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 3 Dec 2021 14:55:43 +0000 Subject: [PATCH 36/50] add final --- .../tjbot/commands/moderation/ModerationUtils.java | 2 +- .../togetherjava/tjbot/commands/moderation/WarnCommand.java | 5 ++++- 2 files changed, 5 insertions(+), 2 deletions(-) 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 index 8d4a63edf3..336496c222 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -217,7 +217,7 @@ enum Action { */ KICK("kicked"), /** - * When a user warns another user + * When a user warns another user. */ WARN("warned"); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index ddf4302dcb..d20adffeba 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -24,6 +24,7 @@ import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; import java.awt.*; +import java.time.Instant; import java.util.Objects; import java.util.Optional; import java.util.function.Predicate; @@ -36,7 +37,7 @@ * warned and will receive a dm telling them why there were warned. After that all the data will be * added to the database. */ -public class WarnCommand extends SlashCommandAdapter { +public final class WarnCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); private static final String USER_OPTION = "user"; private static final String REASON_OPTION = "reason"; @@ -141,6 +142,8 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { .setUserId(target.getIdLong()) .setGuildId(guildId) .setWarnReason(reason) + .setActionType(ModerationUtils.Action.WARN.getVerb()) + .setTimestamp(Instant.now()) .setWarningAmount(oldWarnAmount.orElse(0) + 1); if (warnSystemRecord.update() == 0) { warnSystemRecord.insert(); From ef24c77dc5592d7a8e067672ec0cf56ba7c245b6 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 3 Dec 2021 22:10:36 +0000 Subject: [PATCH 37/50] Update WarnCommand.java --- .../togetherjava/tjbot/commands/moderation/WarnCommand.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index d20adffeba..acb4b17d26 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -67,8 +67,7 @@ public WarnCommand(@NotNull Database database) { """ Hey there, We are sorry to inform you that you have been warned for the following reason: %s The repercussion of this warning depends on the severity of the warning or one the number of warnings you have received.\040 - The warn system works as follows: - + The warn system can be seen in the #rule channel. """ .formatted(reason))) .mapToResult() From 553d8355ba3213dca4b34e4a7c43a9ab939436aa Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 3 Dec 2021 22:21:50 +0000 Subject: [PATCH 38/50] removed unused methods --- .../tjbot/commands/moderation/WarnCommand.java | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index acb4b17d26..c93d58bdd8 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -1,6 +1,5 @@ package org.togetherjava.tjbot.commands.moderation; -import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; @@ -13,7 +12,6 @@ import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.utils.Result; import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.SlashCommandAdapter; @@ -23,7 +21,6 @@ import org.togetherjava.tjbot.db.generated.tables.WarnSystem; import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; -import java.awt.*; import java.time.Instant; import java.util.Objects; import java.util.Optional; @@ -60,7 +57,7 @@ public WarnCommand(@NotNull Database database) { } private static @NotNull RestAction dmUser(long userId, @NotNull String reason, - @NotNull Guild guild, @NotNull SlashCommandEvent event) { + @NotNull SlashCommandEvent event) { return event.getJDA() .openPrivateChannelById(userId) .flatMap(channel -> channel.sendMessage( @@ -85,8 +82,7 @@ public WarnCommand(@NotNull Database database) { } private boolean handleChecks(@NotNull Member bot, @NotNull Member author, - @Nullable Member target, @NotNull CharSequence reason, @NotNull Guild guild, - @NotNull Interaction event) { + @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { return false; @@ -107,7 +103,6 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping userOption = Objects.requireNonNull(event.getOption(USER_OPTION), "The option is null"); User target = userOption.getAsUser(); - Member targetMember = userOption.getAsMember(); Member author = Objects.requireNonNull(event.getMember(), "The author is null"); Guild guild = Objects.requireNonNull(event.getGuild(), "The guild is null"); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") @@ -115,12 +110,12 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { Member bot = guild.getSelfMember(); - if (!handleChecks(bot, author, targetMember, reason, guild, event)) { + if (!handleChecks(bot, author, reason, guild, event)) { return; } long userId = target.getIdLong(); - dmUser(userId, reason, guild, event) + dmUser(userId, reason, event) .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) .flatMap(event::replyEmbeds) .queue(); From 87f3aaf1f0adf04063e188ae085b4062f62d859e Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 4 Dec 2021 08:28:57 +0000 Subject: [PATCH 39/50] fixed the dm message --- .../org/togetherjava/tjbot/commands/moderation/WarnCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index c93d58bdd8..11f9e163c1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -64,7 +64,7 @@ public WarnCommand(@NotNull Database database) { """ Hey there, We are sorry to inform you that you have been warned for the following reason: %s The repercussion of this warning depends on the severity of the warning or one the number of warnings you have received.\040 - The warn system can be seen in the #rule channel. + The warn system can be seen in the <#652440333107331082> channel.\040 """ .formatted(reason))) .mapToResult() From 7e421ec02e81cf5ea62eb1f11400621ec5f2e37b Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 10 Dec 2021 16:29:09 +0000 Subject: [PATCH 40/50] finished --- .../togetherjava/tjbot/commands/Commands.java | 3 +- .../commands/moderation/ActionRecord.java | 2 +- .../commands/moderation/WarnCommand.java | 46 +++---------------- .../main/resources/db/V5__Add_Warn_System.sql | 10 ---- 4 files changed, 10 insertions(+), 51 deletions(-) delete mode 100644 application/src/main/resources/db/V5__Add_Warn_System.sql 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 5ee0703225..21f23a8cbc 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Commands.java @@ -1,4 +1,5 @@ package org.togetherjava.tjbot.commands; + import org.jetbrains.annotations.NotNull; import org.togetherjava.tjbot.commands.basic.DatabaseCommand; import org.togetherjava.tjbot.commands.basic.PingCommand; @@ -51,7 +52,7 @@ public enum Commands { commands.add(new TagManageCommand(tagSystem)); commands.add(new TagsCommand(tagSystem)); commands.add(new VcActivityCommand()); - commands.add(new WarnCommand(database)); + commands.add(new WarnCommand(actionsStore)); commands.add(new KickCommand(actionsStore)); commands.add(new BanCommand(actionsStore)); commands.add(new UnbanCommand(actionsStore)); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java index dbfb81fa24..38d3b149b3 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java @@ -9,7 +9,7 @@ /** * Record for actions as maintained by {@link ModerationActionsStore}. Each action has a unique * caseId. - * + * * @param caseId the unique case id associated with this action * @param issuedAt the instant at which this action was issued * @param guildId the id of the guild in which context this action happened diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 11f9e163c1..612a74e226 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -12,18 +12,11 @@ import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.utils.Result; 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 org.togetherjava.tjbot.config.Config; -import org.togetherjava.tjbot.db.Database; -import org.togetherjava.tjbot.db.generated.tables.WarnSystem; -import org.togetherjava.tjbot.db.generated.tables.records.WarnSystemRecord; -import java.time.Instant; import java.util.Objects; -import java.util.Optional; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -35,25 +28,26 @@ * added to the database. */ public final class WarnCommand extends SlashCommandAdapter { - private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); private static final String USER_OPTION = "user"; private static final String REASON_OPTION = "reason"; private static final String ACTION_VERB = "warn"; - private final Database database; + private final ModerationActionsStore actionsStore; private final Predicate hasRequiredRole; /** * Creates a new Instance. + * + * @param actionsStore used to store actions issued by this command */ - public WarnCommand(@NotNull Database database) { + public WarnCommand(@NotNull ModerationActionsStore actionsStore) { super("warn", "warns the user", SlashCommandVisibility.GUILD); - this.database = database; getData().addOption(OptionType.USER, USER_OPTION, "The user to warn", true) .addOption(OptionType.STRING, REASON_OPTION, "The reason for the warning", true); hasRequiredRole = Pattern.compile(Config.getInstance().getHeavyModerationRolePattern()) .asMatchPredicate(); + this.actionsStore = Objects.requireNonNull(actionsStore); } private static @NotNull RestAction dmUser(long userId, @NotNull String reason, @@ -113,39 +107,13 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { if (!handleChecks(bot, author, reason, guild, event)) { return; } - long userId = target.getIdLong(); dmUser(userId, reason, event) .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) .flatMap(event::replyEmbeds) .queue(); - long guildId = guild.getIdLong(); - Optional oldWarnAmount = database.read(context -> { - try (var select = context.selectFrom(WarnSystem.WARN_SYSTEM)) { - return Optional - .ofNullable(select.where(WarnSystem.WARN_SYSTEM.USER_ID.eq(userId) - .and(WarnSystem.WARN_SYSTEM.GUILD_ID.eq(guildId))).fetchOne()) - .map(WarnSystemRecord::getWarningAmount); - } - }); - - try { - database.write(context -> { - WarnSystemRecord warnSystemRecord = context.newRecord(WarnSystem.WARN_SYSTEM) - .setUserId(target.getIdLong()) - .setGuildId(guildId) - .setWarnReason(reason) - .setActionType(ModerationUtils.Action.WARN.getVerb()) - .setTimestamp(Instant.now()) - .setWarningAmount(oldWarnAmount.orElse(0) + 1); - if (warnSystemRecord.update() == 0) { - warnSystemRecord.insert(); - } - }); - logger.info("Saved the user '{}' to the warn system.", target.getAsTag()); - } catch (Exception exception) { - exception.printStackTrace(); - } + actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), + ModerationUtils.Action.WARN, null, reason); } } diff --git a/application/src/main/resources/db/V5__Add_Warn_System.sql b/application/src/main/resources/db/V5__Add_Warn_System.sql deleted file mode 100644 index 1ff6fdcf7b..0000000000 --- a/application/src/main/resources/db/V5__Add_Warn_System.sql +++ /dev/null @@ -1,10 +0,0 @@ -CREATE TABLE warn_system -( - case_id INTEGER PRIMARY KEY AUTOINCREMENT, - user_id BIGINT NOT NULL, - guild_id BIGINT NOT NULL, - warn_reason TEXT DEFAULT 'This user has been warned for breaking the rules.', - action_type TEXT DEFAULT 'warned', - timestamp TIMESTAMP NOT NULL, - warning_amount INTEGER DEFAULT 0 -) \ No newline at end of file From 9af8a85c9dfeaf2f45d266261c07beadfc961242 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 10 Dec 2021 16:49:31 +0000 Subject: [PATCH 41/50] added better javadoc --- .../tjbot/commands/moderation/WarnCommand.java | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 612a74e226..200beb9fa1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -22,10 +22,11 @@ /** - * This command allows a moderator to warn a user. This moderator will need to have ban permission - * and well need to type {@code /warn @user reason}. If the command is successful the user will be - * warned and will receive a dm telling them why there were warned. After that all the data will be - * added to the database. + * This command can warn users. Warning can also be paired with a warn 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 WarnCommand extends SlashCommandAdapter { private static final String USER_OPTION = "user"; From ca1de68bc993cf1c3afb88c8da7a64057d801159 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 10 Dec 2021 19:26:20 +0000 Subject: [PATCH 42/50] fixed the JavaDoc --- .../tjbot/commands/moderation/ActionRecord.java | 4 ++-- .../tjbot/commands/moderation/WarnCommand.java | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java index 38d3b149b3..acb12b8669 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java @@ -9,7 +9,7 @@ /** * Record for actions as maintained by {@link ModerationActionsStore}. Each action has a unique * caseId. - * + * * @param caseId the unique case id associated with this action * @param issuedAt the instant at which this action was issued * @param guildId the id of the guild in which context this action happened @@ -26,7 +26,7 @@ public record ActionRecord(int caseId, @NotNull Instant issuedAt, long guildId, /** * Creates the action record that corresponds to the given action entry from the database table. - * + * * @param action the action to convert * @return the corresponding action record */ diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 200beb9fa1..69d5c2caf2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -22,11 +22,11 @@ /** - * This command can warn users. Warning can also be paired with a warn reason. The command will also - * try to DM the user to inform them about the action and the reason. + * This command can warn users. 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). + * The command fails if the user triggering it is lacking permissions to either warn other users or + * to warn the specific given user (for example a moderator attempting to ban an admin). */ public final class WarnCommand extends SlashCommandAdapter { private static final String USER_OPTION = "user"; From 488660419a012b31088e0214dfb60d5388e2a2ec Mon Sep 17 00:00:00 2001 From: Yusuf Date: Fri, 10 Dec 2021 19:37:34 +0000 Subject: [PATCH 43/50] Update WarnCommand.java --- .../org/togetherjava/tjbot/commands/moderation/WarnCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 69d5c2caf2..e9d9cf30af 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -26,7 +26,7 @@ * action and the reason. *

* The command fails if the user triggering it is lacking permissions to either warn other users or - * to warn the specific given user (for example a moderator attempting to ban an admin). + * to warn the specific given user (for example a moderator attempting to warn an admin). */ public final class WarnCommand extends SlashCommandAdapter { private static final String USER_OPTION = "user"; From eeefe286fd17669e43697547f87fd99331708208 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 11 Dec 2021 12:20:47 +0000 Subject: [PATCH 44/50] FIxed all the issues --- .../commands/moderation/WarnCommand.java | 104 ++++++++++-------- 1 file changed, 59 insertions(+), 45 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index e9d9cf30af..1d2a3745ec 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -1,17 +1,16 @@ 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.MessageEmbed; -import net.dv8tion.jda.api.entities.User; +import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.events.interaction.SlashCommandEvent; -import net.dv8tion.jda.api.interactions.Interaction; +import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.OptionMapping; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.utils.Result; import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; @@ -29,6 +28,7 @@ * to warn the specific given user (for example a moderator attempting to warn an admin). */ public final class WarnCommand extends SlashCommandAdapter { + private static final Logger logger = LoggerFactory.getLogger(WarnCommand.class); private static final String USER_OPTION = "user"; private static final String REASON_OPTION = "reason"; private static final String ACTION_VERB = "warn"; @@ -43,29 +43,50 @@ public final class WarnCommand extends SlashCommandAdapter { public WarnCommand(@NotNull ModerationActionsStore actionsStore) { super("warn", "warns the user", SlashCommandVisibility.GUILD); - getData().addOption(OptionType.USER, USER_OPTION, "The user to warn", true) - .addOption(OptionType.STRING, REASON_OPTION, "The reason for the warning", true); + getData().addOption(OptionType.USER, USER_OPTION, "The user who you want to warn", true) + .addOption(OptionType.STRING, REASON_OPTION, "The user who you want to warn", true); hasRequiredRole = Pattern.compile(Config.getInstance().getHeavyModerationRolePattern()) .asMatchPredicate(); this.actionsStore = Objects.requireNonNull(actionsStore); } - private static @NotNull RestAction dmUser(long userId, @NotNull String reason, - @NotNull SlashCommandEvent event) { + private @NotNull RestAction warnUserFlow(@NotNull User target, @NotNull Member author, + @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { + return dmUser(target, reason, guild, event).map(hasSentDm -> { + warnUser(target, author, reason, guild); + return hasSentDm; + }) + .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) + .flatMap(event::replyEmbeds); + } + + private static @NotNull RestAction dmUser(@NotNull ISnowflake target, + @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { return event.getJDA() - .openPrivateChannelById(userId) + .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage( """ - Hey there, We are sorry to inform you that you have been warned for the following reason: %s - The repercussion of this warning depends on the severity of the warning or one the number of warnings you have received.\040 - The warn system can be seen in the <#652440333107331082> channel.\040 + Hey there, sorry to tell you but unfortunately you have been warned in the server %s. + If you think this was a mistake, please contact a moderator or admin of the server. + The reason for the warning is: %s """ - .formatted(reason))) + .formatted(guild.getName(), reason))) .mapToResult() .map(Result::isSuccess); } + private void warnUser(@NotNull User target, @NotNull Member author, @NotNull String reason, + @NotNull Guild guild) { + logger.info("'{}' ({}) warned the user '{}' ({}) for reason '{}'.", + author.getUser().getAsTag(), author.getId(), target.getAsTag(), target.getId(), + reason); + + actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), + ModerationUtils.Action.WARN, null, reason); + + } + private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull User target, @NotNull Member author, @NotNull String reason) { String dmNoticeText = ""; @@ -76,45 +97,38 @@ public WarnCommand(@NotNull ModerationActionsStore actionsStore) { target, dmNoticeText, reason); } - private boolean handleChecks(@NotNull Member bot, @NotNull Member author, - @NotNull CharSequence reason, @NotNull Guild guild, @NotNull Interaction event) { - - if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { - return false; - } - if (!ModerationUtils.handleHasBotPermissions(ACTION_VERB, Permission.BAN_MEMBERS, bot, - guild, event)) { - return false; - } - if (!ModerationUtils.handleHasAuthorPermissions(ACTION_VERB, Permission.BAN_MEMBERS, author, - guild, event)) { - return false; - } - return ModerationUtils.handleReason(reason, event); - } - @Override public void onSlashCommand(@NotNull SlashCommandEvent event) { - OptionMapping userOption = - Objects.requireNonNull(event.getOption(USER_OPTION), "The option is null"); - User target = userOption.getAsUser(); + OptionMapping targetOption = + Objects.requireNonNull(event.getOption(USER_OPTION), "The target is null"); + User target = targetOption.getAsUser(); Member author = Objects.requireNonNull(event.getMember(), "The author is null"); Guild guild = Objects.requireNonNull(event.getGuild(), "The guild is null"); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") .getAsString(); - Member bot = guild.getSelfMember(); - - if (!handleChecks(bot, author, reason, guild, event)) { + if (!handleChecks(guild.getSelfMember(), author, targetOption.getAsMember(), reason, + event)) { return; } - long userId = target.getIdLong(); - dmUser(userId, reason, event) - .map(hasSentDm -> sendFeedback(hasSentDm, target, author, reason)) - .flatMap(event::replyEmbeds) - .queue(); - actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), - ModerationUtils.Action.WARN, null, reason); + warnUserFlow(target, author, reason, guild, event).queue(); + } + + @SuppressWarnings("BooleanMethodNameMustStartWithQuestion") + private boolean handleChecks(@NotNull Member bot, @NotNull Member author, + @Nullable Member target, String reason, @NotNull SlashCommandEvent event) { + if (target == null) { + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { + return false; + } + } else { + // Check if the author can warn a user with higher perms. + if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, + event)) { + return false; + } + } + return ModerationUtils.handleReason(reason, event); } } From 0d32bcda21edacc95518d1161d21101a0b2b3e21 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 11 Dec 2021 14:08:00 +0000 Subject: [PATCH 45/50] fixed most of the issues --- .../commands/moderation/WarnCommand.java | 21 ++++++++----------- 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 1d2a3745ec..077c3d6918 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -51,8 +51,9 @@ public WarnCommand(@NotNull ModerationActionsStore actionsStore) { this.actionsStore = Objects.requireNonNull(actionsStore); } - private @NotNull RestAction warnUserFlow(@NotNull User target, @NotNull Member author, - @NotNull String reason, @NotNull Guild guild, @NotNull SlashCommandEvent event) { + private @NotNull RestAction warnUserFlow(@NotNull User target, + @NotNull Member author, @NotNull String reason, @NotNull Guild guild, + @NotNull SlashCommandEvent event) { return dmUser(target, reason, guild, event).map(hasSentDm -> { warnUser(target, author, reason, guild); return hasSentDm; @@ -118,16 +119,12 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { @SuppressWarnings("BooleanMethodNameMustStartWithQuestion") private boolean handleChecks(@NotNull Member bot, @NotNull Member author, @Nullable Member target, String reason, @NotNull SlashCommandEvent event) { - if (target == null) { - if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { - return false; - } - } else { - // Check if the author can warn a user with higher perms. - if (!ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, target, - event)) { - return false; - } + if (target != null && !ModerationUtils.handleCanInteractWithTarget(ACTION_VERB, bot, author, + target, event)) { + return false; + } + if (!ModerationUtils.handleHasAuthorRole(ACTION_VERB, hasRequiredRole, author, event)) { + return false; } return ModerationUtils.handleReason(reason, event); } From 3850fd56b3672b5c0d810942a416dd315bc7ca9f Mon Sep 17 00:00:00 2001 From: Yusuf Date: Sat, 11 Dec 2021 14:15:05 +0000 Subject: [PATCH 46/50] fixed more issues --- .../togetherjava/tjbot/commands/moderation/ModerationUtils.java | 1 - .../org/togetherjava/tjbot/commands/moderation/WarnCommand.java | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) 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 index 336496c222..bf5a3f765b 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -221,7 +221,6 @@ enum Action { */ WARN("warned"); - private final String verb; /** diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 077c3d6918..3fcde240ba 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -41,7 +41,7 @@ public final class WarnCommand extends SlashCommandAdapter { * @param actionsStore used to store actions issued by this command */ public WarnCommand(@NotNull ModerationActionsStore actionsStore) { - super("warn", "warns the user", SlashCommandVisibility.GUILD); + super("warn", "Warns the given user", SlashCommandVisibility.GUILD); getData().addOption(OptionType.USER, USER_OPTION, "The user who you want to warn", true) .addOption(OptionType.STRING, REASON_OPTION, "The user who you want to warn", true); From 8f1ada73877d25d0592174b61780eb55c5348019 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Mon, 13 Dec 2021 20:06:58 +0000 Subject: [PATCH 47/50] implemented the fixes. The issue with ActionRecord was resolved but does not appear on Github which is a problem for their side. @Zabuzard just letting you know --- .../togetherjava/tjbot/commands/moderation/WarnCommand.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 3fcde240ba..9ae2fc3052 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -36,7 +36,7 @@ public final class WarnCommand extends SlashCommandAdapter { private final Predicate hasRequiredRole; /** - * Creates a new Instance. + * Creates a new instance. * * @param actionsStore used to store actions issued by this command */ @@ -85,7 +85,6 @@ private void warnUser(@NotNull User target, @NotNull Member author, @NotNull Str actionsStore.addAction(guild.getIdLong(), author.getIdLong(), target.getIdLong(), ModerationUtils.Action.WARN, null, reason); - } private static @NotNull MessageEmbed sendFeedback(boolean hasSentDm, @NotNull User target, @@ -102,7 +101,6 @@ private void warnUser(@NotNull User target, @NotNull Member author, @NotNull Str public void onSlashCommand(@NotNull SlashCommandEvent event) { OptionMapping targetOption = Objects.requireNonNull(event.getOption(USER_OPTION), "The target is null"); - User target = targetOption.getAsUser(); Member author = Objects.requireNonNull(event.getMember(), "The author is null"); Guild guild = Objects.requireNonNull(event.getGuild(), "The guild is null"); String reason = Objects.requireNonNull(event.getOption(REASON_OPTION), "The reason is null") @@ -113,7 +111,7 @@ public void onSlashCommand(@NotNull SlashCommandEvent event) { return; } - warnUserFlow(target, author, reason, guild, event).queue(); + warnUserFlow(targetOption.getAsUser(), author, reason, guild, event).queue(); } @SuppressWarnings("BooleanMethodNameMustStartWithQuestion") From 3b86c9e6cd06367f4bc8e0feada45066270c3fb1 Mon Sep 17 00:00:00 2001 From: Yusuf Date: Mon, 13 Dec 2021 20:31:35 +0000 Subject: [PATCH 48/50] fixed the Action record issue --- .../togetherjava/tjbot/commands/moderation/ActionRecord.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java index acb12b8669..dbfb81fa24 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ActionRecord.java @@ -26,7 +26,7 @@ public record ActionRecord(int caseId, @NotNull Instant issuedAt, long guildId, /** * Creates the action record that corresponds to the given action entry from the database table. - * + * * @param action the action to convert * @return the corresponding action record */ From 61ebf1b5b5c64d5f1ab72aada0b036e9a9d60d70 Mon Sep 17 00:00:00 2001 From: Yusuf Arfan Ismail Date: Tue, 14 Dec 2021 12:56:18 +0000 Subject: [PATCH 49/50] fixed the issues Added the space back and added Why you want to warn the user --- .../org/togetherjava/tjbot/commands/moderation/WarnCommand.java | 2 +- .../org/togetherjava/tjbot/commands/utils/MessageUtils.java | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java index 9ae2fc3052..b7943a065f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/WarnCommand.java @@ -44,7 +44,7 @@ public WarnCommand(@NotNull ModerationActionsStore actionsStore) { super("warn", "Warns the given user", SlashCommandVisibility.GUILD); getData().addOption(OptionType.USER, USER_OPTION, "The user who you want to warn", true) - .addOption(OptionType.STRING, REASON_OPTION, "The user who you want to warn", true); + .addOption(OptionType.STRING, REASON_OPTION, "Why you want to warn the user", true); hasRequiredRole = Pattern.compile(Config.getInstance().getHeavyModerationRolePattern()) .asMatchPredicate(); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java index a40ccdc572..6828b594c2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/utils/MessageUtils.java @@ -67,7 +67,7 @@ public static void disableButtons(@NotNull Message message) { * Escapes every markdown content in the given string. * * If the escaped message is sent to Discord, it will display the original message. - * + * * @param text the text to escape * @return the escaped text */ From 2ecbc1923aa024309e220b40d838a346fd4664fb Mon Sep 17 00:00:00 2001 From: Yusuf Arfan Ismail Date: Tue, 14 Dec 2021 13:08:42 +0000 Subject: [PATCH 50/50] spotlessApply --- .../togetherjava/tjbot/commands/moderation/ModerationUtils.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 1f1b08a336..524d72ee1e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/ModerationUtils.java @@ -345,7 +345,7 @@ enum Action { * When a user warns another user. */ WARN("warned"), - /** + /** * When a user mutes another user. */ MUTE("muted"),