From d8a08fb24e99decfd8105125713c7acc75ad862d Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sat, 13 Aug 2022 16:19:41 +0200 Subject: [PATCH 01/45] Adding the /modmail command Commands which redirects command called from Guild or Dm to a dedicated channel in Config#getModAuditLogChannelPattern() --- .../togetherjava/tjbot/commands/Features.java | 4 + .../moderation/modmail/ModMailCommand.java | 160 ++++++++++++++++++ 2 files changed, 164 insertions(+) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index 581296a77d..cf6fb94c17 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -126,6 +126,10 @@ public static Collection createFeatures(JDA jda, Database database, Con features.add(new WhoIsCommand()); features.add(new WolframAlphaCommand(config)); features.add(new AskCommand(config, helpSystemHelper)); + features.add(new CloseCommand()); + features.add(new ChangeHelpCategoryCommand(config, helpSystemHelper)); + features.add(new ChangeHelpTitleCommand(helpSystemHelper)); + features.add(new ModMailCommand(config)); features.add(new HelpThreadCommand(config, helpSystemHelper)); // Mixtures diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java new file mode 100644 index 0000000000..d2d1dd1284 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -0,0 +1,160 @@ +package org.togetherjava.tjbot.commands.moderation.modmail; + +import com.github.benmanes.caffeine.cache.Cache; +import com.github.benmanes.caffeine.cache.Caffeine; +import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.MessageChannel; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.requests.restaction.MessageAction; +import org.jetbrains.annotations.NotNull; +import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.SlashCommandVisibility; +import org.togetherjava.tjbot.config.Config; +import org.togetherjava.tjbot.moderation.ModAuditLogWriter; + +import java.awt.*; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +import java.util.*; +import java.util.concurrent.TimeUnit; +import java.util.function.Predicate; +import java.util.regex.Pattern; + +/** + * Implements the '/modmail' command which can be used to automatically redirects messages from DM + * or Guild. + *

+ * Actions are then logged to a dedicated channel, given by + * {@link Config#getModAuditLogChannelPattern()}. + */ + +public class ModMailCommand extends SlashCommandAdapter { + + private static final String COMMAND_NAME = "modmail"; + private static final String MESSAGE = "message"; + private static final String OPTION_MESSAGE_PRIVATE = "message-private"; + private static final int COOLDOWN_DURATION_VALUE = 30; + private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES; + private final Cache channelIdToLastCommandInvocation; + private static Predicate auditLogChannelNamePredicate; + + + /** + * Creates a new instance. + * + * @param config the config to use for this + */ + public ModMailCommand(@NotNull Config config) { + super(COMMAND_NAME, "Sends a message to the moderators", SlashCommandVisibility.GLOBAL); + getData().addOption(OptionType.STRING, MESSAGE, "Message to the moderators", true) + .addOption(OptionType.BOOLEAN, OPTION_MESSAGE_PRIVATE, + "do you wish for" + " your" + " message to stay " + "private", false); + + channelIdToLastCommandInvocation = Caffeine.newBuilder() + .maximumSize(1_000) + .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT)) + .build(); + + auditLogChannelNamePredicate = + Pattern.compile(config.getModAuditLogChannelPattern()).asMatchPredicate(); + } + + @Override + public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { + // displays appropriate message, depending on if channel the command has been already called + MessageChannel messageChannel = event.getChannel(); + if (isChannelOnCooldown(messageChannel)) { + event + .reply("Please wait a bit, this command can only be used once per %d %s.".formatted( + COOLDOWN_DURATION_VALUE, + COOLDOWN_DURATION_UNIT.toString().toLowerCase(Locale.US))) + .setEphemeral(true) + .queue(); + return; + } + channelIdToLastCommandInvocation.put(messageChannel.getIdLong(), Instant.now()); + + + // retrieving the appropriate channel + Optional auditLogChannel = getChannel(event); + if (auditLogChannel.isEmpty()) { + return; + } + // until here + + List attachments = getAttachments(event); + + + // this message is creating the embed + + String user = event.getUser().getAsTag(); + boolean optionalMessage = + Objects.requireNonNull(event.getOption(OPTION_MESSAGE_PRIVATE)).getAsBoolean(); + // String reason = Objects.requireNonNull(event.getOption(REASON)).getAsString(); + if (optionalMessage) { + user = "Anonymous"; + } + MessageAction message = auditLogChannel.orElseThrow().sendMessageEmbeds(messageEmbed(user)); + + message = buildAttachment(attachments, message); + message.queue(); + // ends here + + event.reply("Thank you for contacting the moderators").setEphemeral(true).queue(); + + } + + private MessageAction buildAttachment(List attachments, + MessageAction message) { + for (ModAuditLogWriter.Attachment attachment : attachments) { + message = message.addFile(attachment.getContentRaw(), attachment.name()); + } + return message; + } + + @NotNull + private MessageEmbed messageEmbed(String user) { + return new EmbedBuilder().setAuthor("Modmail Command invoked") + .setColor(Color.BLACK) + .setTitle("Message from user '%s' who used /modmail command".formatted(user)) + /* + * .addField("Reason", reason, false) + */.build(); + } + + @NotNull + private List getAttachments( + @NotNull SlashCommandInteractionEvent event) { + String content = Objects.requireNonNull(event.getOption(MESSAGE)).getAsString(); + List attachments = new ArrayList<>(); + attachments.add(new ModAuditLogWriter.Attachment("content.md", content)); + return attachments; + } + + private @NotNull Optional getChannel(@NotNull SlashCommandInteractionEvent event) { + long guildId = 1004371840245964851L; + Guild guild = event.getChannel().getJDA().getGuildById(guildId); + if (guild == null) { + return Optional.empty(); + } + return guild.getTextChannelCache() + .stream() + .filter(channel -> auditLogChannelNamePredicate.test(channel.getName())) + .findAny(); + } + + private boolean isChannelOnCooldown(@NotNull MessageChannel channel) { + return Optional + .ofNullable(channelIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) + .map(sinceCommandInvoked -> sinceCommandInvoked.plus(COOLDOWN_DURATION_VALUE, + COOLDOWN_DURATION_UNIT)) + .filter(Instant.now()::isBefore) + .isPresent(); + } + +} From 36cbbc9a6bd1382ac4ec33fe566c6588afce06f7 Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sat, 13 Aug 2022 16:37:08 +0200 Subject: [PATCH 02/45] Removing comments , plus signs and commented out code --- .../commands/moderation/modmail/ModMailCommand.java | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index d2d1dd1284..20bf2cc728 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -53,7 +53,7 @@ public ModMailCommand(@NotNull Config config) { super(COMMAND_NAME, "Sends a message to the moderators", SlashCommandVisibility.GLOBAL); getData().addOption(OptionType.STRING, MESSAGE, "Message to the moderators", true) .addOption(OptionType.BOOLEAN, OPTION_MESSAGE_PRIVATE, - "do you wish for" + " your" + " message to stay " + "private", false); + "do you wish for your message to stay private", false); channelIdToLastCommandInvocation = Caffeine.newBuilder() .maximumSize(1_000) @@ -80,12 +80,10 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { channelIdToLastCommandInvocation.put(messageChannel.getIdLong(), Instant.now()); - // retrieving the appropriate channel Optional auditLogChannel = getChannel(event); if (auditLogChannel.isEmpty()) { return; } - // until here List attachments = getAttachments(event); @@ -95,7 +93,6 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { String user = event.getUser().getAsTag(); boolean optionalMessage = Objects.requireNonNull(event.getOption(OPTION_MESSAGE_PRIVATE)).getAsBoolean(); - // String reason = Objects.requireNonNull(event.getOption(REASON)).getAsString(); if (optionalMessage) { user = "Anonymous"; } @@ -122,9 +119,7 @@ private MessageEmbed messageEmbed(String user) { return new EmbedBuilder().setAuthor("Modmail Command invoked") .setColor(Color.BLACK) .setTitle("Message from user '%s' who used /modmail command".formatted(user)) - /* - * .addField("Reason", reason, false) - */.build(); + .build(); } @NotNull From e8c68d2eb1d41da0a21679c426ee33bef7edad4c Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sun, 14 Aug 2022 06:32:58 +0200 Subject: [PATCH 03/45] Adding modmail channel to config and reflecting those changes in command --- .../commands/moderation/modmail/ModMailCommand.java | 12 ++++++------ .../java/org/togetherjava/tjbot/config/Config.java | 11 +++++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 20bf2cc728..b5a160f853 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -41,7 +41,7 @@ public class ModMailCommand extends SlashCommandAdapter { private static final int COOLDOWN_DURATION_VALUE = 30; private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES; private final Cache channelIdToLastCommandInvocation; - private static Predicate auditLogChannelNamePredicate; + private final Predicate modMailChannelNamePredicate; /** @@ -60,8 +60,8 @@ public ModMailCommand(@NotNull Config config) { .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT)) .build(); - auditLogChannelNamePredicate = - Pattern.compile(config.getModAuditLogChannelPattern()).asMatchPredicate(); + modMailChannelNamePredicate = + Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); } @Override @@ -90,7 +90,7 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { // this message is creating the embed - String user = event.getUser().getAsTag(); + String user = event.getUser().getAsMention(); boolean optionalMessage = Objects.requireNonNull(event.getOption(OPTION_MESSAGE_PRIVATE)).getAsBoolean(); if (optionalMessage) { @@ -118,7 +118,7 @@ private MessageAction buildAttachment(List attachm private MessageEmbed messageEmbed(String user) { return new EmbedBuilder().setAuthor("Modmail Command invoked") .setColor(Color.BLACK) - .setTitle("Message from user '%s' who used /modmail command".formatted(user)) + .setTitle("/modmail from user '%s' ".formatted(user)) .build(); } @@ -139,7 +139,7 @@ private List getAttachments( } return guild.getTextChannelCache() .stream() - .filter(channel -> auditLogChannelNamePredicate.test(channel.getName())) + .filter(channel -> modMailChannelNamePredicate.test(channel.getName())) .findAny(); } diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java index d9b9d8a88f..8f5a341ed1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -21,6 +21,7 @@ public final class Config { private final String projectWebsite; private final String discordGuildInvite; private final String modAuditLogChannelPattern; + private final String modMailChannelPattern; private final String mutedRolePattern; private final String heavyModerationRolePattern; private final String softModerationRolePattern; @@ -117,6 +118,16 @@ public String getModAuditLogChannelPattern() { return modAuditLogChannelPattern; } + /** + * Gets the REGEX pattern used to identify the channel that is supposed to contain all messages + * from command modmail + * + * @return the channel name pattern + */ + public String getModMailChannelPattern() { + return modMailChannelPattern; + } + /** * Gets the token of the Discord bot to connect this application to. * From c132467632a9e4c268a6a57078850daba0bfb20f Mon Sep 17 00:00:00 2001 From: FoolProof Date: Mon, 15 Aug 2022 19:13:41 +0200 Subject: [PATCH 04/45] Removing comments, unnecessary lines and making methods --- .../moderation/modmail/ModMailCommand.java | 39 +++++++++++-------- 1 file changed, 22 insertions(+), 17 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index b5a160f853..abb0cdfca8 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -55,18 +55,22 @@ public ModMailCommand(@NotNull Config config) { .addOption(OptionType.BOOLEAN, OPTION_MESSAGE_PRIVATE, "do you wish for your message to stay private", false); - channelIdToLastCommandInvocation = Caffeine.newBuilder() - .maximumSize(1_000) - .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT)) - .build(); + channelIdToLastCommandInvocation = setCooldown(); modMailChannelNamePredicate = Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); } + @NotNull + private Cache setCooldown() { + return Caffeine.newBuilder() + .maximumSize(1_000) + .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT)) + .build(); + } + @Override public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { - // displays appropriate message, depending on if channel the command has been already called MessageChannel messageChannel = event.getChannel(); if (isChannelOnCooldown(messageChannel)) { event @@ -79,7 +83,6 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { } channelIdToLastCommandInvocation.put(messageChannel.getIdLong(), Instant.now()); - Optional auditLogChannel = getChannel(event); if (auditLogChannel.isEmpty()) { return; @@ -87,25 +90,27 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { List attachments = getAttachments(event); - - // this message is creating the embed - - String user = event.getUser().getAsMention(); - boolean optionalMessage = - Objects.requireNonNull(event.getOption(OPTION_MESSAGE_PRIVATE)).getAsBoolean(); - if (optionalMessage) { - user = "Anonymous"; - } + String user = getName(event); MessageAction message = auditLogChannel.orElseThrow().sendMessageEmbeds(messageEmbed(user)); message = buildAttachment(attachments, message); message.queue(); - // ends here event.reply("Thank you for contacting the moderators").setEphemeral(true).queue(); } + @NotNull + private String getName(@NotNull SlashCommandInteractionEvent event) { + String user = "@" + event.getUser().getName(); + boolean optionalMessage = + Objects.requireNonNull(event.getOption(OPTION_MESSAGE_PRIVATE)).getAsBoolean(); + if (optionalMessage) { + user = "Anonymous"; + } + return user; + } + private MessageAction buildAttachment(List attachments, MessageAction message) { for (ModAuditLogWriter.Attachment attachment : attachments) { @@ -118,7 +123,7 @@ private MessageAction buildAttachment(List attachm private MessageEmbed messageEmbed(String user) { return new EmbedBuilder().setAuthor("Modmail Command invoked") .setColor(Color.BLACK) - .setTitle("/modmail from user '%s' ".formatted(user)) + .setTitle("/modmail from '%s' ".formatted(user)) .build(); } From e2b4fd031a12ef0af5ec2c2f0edde14d72c86def Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sat, 20 Aug 2022 15:49:01 +0200 Subject: [PATCH 05/45] Improving the naming, removing require not null and additional ... Improvements requested from the reviews --- .../moderation/modmail/ModMailCommand.java | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index abb0cdfca8..9655249a92 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -19,8 +19,10 @@ import java.awt.*; import java.time.Instant; import java.time.temporal.ChronoUnit; +import java.util.ArrayList; import java.util.List; -import java.util.*; +import java.util.Locale; +import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -55,14 +57,14 @@ public ModMailCommand(@NotNull Config config) { .addOption(OptionType.BOOLEAN, OPTION_MESSAGE_PRIVATE, "do you wish for your message to stay private", false); - channelIdToLastCommandInvocation = setCooldown(); + channelIdToLastCommandInvocation = createCooldownCache(); modMailChannelNamePredicate = Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); } @NotNull - private Cache setCooldown() { + private Cache createCooldownCache() { return Caffeine.newBuilder() .maximumSize(1_000) .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT)) @@ -102,9 +104,8 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { @NotNull private String getName(@NotNull SlashCommandInteractionEvent event) { - String user = "@" + event.getUser().getName(); - boolean optionalMessage = - Objects.requireNonNull(event.getOption(OPTION_MESSAGE_PRIVATE)).getAsBoolean(); + String user = event.getUser().getAsMention(); + boolean optionalMessage = event.getOption(OPTION_MESSAGE_PRIVATE).getAsBoolean(); if (optionalMessage) { user = "Anonymous"; } @@ -130,7 +131,7 @@ private MessageEmbed messageEmbed(String user) { @NotNull private List getAttachments( @NotNull SlashCommandInteractionEvent event) { - String content = Objects.requireNonNull(event.getOption(MESSAGE)).getAsString(); + String content = event.getOption(MESSAGE).getAsString(); List attachments = new ArrayList<>(); attachments.add(new ModAuditLogWriter.Attachment("content.md", content)); return attachments; @@ -138,7 +139,7 @@ private List getAttachments( private @NotNull Optional getChannel(@NotNull SlashCommandInteractionEvent event) { long guildId = 1004371840245964851L; - Guild guild = event.getChannel().getJDA().getGuildById(guildId); + Guild guild = event.getJDA().getGuildById(guildId); if (guild == null) { return Optional.empty(); } From 238bea4d5d5dc576712310ab8c7608c2f39cf5d5 Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sat, 20 Aug 2022 16:28:06 +0200 Subject: [PATCH 06/45] Adding the time remaining since command called and bunch ... of helper methods --- .../moderation/modmail/ModMailCommand.java | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 9655249a92..2671d72e95 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -17,6 +17,7 @@ import org.togetherjava.tjbot.moderation.ModAuditLogWriter; import java.awt.*; +import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; @@ -75,9 +76,10 @@ private Cache createCooldownCache() { public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { MessageChannel messageChannel = event.getChannel(); if (isChannelOnCooldown(messageChannel)) { + System.out.println(getTimePassedSinceCommandCalled(messageChannel)); event .reply("Please wait a bit, this command can only be used once per %d %s.".formatted( - COOLDOWN_DURATION_VALUE, + getRemainingTime(messageChannel), COOLDOWN_DURATION_UNIT.toString().toLowerCase(Locale.US))) .setEphemeral(true) .queue(); @@ -102,6 +104,10 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { } + private long getRemainingTime(MessageChannel messageChannel) { + return COOLDOWN_DURATION_VALUE - getTimePassedSinceCommandCalled(messageChannel); + } + @NotNull private String getName(@NotNull SlashCommandInteractionEvent event) { String user = event.getUser().getAsMention(); @@ -158,4 +164,15 @@ private boolean isChannelOnCooldown(@NotNull MessageChannel channel) { .isPresent(); } + private Long getTimePassedSinceCommandCalled(@NotNull MessageChannel channel) { + return Optional + .ofNullable(channelIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) + .map(this::getTime) + .get(); + } + + private long getTime(Instant sinceCommandInvoked) { + return Duration.between(sinceCommandInvoked, Instant.now()).getSeconds() / 60; + } + } From 1f28832f996e80d6c09e7d83c990775a62131cb1 Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sat, 20 Aug 2022 16:39:27 +0200 Subject: [PATCH 07/45] Removing print statement also adding an else if the value is not present --- .../commands/moderation/modmail/ModMailCommand.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 2671d72e95..9ec6016ba9 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -76,7 +76,6 @@ private Cache createCooldownCache() { public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { MessageChannel messageChannel = event.getChannel(); if (isChannelOnCooldown(messageChannel)) { - System.out.println(getTimePassedSinceCommandCalled(messageChannel)); event .reply("Please wait a bit, this command can only be used once per %d %s.".formatted( getRemainingTime(messageChannel), @@ -164,15 +163,16 @@ private boolean isChannelOnCooldown(@NotNull MessageChannel channel) { .isPresent(); } - private Long getTimePassedSinceCommandCalled(@NotNull MessageChannel channel) { + private int getTimePassedSinceCommandCalled(@NotNull MessageChannel channel) { return Optional .ofNullable(channelIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) .map(this::getTime) - .get(); + .orElse(COOLDOWN_DURATION_VALUE); } - private long getTime(Instant sinceCommandInvoked) { - return Duration.between(sinceCommandInvoked, Instant.now()).getSeconds() / 60; + private int getTime(Instant sinceCommandInvoked) { + return Math + .toIntExact(Duration.between(sinceCommandInvoked, Instant.now()).getSeconds() / 60); } } From 9e1027fd81616eb74086af25440bc2d53bd6d160 Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sat, 20 Aug 2022 17:36:25 +0200 Subject: [PATCH 08/45] Changing from Math.toExactInt to a int cast instead for sonar --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 9ec6016ba9..8f11ea9fd3 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -171,8 +171,7 @@ private int getTimePassedSinceCommandCalled(@NotNull MessageChannel channel) { } private int getTime(Instant sinceCommandInvoked) { - return Math - .toIntExact(Duration.between(sinceCommandInvoked, Instant.now()).getSeconds() / 60); + return (int) Duration.between(sinceCommandInvoked, Instant.now()).toMinutes(); } } From d8b00127fee8de4dcc792d5f07e4fe40e8a34785 Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sat, 20 Aug 2022 17:43:49 +0200 Subject: [PATCH 09/45] Different math operant sonar , attempt #2 --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 8f11ea9fd3..ee062e82da 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -103,7 +103,7 @@ public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { } - private long getRemainingTime(MessageChannel messageChannel) { + private int getRemainingTime(MessageChannel messageChannel) { return COOLDOWN_DURATION_VALUE - getTimePassedSinceCommandCalled(messageChannel); } From 6cbdcbb74cdf43db305b73d29476c00c0a1d5ccd Mon Sep 17 00:00:00 2001 From: FoolProof Date: Mon, 22 Aug 2022 14:52:35 +0200 Subject: [PATCH 10/45] Removing the guild id and adding guildNamePredicate instead --- .../commands/moderation/modmail/ModMailCommand.java | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index ee062e82da..c79baa055a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -45,6 +45,7 @@ public class ModMailCommand extends SlashCommandAdapter { private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES; private final Cache channelIdToLastCommandInvocation; private final Predicate modMailChannelNamePredicate; + private final Predicate guildNamePatternPredicate; /** @@ -62,6 +63,8 @@ public ModMailCommand(@NotNull Config config) { modMailChannelNamePredicate = Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); + guildNamePatternPredicate = + Pattern.compile(config.getGuildNamePattern()).asMatchPredicate(); } @NotNull @@ -143,8 +146,12 @@ private List getAttachments( } private @NotNull Optional getChannel(@NotNull SlashCommandInteractionEvent event) { - long guildId = 1004371840245964851L; - Guild guild = event.getJDA().getGuildById(guildId); + Guild guild = event.getJDA() + .getGuildCache() + .stream() + .filter(guildName -> guildNamePatternPredicate.test(guildName.getName())) + .toList() + .get(0); if (guild == null) { return Optional.empty(); } From 69279a2cae8f68d7bfe95bdb572b9b5e4437c449 Mon Sep 17 00:00:00 2001 From: FoolProof Date: Fri, 16 Sep 2022 08:13:59 +0200 Subject: [PATCH 11/45] Making the class final --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index c79baa055a..d5b42591d7 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -36,7 +36,7 @@ * {@link Config#getModAuditLogChannelPattern()}. */ -public class ModMailCommand extends SlashCommandAdapter { +public final class ModMailCommand extends SlashCommandAdapter { private static final String COMMAND_NAME = "modmail"; private static final String MESSAGE = "message"; From 4d097dca2f8d1ebb5b8c780a2be00334d0af0b0a Mon Sep 17 00:00:00 2001 From: FoolProof Date: Fri, 16 Sep 2022 10:28:31 +0200 Subject: [PATCH 12/45] Removing @NotNull --- .../moderation/modmail/ModMailCommand.java | 20 +++++++------------ 1 file changed, 7 insertions(+), 13 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index d5b42591d7..da9d6e00a2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -10,7 +10,6 @@ import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.requests.restaction.MessageAction; -import org.jetbrains.annotations.NotNull; import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; @@ -53,7 +52,7 @@ public final class ModMailCommand extends SlashCommandAdapter { * * @param config the config to use for this */ - public ModMailCommand(@NotNull Config config) { + public ModMailCommand(Config config) { super(COMMAND_NAME, "Sends a message to the moderators", SlashCommandVisibility.GLOBAL); getData().addOption(OptionType.STRING, MESSAGE, "Message to the moderators", true) .addOption(OptionType.BOOLEAN, OPTION_MESSAGE_PRIVATE, @@ -67,7 +66,6 @@ public ModMailCommand(@NotNull Config config) { Pattern.compile(config.getGuildNamePattern()).asMatchPredicate(); } - @NotNull private Cache createCooldownCache() { return Caffeine.newBuilder() .maximumSize(1_000) @@ -76,7 +74,7 @@ private Cache createCooldownCache() { } @Override - public void onSlashCommand(@NotNull SlashCommandInteractionEvent event) { + public void onSlashCommand(SlashCommandInteractionEvent event) { MessageChannel messageChannel = event.getChannel(); if (isChannelOnCooldown(messageChannel)) { event @@ -110,8 +108,7 @@ private int getRemainingTime(MessageChannel messageChannel) { return COOLDOWN_DURATION_VALUE - getTimePassedSinceCommandCalled(messageChannel); } - @NotNull - private String getName(@NotNull SlashCommandInteractionEvent event) { + private String getName(SlashCommandInteractionEvent event) { String user = event.getUser().getAsMention(); boolean optionalMessage = event.getOption(OPTION_MESSAGE_PRIVATE).getAsBoolean(); if (optionalMessage) { @@ -128,7 +125,6 @@ private MessageAction buildAttachment(List attachm return message; } - @NotNull private MessageEmbed messageEmbed(String user) { return new EmbedBuilder().setAuthor("Modmail Command invoked") .setColor(Color.BLACK) @@ -136,16 +132,14 @@ private MessageEmbed messageEmbed(String user) { .build(); } - @NotNull - private List getAttachments( - @NotNull SlashCommandInteractionEvent event) { + private List getAttachments(SlashCommandInteractionEvent event) { String content = event.getOption(MESSAGE).getAsString(); List attachments = new ArrayList<>(); attachments.add(new ModAuditLogWriter.Attachment("content.md", content)); return attachments; } - private @NotNull Optional getChannel(@NotNull SlashCommandInteractionEvent event) { + private Optional getChannel(SlashCommandInteractionEvent event) { Guild guild = event.getJDA() .getGuildCache() .stream() @@ -161,7 +155,7 @@ private List getAttachments( .findAny(); } - private boolean isChannelOnCooldown(@NotNull MessageChannel channel) { + private boolean isChannelOnCooldown(MessageChannel channel) { return Optional .ofNullable(channelIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) .map(sinceCommandInvoked -> sinceCommandInvoked.plus(COOLDOWN_DURATION_VALUE, @@ -170,7 +164,7 @@ private boolean isChannelOnCooldown(@NotNull MessageChannel channel) { .isPresent(); } - private int getTimePassedSinceCommandCalled(@NotNull MessageChannel channel) { + private int getTimePassedSinceCommandCalled(MessageChannel channel) { return Optional .ofNullable(channelIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) .map(this::getTime) From 0446811835476dfb4601ac220fde295c864742ba Mon Sep 17 00:00:00 2001 From: FoolProof Date: Sun, 18 Sep 2022 15:40:03 +0200 Subject: [PATCH 13/45] Removing BlackListedListener --- .../src/main/java/org/togetherjava/tjbot/commands/Features.java | 1 + 1 file changed, 1 insertion(+) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index cf6fb94c17..2c8ef24868 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -13,6 +13,7 @@ import org.togetherjava.tjbot.commands.mediaonly.MediaOnlyChannelListener; import org.togetherjava.tjbot.commands.moderation.*; import org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener; +import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; import org.togetherjava.tjbot.commands.moderation.scam.ScamBlocker; import org.togetherjava.tjbot.commands.moderation.scam.ScamHistoryPurgeRoutine; import org.togetherjava.tjbot.commands.moderation.scam.ScamHistoryStore; From 4da1ef3b8bc6b9d4dd39608b3e6cc7d40be8d630 Mon Sep 17 00:00:00 2001 From: FoolProof Date: Wed, 28 Sep 2022 14:36:46 +0200 Subject: [PATCH 14/45] Adding a modmail command message to all channels which handles DM's --- .../org/togetherjava/tjbot/commands/moderation/BanCommand.java | 2 +- .../org/togetherjava/tjbot/commands/moderation/KickCommand.java | 2 +- .../org/togetherjava/tjbot/commands/moderation/MuteCommand.java | 2 +- .../tjbot/commands/moderation/QuarantineCommand.java | 2 +- .../org/togetherjava/tjbot/commands/moderation/WarnCommand.java | 2 +- .../moderation/attachment/BlacklistedAttachmentListener.java | 1 + .../tjbot/commands/moderation/scam/ScamBlocker.java | 2 +- .../src/main/java/org/togetherjava/tjbot/config/Config.java | 2 +- 8 files changed, 8 insertions(+), 7 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 751c15679e..50736080f6 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 @@ -91,7 +91,7 @@ private static RestAction sendDm(ISnowflake target, String dmMessage = """ Hey there, sorry to tell you but unfortunately you have been banned %s from the server %s. - If you think this was a mistake, please contact a moderator or admin of the server. + To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: The reason for the ban is: %s """ .formatted(durationMessage, guild.getName(), reason); 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 696476a3e6..8794ed51b3 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 @@ -75,7 +75,7 @@ private static RestAction sendDm(ISnowflake target, String reason, Guil .flatMap(channel -> channel.sendMessage( """ Hey there, sorry to tell you but unfortunately you have been kicked from the server %s. - If you think this was a mistake, please contact a moderator or admin of the server. + To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: The reason for the kick is: %s """ .formatted(guild.getName(), reason))) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java index c925496ad1..8142696a90 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -79,7 +79,7 @@ private static RestAction sendDm(ISnowflake target, """ Hey there, sorry to tell you but unfortunately you have been muted %s in the server %s. This means you can no longer send any messages in the server until you have been unmuted again. - If you think this was a mistake, please contact a moderator or admin of the server. + To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: The reason for the mute is: %s """ .formatted(durationMessage, guild.getName(), reason); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java index 7dd2efdb5d..d718483878 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java @@ -67,7 +67,7 @@ private static RestAction sendDm(ISnowflake target, String reason, Guil """ Hey there, sorry to tell you but unfortunately you have been put under quarantine in the server %s. This means you can no longer interact with anyone in the server until you have been unquarantined again. - If you think this was a mistake, or the reason no longer applies, please contact a moderator or admin of the server. + To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: The reason for the quarantine is: %s """ .formatted(guild.getName(), reason); 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 0e52fea049..d40c4489f9 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 @@ -63,7 +63,7 @@ private static RestAction dmUser(ISnowflake target, String reason, Guil .flatMap(channel -> channel.sendMessage( """ 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. + To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: The reason for the warning is: %s """ .formatted(guild.getName(), reason))) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java index cd42cc2d82..304af4a119 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java @@ -66,6 +66,7 @@ private MessageCreateData createDmMessage(Message originalMessage) { Hey there, you posted a message containing a blacklisted file attachment: %s. We had to delete your message for security reasons. + To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: Feel free to repost your message without, or with a different file instead. Sorry for any inconvenience caused by this 🙇️ """ .formatted(blacklistedAttachments); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java index 6cb668ab08..4f1ad764f3 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java @@ -255,7 +255,7 @@ private void dmUser(Guild guild, long userId, JDA jda) { This means you can no longer interact with anyone in the server until you have been unquarantined again. If you think this was a mistake (for example, your account was hacked, but you got back control over it), - please contact a moderator or admin of the server. + than to get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: """ .formatted(guild.getName()); diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java index 8f5a341ed1..5f54851593 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -120,7 +120,7 @@ public String getModAuditLogChannelPattern() { /** * Gets the REGEX pattern used to identify the channel that is supposed to contain all messages - * from command modmail + * from users who want to contact a moderator * * @return the channel name pattern */ From 1b55f9ee02ee3dea6e2c448426a61bd484c09eab Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Fri, 30 Sep 2022 17:04:11 +0200 Subject: [PATCH 15/45] Adding the changes mentioned in the PR --- .../moderation/modmail/ModMailCommand.java | 109 ++++++++---------- 1 file changed, 51 insertions(+), 58 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index da9d6e00a2..5af1906419 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -3,20 +3,23 @@ import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Caffeine; import net.dv8tion.jda.api.EmbedBuilder; +import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.MessageChannel; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.OptionType; +import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.restaction.MessageAction; +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.moderation.ModAuditLogWriter; import java.awt.*; -import java.time.Duration; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.ArrayList; @@ -28,8 +31,11 @@ import java.util.regex.Pattern; /** - * Implements the '/modmail' command which can be used to automatically redirects messages from DM - * or Guild. + * Implements the /modmail command, which allows users to contact a moderator within the server or + * even if not part of the server anymore, e.g. after a ban. + *

+ * Therefore, the user DMs the bot and the message are forwarded to moderators in a dedicated + * channel. *

* Actions are then logged to a dedicated channel, given by * {@link Config#getModAuditLogChannelPattern()}. @@ -37,14 +43,16 @@ public final class ModMailCommand extends SlashCommandAdapter { + private static final Logger logger = LoggerFactory.getLogger(ModMailCommand.class); private static final String COMMAND_NAME = "modmail"; - private static final String MESSAGE = "message"; - private static final String OPTION_MESSAGE_PRIVATE = "message-private"; + private static final String OPTION_MESSAGE = "message"; + private static final String OPTION_STAY_ANONYMOUS = "stay-anonymous"; + private static final String OPTION_SERVER_GUILD = "server-guild"; private static final int COOLDOWN_DURATION_VALUE = 30; private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES; - private final Cache channelIdToLastCommandInvocation; + private final Cache authorIdToLastCommandInvocation = createCooldownCache(); private final Predicate modMailChannelNamePredicate; - private final Predicate guildNamePatternPredicate; + private static final Color AMBIENT_COLOR = Color.black; /** @@ -53,17 +61,18 @@ public final class ModMailCommand extends SlashCommandAdapter { * @param config the config to use for this */ public ModMailCommand(Config config) { - super(COMMAND_NAME, "Sends a message to the moderators", SlashCommandVisibility.GLOBAL); - getData().addOption(OptionType.STRING, MESSAGE, "Message to the moderators", true) - .addOption(OptionType.BOOLEAN, OPTION_MESSAGE_PRIVATE, - "do you wish for your message to stay private", false); + super(COMMAND_NAME, "Send a message to the moderators of the selected guild", + SlashCommandVisibility.GLOBAL); + + getData() + .addOption(OptionType.STRING, OPTION_MESSAGE, "What do you want to tell them?", true) + .addOption(OptionType.STRING, OPTION_SERVER_GUILD, "Your guild name", true) + .addOption(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, "if set, your name is hidden", + false); - channelIdToLastCommandInvocation = createCooldownCache(); modMailChannelNamePredicate = Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); - guildNamePatternPredicate = - Pattern.compile(config.getGuildNamePattern()).asMatchPredicate(); } private Cache createCooldownCache() { @@ -78,24 +87,26 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { MessageChannel messageChannel = event.getChannel(); if (isChannelOnCooldown(messageChannel)) { event - .reply("Please wait a bit, this command can only be used once per %d %s.".formatted( - getRemainingTime(messageChannel), - COOLDOWN_DURATION_UNIT.toString().toLowerCase(Locale.US))) + .reply("Can only be used once per %s." + .formatted(COOLDOWN_DURATION_UNIT.toString().toLowerCase(Locale.US))) .setEphemeral(true) .queue(); return; } - channelIdToLastCommandInvocation.put(messageChannel.getIdLong(), Instant.now()); + authorIdToLastCommandInvocation.put(messageChannel.getIdLong(), Instant.now()); - Optional auditLogChannel = getChannel(event); - if (auditLogChannel.isEmpty()) { + Optional modMailAuditLog = getChannel(event); + if (modMailAuditLog.isEmpty()) { + logger.warn("This modmail audit log is empty."); return; } - List attachments = getAttachments(event); + String content = event.getOption(OPTION_MESSAGE).getAsString(); + List attachments = getAttachments(content); - String user = getName(event); - MessageAction message = auditLogChannel.orElseThrow().sendMessageEmbeds(messageEmbed(user)); + String user = getAuthorName(event); + MessageAction message = + modMailAuditLog.orElseThrow().sendMessageEmbeds(createModMailMessage(user)); message = buildAttachment(attachments, message); message.queue(); @@ -104,17 +115,13 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { } - private int getRemainingTime(MessageChannel messageChannel) { - return COOLDOWN_DURATION_VALUE - getTimePassedSinceCommandCalled(messageChannel); - } - private String getName(SlashCommandInteractionEvent event) { - String user = event.getUser().getAsMention(); - boolean optionalMessage = event.getOption(OPTION_MESSAGE_PRIVATE).getAsBoolean(); - if (optionalMessage) { - user = "Anonymous"; + private String getAuthorName(SlashCommandInteractionEvent event) { + boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); + if (wantsToStayAnonymous) { + return "Anonymous"; } - return user; + return event.getUser().getAsMention(); } private MessageAction buildAttachment(List attachments, @@ -125,31 +132,28 @@ private MessageAction buildAttachment(List attachm return message; } - private MessageEmbed messageEmbed(String user) { - return new EmbedBuilder().setAuthor("Modmail Command invoked") - .setColor(Color.BLACK) - .setTitle("/modmail from '%s' ".formatted(user)) + private MessageEmbed createModMailMessage(String user) { + return new EmbedBuilder().setAuthor("/modmail from '%s' ".formatted(user)) + .setColor(AMBIENT_COLOR) + .setTitle("Modmail") .build(); } - private List getAttachments(SlashCommandInteractionEvent event) { - String content = event.getOption(MESSAGE).getAsString(); + private List getAttachments(String content) { List attachments = new ArrayList<>(); attachments.add(new ModAuditLogWriter.Attachment("content.md", content)); return attachments; } private Optional getChannel(SlashCommandInteractionEvent event) { - Guild guild = event.getJDA() + String userGuildName = event.getOption(OPTION_SERVER_GUILD).getAsString(); + return event.getJDA() .getGuildCache() .stream() - .filter(guildName -> guildNamePatternPredicate.test(guildName.getName())) - .toList() - .get(0); - if (guild == null) { - return Optional.empty(); - } - return guild.getTextChannelCache() + .filter(guild -> guild.getName().equals(userGuildName)) + .findAny() + .orElseThrow() + .getTextChannelCache() .stream() .filter(channel -> modMailChannelNamePredicate.test(channel.getName())) .findAny(); @@ -157,22 +161,11 @@ private Optional getChannel(SlashCommandInteractionEvent event) { private boolean isChannelOnCooldown(MessageChannel channel) { return Optional - .ofNullable(channelIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) + .ofNullable(authorIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) .map(sinceCommandInvoked -> sinceCommandInvoked.plus(COOLDOWN_DURATION_VALUE, COOLDOWN_DURATION_UNIT)) .filter(Instant.now()::isBefore) .isPresent(); } - private int getTimePassedSinceCommandCalled(MessageChannel channel) { - return Optional - .ofNullable(channelIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) - .map(this::getTime) - .orElse(COOLDOWN_DURATION_VALUE); - } - - private int getTime(Instant sinceCommandInvoked) { - return (int) Duration.between(sinceCommandInvoked, Instant.now()).toMinutes(); - } - } From 536890cb69a6821426907ffa2514d7c6bd6eb740 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Fri, 30 Sep 2022 19:05:59 +0200 Subject: [PATCH 16/45] Adding the choice for the user guild --- .../moderation/modmail/ModMailCommand.java | 31 ++++++++++++------- 1 file changed, 20 insertions(+), 11 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 5af1906419..7f8ef02c00 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -4,18 +4,18 @@ import com.github.benmanes.caffeine.cache.Caffeine; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.MessageChannel; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.restaction.MessageAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.SlashCommandVisibility; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.moderation.ModAuditLogWriter; @@ -60,16 +60,25 @@ public final class ModMailCommand extends SlashCommandAdapter { * * @param config the config to use for this */ - public ModMailCommand(Config config) { + public ModMailCommand(JDA jda, Config config) { super(COMMAND_NAME, "Send a message to the moderators of the selected guild", - SlashCommandVisibility.GLOBAL); + CommandVisibility.GLOBAL); - getData() - .addOption(OptionType.STRING, OPTION_MESSAGE, "What do you want to tell them?", true) - .addOption(OptionType.STRING, OPTION_SERVER_GUILD, "Your guild name", true) - .addOption(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, "if set, your name is hidden", - false); + OptionData message = new OptionData(OptionType.STRING, OPTION_MESSAGE, + "What do you want to tell them?", true); + OptionData guildOption = new OptionData(OptionType.STRING, OPTION_SERVER_GUILD, + "Your server guild ID", true); + OptionData anonymous = new OptionData(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, + "if set, your name is hidden", false); + List choices = jda.getGuildCache() + .stream() + .map(guild -> new Command.Choice(guild.getName(), guild.getIdLong())) + .toList(); + + guildOption.addChoices(choices); + + getData().addOptions(message, guildOption, anonymous); modMailChannelNamePredicate = Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); @@ -146,11 +155,11 @@ private List getAttachments(String content) { } private Optional getChannel(SlashCommandInteractionEvent event) { - String userGuildName = event.getOption(OPTION_SERVER_GUILD).getAsString(); + long userGuildId = event.getOption(OPTION_SERVER_GUILD).getAsLong(); return event.getJDA() .getGuildCache() .stream() - .filter(guild -> guild.getName().equals(userGuildName)) + .filter(guild -> guild.getIdLong() == userGuildId) .findAny() .orElseThrow() .getTextChannelCache() From d6bbeebb64c5c6f5a519f139af0cfe933a76a773 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Fri, 30 Sep 2022 19:12:37 +0200 Subject: [PATCH 17/45] Adding param into the comment --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 7f8ef02c00..6dbabb807d 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -57,7 +57,8 @@ public final class ModMailCommand extends SlashCommandAdapter { /** * Creates a new instance. - * + * + * @param jda the JDA instance to use to retrieve guildCache * @param config the config to use for this */ public ModMailCommand(JDA jda, Config config) { From fefc27e1c54382fe2571aca4ae0c056f89109746 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Mon, 3 Oct 2022 15:22:04 +0200 Subject: [PATCH 18/45] Adding the improvements from the code review --- .../moderation/modmail/ModMailCommand.java | 56 ++++++------------- 1 file changed, 18 insertions(+), 38 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 6dbabb807d..c0004a5aab 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -4,9 +4,7 @@ import com.github.benmanes.caffeine.cache.Caffeine; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.entities.MessageChannel; -import net.dv8tion.jda.api.entities.MessageEmbed; -import net.dv8tion.jda.api.entities.TextChannel; +import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; @@ -16,19 +14,21 @@ import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.help.HelpSystemHelper; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.moderation.ModAuditLogWriter; import java.awt.*; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.ArrayList; +import java.util.*; import java.util.List; -import java.util.Locale; -import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Pattern; +import java.util.stream.Collectors; + +import static org.togetherjava.tjbot.commands.utils.StringDistances.prefixEditDistance; /** * Implements the /modmail command, which allows users to contact a moderator within the server or @@ -65,11 +65,11 @@ public ModMailCommand(JDA jda, Config config) { super(COMMAND_NAME, "Send a message to the moderators of the selected guild", CommandVisibility.GLOBAL); - OptionData message = new OptionData(OptionType.STRING, OPTION_MESSAGE, + OptionData messageOption = new OptionData(OptionType.STRING, OPTION_MESSAGE, "What do you want to tell them?", true); OptionData guildOption = new OptionData(OptionType.STRING, OPTION_SERVER_GUILD, "Your server guild ID", true); - OptionData anonymous = new OptionData(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, + OptionData anonymousOption = new OptionData(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, "if set, your name is hidden", false); List choices = jda.getGuildCache() @@ -79,7 +79,7 @@ public ModMailCommand(JDA jda, Config config) { guildOption.addChoices(choices); - getData().addOptions(message, guildOption, anonymous); + getData().addOptions(messageOption, guildOption, anonymousOption); modMailChannelNamePredicate = Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); @@ -111,14 +111,12 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { return; } - String content = event.getOption(OPTION_MESSAGE).getAsString(); - List attachments = getAttachments(content); + String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); String user = getAuthorName(event); - MessageAction message = - modMailAuditLog.orElseThrow().sendMessageEmbeds(createModMailMessage(user)); + MessageAction message = modMailAuditLog.orElseThrow() + .sendMessageEmbeds(createModMailMessage(user, userMessage)); - message = buildAttachment(attachments, message); message.queue(); event.reply("Thank you for contacting the moderators").setEphemeral(true).queue(); @@ -134,36 +132,18 @@ private String getAuthorName(SlashCommandInteractionEvent event) { return event.getUser().getAsMention(); } - private MessageAction buildAttachment(List attachments, - MessageAction message) { - for (ModAuditLogWriter.Attachment attachment : attachments) { - message = message.addFile(attachment.getContentRaw(), attachment.name()); - } - return message; - } - - private MessageEmbed createModMailMessage(String user) { - return new EmbedBuilder().setAuthor("/modmail from '%s' ".formatted(user)) + private MessageEmbed createModMailMessage(String user, String userMessage) { + return new EmbedBuilder().setDescription("**/modmail from %s** ".formatted(user)) + .setFooter(userMessage) .setColor(AMBIENT_COLOR) - .setTitle("Modmail") .build(); } - private List getAttachments(String content) { - List attachments = new ArrayList<>(); - attachments.add(new ModAuditLogWriter.Attachment("content.md", content)); - return attachments; - } - private Optional getChannel(SlashCommandInteractionEvent event) { long userGuildId = event.getOption(OPTION_SERVER_GUILD).getAsLong(); - return event.getJDA() - .getGuildCache() - .stream() - .filter(guild -> guild.getIdLong() == userGuildId) - .findAny() - .orElseThrow() - .getTextChannelCache() + Guild guild = Objects.requireNonNull(event.getJDA().getGuildById(userGuildId), + "Something went wrong with selecting the guild."); + return guild.getTextChannelCache() .stream() .filter(channel -> modMailChannelNamePredicate.test(channel.getName())) .findAny(); From 68723e0d903ef469236daa196cd860c4a4e831f6 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Mon, 3 Oct 2022 15:26:40 +0200 Subject: [PATCH 19/45] Removing unnecessary imports --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 5 ----- 1 file changed, 5 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index c0004a5aab..4dabf066c2 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -14,9 +14,7 @@ import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; -import org.togetherjava.tjbot.commands.help.HelpSystemHelper; import org.togetherjava.tjbot.config.Config; -import org.togetherjava.tjbot.moderation.ModAuditLogWriter; import java.awt.*; import java.time.Instant; @@ -26,9 +24,6 @@ import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Pattern; -import java.util.stream.Collectors; - -import static org.togetherjava.tjbot.commands.utils.StringDistances.prefixEditDistance; /** * Implements the /modmail command, which allows users to contact a moderator within the server or From 433621fd9dc90ade059517f56d91909682203278 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 5 Oct 2022 21:34:30 +0200 Subject: [PATCH 20/45] Resolving all conflicts and making improvements --- .../org/togetherjava/tjbot/commands/Features.java | 5 +---- .../moderation/modmail/ModMailCommand.java | 15 ++++++++++----- .../org/togetherjava/tjbot/config/Config.java | 3 +++ 3 files changed, 14 insertions(+), 9 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index 2c8ef24868..28c4f1284f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/Features.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java @@ -127,10 +127,7 @@ public static Collection createFeatures(JDA jda, Database database, Con features.add(new WhoIsCommand()); features.add(new WolframAlphaCommand(config)); features.add(new AskCommand(config, helpSystemHelper)); - features.add(new CloseCommand()); - features.add(new ChangeHelpCategoryCommand(config, helpSystemHelper)); - features.add(new ChangeHelpTitleCommand(helpSystemHelper)); - features.add(new ModMailCommand(config)); + features.add(new ModMailCommand(jda, config)); features.add(new HelpThreadCommand(config, helpSystemHelper)); // Mixtures diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 4dabf066c2..5292b5db28 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -4,27 +4,32 @@ import com.github.benmanes.caffeine.cache.Caffeine; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.Guild; +import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; +import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; -import net.dv8tion.jda.api.requests.restaction.MessageAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.config.Config; - +import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; import java.awt.*; import java.time.Instant; import java.time.temporal.ChronoUnit; -import java.util.*; import java.util.List; +import java.util.Locale; +import java.util.Objects; +import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Pattern; + /** * Implements the /modmail command, which allows users to contact a moderator within the server or * even if not part of the server anymore, e.g. after a ban. @@ -109,7 +114,7 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); String user = getAuthorName(event); - MessageAction message = modMailAuditLog.orElseThrow() + MessageCreateAction message = modMailAuditLog.orElseThrow() .sendMessageEmbeds(createModMailMessage(user, userMessage)); message.queue(); diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java index 5f54851593..8be3b5dd06 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -45,6 +45,8 @@ private Config(@JsonProperty(value = "token", required = true) String token, @JsonProperty(value = "discordGuildInvite", required = true) String discordGuildInvite, @JsonProperty(value = "modAuditLogChannelPattern", required = true) String modAuditLogChannelPattern, + @JsonProperty(value = "modMailChannelPattern", + required = true) String modMailChannelPattern, @JsonProperty(value = "mutedRolePattern", required = true) String mutedRolePattern, @JsonProperty(value = "heavyModerationRolePattern", required = true) String heavyModerationRolePattern, @@ -72,6 +74,7 @@ private Config(@JsonProperty(value = "token", required = true) String token, this.projectWebsite = Objects.requireNonNull(projectWebsite); this.discordGuildInvite = Objects.requireNonNull(discordGuildInvite); this.modAuditLogChannelPattern = Objects.requireNonNull(modAuditLogChannelPattern); + this.modMailChannelPattern = Objects.requireNonNull(modMailChannelPattern); this.mutedRolePattern = Objects.requireNonNull(mutedRolePattern); this.heavyModerationRolePattern = Objects.requireNonNull(heavyModerationRolePattern); this.softModerationRolePattern = Objects.requireNonNull(softModerationRolePattern); From 5d3a3b448359485818c0c8845e5b9331e3a41b6e Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Thu, 6 Oct 2022 16:48:52 +0200 Subject: [PATCH 21/45] Making more changes --- .../moderation/modmail/ModMailCommand.java | 58 +++++++++---------- 1 file changed, 28 insertions(+), 30 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 5292b5db28..2d8438c5ca 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -5,24 +5,26 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Guild; -import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; +import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; +import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; +import org.togetherjava.tjbot.commands.utils.DiscordClientAction; import org.togetherjava.tjbot.config.Config; -import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; + import java.awt.*; import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; -import java.util.Locale; import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; @@ -50,14 +52,14 @@ public final class ModMailCommand extends SlashCommandAdapter { private static final String OPTION_SERVER_GUILD = "server-guild"; private static final int COOLDOWN_DURATION_VALUE = 30; private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES; + private static final Color AMBIENT_COLOR = Color.black; private final Cache authorIdToLastCommandInvocation = createCooldownCache(); private final Predicate modMailChannelNamePredicate; - private static final Color AMBIENT_COLOR = Color.black; /** * Creates a new instance. - * + * * @param jda the JDA instance to use to retrieve guildCache * @param config the config to use for this */ @@ -70,7 +72,7 @@ public ModMailCommand(JDA jda, Config config) { OptionData guildOption = new OptionData(OptionType.STRING, OPTION_SERVER_GUILD, "Your server guild ID", true); OptionData anonymousOption = new OptionData(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, - "if set, your name is hidden", false); + "if set, your name is hidden", true); List choices = jda.getGuildCache() .stream() @@ -94,28 +96,34 @@ private Cache createCooldownCache() { @Override public void onSlashCommand(SlashCommandInteractionEvent event) { - MessageChannel messageChannel = event.getChannel(); - if (isChannelOnCooldown(messageChannel)) { - event - .reply("Can only be used once per %s." - .formatted(COOLDOWN_DURATION_UNIT.toString().toLowerCase(Locale.US))) + long userId = event.getUser().getIdLong(); + if (isChannelOnCooldown(userId)) { + event.reply("Can only be used once per %s minutes.".formatted(COOLDOWN_DURATION_VALUE)) .setEphemeral(true) .queue(); return; } - authorIdToLastCommandInvocation.put(messageChannel.getIdLong(), Instant.now()); + authorIdToLastCommandInvocation.put(userId, Instant.now()); Optional modMailAuditLog = getChannel(event); if (modMailAuditLog.isEmpty()) { - logger.warn("This modmail audit log is empty."); + logger.warn("Cannot find the designated modmail channel in this server."); return; } String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); - - String user = getAuthorName(event); + boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); + String user = event.getUser().getAsMention(); MessageCreateAction message = modMailAuditLog.orElseThrow() - .sendMessageEmbeds(createModMailMessage(user, userMessage)); + .sendMessageEmbeds(createModMailMessage(user, userMessage)) + .addActionRow(DiscordClientAction.General.USER.asLinkButton("Click to see profile!", + String.valueOf(userId))); + + if (wantsToStayAnonymous) { + user = "Anonymous"; + message = modMailAuditLog.orElseThrow() + .sendMessageEmbeds(createModMailMessage(user, userMessage)); + } message.queue(); @@ -123,18 +131,9 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { } - - private String getAuthorName(SlashCommandInteractionEvent event) { - boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); - if (wantsToStayAnonymous) { - return "Anonymous"; - } - return event.getUser().getAsMention(); - } - private MessageEmbed createModMailMessage(String user, String userMessage) { - return new EmbedBuilder().setDescription("**/modmail from %s** ".formatted(user)) - .setFooter(userMessage) + return new EmbedBuilder().setTitle("**/modmail from %s** ".formatted(user)) + .setDescription(userMessage) .setColor(AMBIENT_COLOR) .build(); } @@ -149,9 +148,8 @@ private Optional getChannel(SlashCommandInteractionEvent event) { .findAny(); } - private boolean isChannelOnCooldown(MessageChannel channel) { - return Optional - .ofNullable(authorIdToLastCommandInvocation.getIfPresent(channel.getIdLong())) + private boolean isChannelOnCooldown(long userId) { + return Optional.ofNullable(authorIdToLastCommandInvocation.getIfPresent(userId)) .map(sinceCommandInvoked -> sinceCommandInvoked.plus(COOLDOWN_DURATION_VALUE, COOLDOWN_DURATION_UNIT)) .filter(Instant.now()::isBefore) From 3edf7ef8819d4231971a135b927c3dca492dceba Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Thu, 6 Oct 2022 16:52:29 +0200 Subject: [PATCH 22/45] Removing unused imports --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 2 -- 1 file changed, 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 2d8438c5ca..42e00c5101 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -8,12 +8,10 @@ import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; -import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; -import net.dv8tion.jda.api.requests.restaction.interactions.ReplyCallbackAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.CommandVisibility; From 8dcc750c72d35efcb4f48eec2aa86f0bee7a0782 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Thu, 6 Oct 2022 17:26:27 +0200 Subject: [PATCH 23/45] Adding a package.info --- .../commands/moderation/modmail/package-info.java | 10 ++++++++++ 1 file changed, 10 insertions(+) create mode 100644 application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java new file mode 100644 index 0000000000..22cbc8fe0f --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java @@ -0,0 +1,10 @@ +/** + * This packages offers all the functionality for mod mail messages. + */ +@MethodsReturnNonnullByDefault +@ParametersAreNonnullByDefault +package org.togetherjava.tjbot.commands.moderation.modmail; + +import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; + +import javax.annotation.ParametersAreNonnullByDefault; From 6cf7926ef83ada0276bfd8cd9d4df0e91ad8d9b3 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Thu, 6 Oct 2022 17:27:59 +0200 Subject: [PATCH 24/45] Improving the message package info --- .../tjbot/commands/moderation/modmail/package-info.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java index 22cbc8fe0f..4bb2fa2d94 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java @@ -1,5 +1,5 @@ /** - * This packages offers all the functionality for mod mail messages. + * This packages offers all the functionality for messaging moderators trough mod mail. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault From 8f17dad0ee9003261938bf45ebf5e4226b58e0c7 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Sat, 8 Oct 2022 11:33:07 +0200 Subject: [PATCH 25/45] Adding to the config template, adding the little UX improvements --- application/config.json.template | 1 + .../tjbot/commands/moderation/modmail/ModMailCommand.java | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/application/config.json.template b/application/config.json.template index d7a3563a38..6a661bdb02 100644 --- a/application/config.json.template +++ b/application/config.json.template @@ -5,6 +5,7 @@ "projectWebsite": "https://github.com/Together-Java/TJ-Bot", "discordGuildInvite": "https://discord.com/invite/XXFUXzK", "modAuditLogChannelPattern": "mod_audit_log", + "modMailChannelPattern": "modmail", "mutedRolePattern": "Muted", "heavyModerationRolePattern": "Moderator", "softModerationRolePattern": "Moderator|Staff Assistant", diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 42e00c5101..d1cdff2599 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -130,8 +130,8 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { } private MessageEmbed createModMailMessage(String user, String userMessage) { - return new EmbedBuilder().setTitle("**/modmail from %s** ".formatted(user)) - .setDescription(userMessage) + return new EmbedBuilder().setDescription("**/modmail from %s** ".formatted(user)) + .setFooter(userMessage) .setColor(AMBIENT_COLOR) .build(); } From ccc264136b3e614744aba62e9d26df8214d4c706 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Sat, 8 Oct 2022 17:55:04 +0200 Subject: [PATCH 26/45] Merging two queues into one --- .../moderation/modmail/ModMailCommand.java | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index d1cdff2599..0534eae7ed 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -95,6 +95,8 @@ private Cache createCooldownCache() { @Override public void onSlashCommand(SlashCommandInteractionEvent event) { long userId = event.getUser().getIdLong(); + event.deferReply().setEphemeral(true).queue(); + if (isChannelOnCooldown(userId)) { event.reply("Can only be used once per %s minutes.".formatted(COOLDOWN_DURATION_VALUE)) .setEphemeral(true) @@ -123,15 +125,22 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { .sendMessageEmbeds(createModMailMessage(user, userMessage)); } - message.queue(); - - event.reply("Thank you for contacting the moderators").setEphemeral(true).queue(); + message.mapToResult().flatMap(result -> { + if (result.isSuccess()) { + return event.getHook().editOriginal("Your message has been forwarded, thanks."); + } else { + return event.getHook() + .editOriginal("There was an issue forwarding your message, sorry. We are " + + "investigating."); + } + }).queue(); } private MessageEmbed createModMailMessage(String user, String userMessage) { return new EmbedBuilder().setDescription("**/modmail from %s** ".formatted(user)) .setFooter(userMessage) + .appendDescription("") .setColor(AMBIENT_COLOR) .build(); } From 73f09a3049f66ff94fa221dd2089cb56da82df1d Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Sat, 8 Oct 2022 17:56:07 +0200 Subject: [PATCH 27/45] Removing description --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 1 - 1 file changed, 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 0534eae7ed..f516066c7a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -140,7 +140,6 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { private MessageEmbed createModMailMessage(String user, String userMessage) { return new EmbedBuilder().setDescription("**/modmail from %s** ".formatted(user)) .setFooter(userMessage) - .appendDescription("") .setColor(AMBIENT_COLOR) .build(); } From 75c61de072e906f0f2f6236b9014b82b68b7e0ae Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Tue, 11 Oct 2022 17:35:13 +0200 Subject: [PATCH 28/45] Improving the things mentioned --- .../moderation/attachment/package-info.java | 4 +- .../moderation/modmail/ModMailCommand.java | 114 ++++++++++-------- .../moderation/modmail/package-info.java | 3 +- .../commands/moderation/scam/ScamBlocker.java | 2 +- .../org/togetherjava/tjbot/config/Config.java | 2 +- 5 files changed, 74 insertions(+), 51 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java index cb62b969b0..4d8f9ad910 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java @@ -1,5 +1,7 @@ /** - * This packages offers all the functionality for checking attachment safety. + * This packages offers all the functionality for checking attachment safety see + * {@link org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener} as + * main entry point. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index f516066c7a..e6cbe96c4d 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -8,10 +8,13 @@ import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; +import net.dv8tion.jda.api.interactions.InteractionHook; import net.dv8tion.jda.api.interactions.commands.Command; import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.CommandVisibility; @@ -34,10 +37,10 @@ * Implements the /modmail command, which allows users to contact a moderator within the server or * even if not part of the server anymore, e.g. after a ban. *

- * Therefore, the user DMs the bot and the message are forwarded to moderators in a dedicated - * channel. + * Therefore, the user uses the SlashCommand /modmail and the message are forwarded to moderators in + * a dedicated channel. *

- * Actions are then logged to a dedicated channel, given by + * Messages are then forwarded to a dedicated channel, given by * {@link Config#getModAuditLogChannelPattern()}. */ @@ -47,30 +50,31 @@ public final class ModMailCommand extends SlashCommandAdapter { private static final String COMMAND_NAME = "modmail"; private static final String OPTION_MESSAGE = "message"; private static final String OPTION_STAY_ANONYMOUS = "stay-anonymous"; - private static final String OPTION_SERVER_GUILD = "server-guild"; + private static final String OPTION_GUILD = "server"; private static final int COOLDOWN_DURATION_VALUE = 30; private static final ChronoUnit COOLDOWN_DURATION_UNIT = ChronoUnit.MINUTES; - private static final Color AMBIENT_COLOR = Color.black; - private final Cache authorIdToLastCommandInvocation = createCooldownCache(); + private static final Color AMBIENT_COLOR = Color.BLACK; + private final Cache authorToLastModMailInvocation = createCooldownCache(); private final Predicate modMailChannelNamePredicate; /** * Creates a new instance. * - * @param jda the JDA instance to use to retrieve guildCache - * @param config the config to use for this + * @param jda the JDA instance to retrieve guildCache + * @param config to get the channel to forward modmails to */ public ModMailCommand(JDA jda, Config config) { - super(COMMAND_NAME, "Send a message to the moderators of the selected guild", + super(COMMAND_NAME, "Contact the moderators of the selected guild", CommandVisibility.GLOBAL); OptionData messageOption = new OptionData(OptionType.STRING, OPTION_MESSAGE, "What do you want to tell them?", true); - OptionData guildOption = new OptionData(OptionType.STRING, OPTION_SERVER_GUILD, - "Your server guild ID", true); + OptionData guildOption = new OptionData(OptionType.STRING, OPTION_GUILD, + "The server to contact mods from", true); OptionData anonymousOption = new OptionData(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, - "if set, your name is hidden", true); + "If set, your name is hidden - note that mods then can not get " + "back to you", + true); List choices = jda.getGuildCache() .stream() @@ -95,46 +99,72 @@ private Cache createCooldownCache() { @Override public void onSlashCommand(SlashCommandInteractionEvent event) { long userId = event.getUser().getIdLong(); + + handleCooldown(userId, event); + event.deferReply().setEphemeral(true).queue(); + long userGuildId = event.getOption(OPTION_GUILD).getAsLong(); + Optional modMailAuditLog = getModMailChannel(event.getJDA(), userGuildId); + if (modMailAuditLog.isEmpty()) { + logger.warn( + "Cannot find the designated modmail channel in server %s server by the id of %d ." + .formatted(event.getGuild().getName(), userGuildId)); + return; + } + + MessageCreateAction message = createMessage(event, userId, modMailAuditLog.orElseThrow()); + + sendMessage(event, message); + + } + + private void handleCooldown(long userId, SlashCommandInteractionEvent event) { if (isChannelOnCooldown(userId)) { event.reply("Can only be used once per %s minutes.".formatted(COOLDOWN_DURATION_VALUE)) .setEphemeral(true) .queue(); return; } - authorIdToLastCommandInvocation.put(userId, Instant.now()); + authorToLastModMailInvocation.put(userId, Instant.now()); + } - Optional modMailAuditLog = getChannel(event); - if (modMailAuditLog.isEmpty()) { - logger.warn("Cannot find the designated modmail channel in this server."); - return; - } + private Optional getModMailChannel(JDA jda, long userGuildI) { + return jda.getGuildById(userGuildI) + .getTextChannelCache() + .stream() + .filter(channel -> modMailChannelNamePredicate.test(channel.getName())) + .findAny(); + } + private MessageCreateAction createMessage(SlashCommandInteractionEvent event, long userId, + TextChannel modMailAuditLog) { String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); - String user = event.getUser().getAsMention(); - MessageCreateAction message = modMailAuditLog.orElseThrow() - .sendMessageEmbeds(createModMailMessage(user, userMessage)) - .addActionRow(DiscordClientAction.General.USER.asLinkButton("Click to see profile!", - String.valueOf(userId))); - + String user; + MessageCreateAction message; if (wantsToStayAnonymous) { user = "Anonymous"; - message = modMailAuditLog.orElseThrow() - .sendMessageEmbeds(createModMailMessage(user, userMessage)); + message = modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage)); + } else { + user = event.getUser().getAsMention(); + message = modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage)) + .addActionRow(DiscordClientAction.General.USER.asLinkButton("Author Profile", + String.valueOf(userId))); } + return message; + } - message.mapToResult().flatMap(result -> { - if (result.isSuccess()) { - return event.getHook().editOriginal("Your message has been forwarded, thanks."); - } else { - return event.getHook() - .editOriginal("There was an issue forwarding your message, sorry. We are " - + "investigating."); - } - }).queue(); - + private void sendMessage(SlashCommandInteractionEvent event, MessageCreateAction message) { + InteractionHook hook = event.getHook(); + message.mapToResult() + .map(result -> result.isSuccess() ? "Your message has been forwarded, thanks." + : "There was an issue forwarding your message, sorry. We are investigating.") + .flatMap(hook::editOriginal) + .queue(any -> { + }, error -> logger.warn( + "There was an problem with forwarding the message to the modmail channel.", + error)); // need to add on queue on success } private MessageEmbed createModMailMessage(String user, String userMessage) { @@ -144,18 +174,8 @@ private MessageEmbed createModMailMessage(String user, String userMessage) { .build(); } - private Optional getChannel(SlashCommandInteractionEvent event) { - long userGuildId = event.getOption(OPTION_SERVER_GUILD).getAsLong(); - Guild guild = Objects.requireNonNull(event.getJDA().getGuildById(userGuildId), - "Something went wrong with selecting the guild."); - return guild.getTextChannelCache() - .stream() - .filter(channel -> modMailChannelNamePredicate.test(channel.getName())) - .findAny(); - } - private boolean isChannelOnCooldown(long userId) { - return Optional.ofNullable(authorIdToLastCommandInvocation.getIfPresent(userId)) + return Optional.ofNullable(authorToLastModMailInvocation.getIfPresent(userId)) .map(sinceCommandInvoked -> sinceCommandInvoked.plus(COOLDOWN_DURATION_VALUE, COOLDOWN_DURATION_UNIT)) .filter(Instant.now()::isBefore) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java index 4bb2fa2d94..d0a2de9825 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java @@ -1,5 +1,6 @@ /** - * This packages offers all the functionality for messaging moderators trough mod mail. + * This packages offers all the functionality for messaging moderators trough mod mail see + * {@link org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand} as main entry point. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java index 4f1ad764f3..cb910da0d1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java @@ -255,7 +255,7 @@ private void dmUser(Guild guild, long userId, JDA jda) { This means you can no longer interact with anyone in the server until you have been unquarantined again. If you think this was a mistake (for example, your account was hacked, but you got back control over it), - than to get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: + you can get in touch with a moderator by using the **/modmail** command :thumbsup: """ .formatted(guild.getName()); diff --git a/application/src/main/java/org/togetherjava/tjbot/config/Config.java b/application/src/main/java/org/togetherjava/tjbot/config/Config.java index 8be3b5dd06..7c078a97f7 100644 --- a/application/src/main/java/org/togetherjava/tjbot/config/Config.java +++ b/application/src/main/java/org/togetherjava/tjbot/config/Config.java @@ -123,7 +123,7 @@ public String getModAuditLogChannelPattern() { /** * Gets the REGEX pattern used to identify the channel that is supposed to contain all messages - * from users who want to contact a moderator + * from users who want to contact a moderator. * * @return the channel name pattern */ From 571101098ecfd9ddaee1ae3660f40f017d814f65 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 12 Oct 2022 08:36:02 +0200 Subject: [PATCH 29/45] Making an ModerationUtil for Dm advices after ModerationAction --- .../tjbot/commands/moderation/BanCommand.java | 9 ++--- .../commands/moderation/KickCommand.java | 7 +--- .../commands/moderation/ModerationUtils.java | 35 +++++++++++++++++++ .../commands/moderation/MuteCommand.java | 10 ++---- .../moderation/QuarantineCommand.java | 8 +---- .../commands/moderation/UnmuteCommand.java | 7 ++-- .../moderation/UnquarantineCommand.java | 7 ++-- .../commands/moderation/WarnCommand.java | 7 +--- 8 files changed, 46 insertions(+), 44 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 50736080f6..eca2908c7b 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 @@ -88,13 +88,8 @@ private static RestAction sendDm(ISnowflake target, GenericEvent event) { String durationMessage = temporaryData == null ? "permanently" : "for " + temporaryData.duration(); - String dmMessage = - """ - Hey there, sorry to tell you but unfortunately you have been banned %s from the server %s. - To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: - The reason for the ban is: %s - """ - .formatted(durationMessage, guild.getName(), reason); + String dmMessage = ModerationUtils.getDmAdvice(ModerationAction.BAN, durationMessage, + guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) 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 8794ed51b3..9de3e165f0 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 @@ -73,12 +73,7 @@ private static RestAction sendDm(ISnowflake target, String reason, Guil return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage( - """ - Hey there, sorry to tell you but unfortunately you have been kicked from the server %s. - To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: - The reason for the kick is: %s - """ - .formatted(guild.getName(), reason))) + ModerationUtils.getDmAdvice(ModerationAction.KICK, guild.getName(), reason))) .mapToResult() .map(Result::isSuccess); } 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 58a2e232ce..256b504964 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 @@ -17,6 +17,7 @@ import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; import java.util.Optional; +import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -372,4 +373,38 @@ static Optional computeTemporaryData(String durationText) { */ record TemporaryData(Instant expiresAt, String duration) { } + + /** + * Gives out advice depending on the {@link ModerationAction} and the parameters passed into it. + * + * @param action gives out a {@link ModerationAction} to be able to respond and build a message + * appropriately such as {@link ModerationAction#BAN}, {@link ModerationAction#MUTE} + * etc.. + * @param message is the message that is being used to build responses, such as + * {@link Guild#getName()}, and reasoning for an action. + * @return the appropriate advice. + */ + public static String getDmAdvice(ModerationAction action, String... message) { + if (message.length == 3) { + return """ + Hey there, sorry to tell you but unfortunately you have been %s %s from the server %s. + To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: + The reason for being %s is: %s + """ + .formatted(action, message, message, message, message); + } else if (ModerationAction.UNMUTE.getVerb().equals(action.getVerb()) + || ModerationAction.UNQUARANTINE.getVerb().equals(action.getVerb())) { + return """ + Hey there, you have been %s in the server %s. + This means you can now interact with others in the server again. + The reason for the %s is: %s + """.formatted(action, message, action, message); + } + return """ + Hey there, sorry to tell you but unfortunately you have been %s, which came from the server %s. + To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: + The reason for the kick is: %s + """ + .formatted(action, message, message); + } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java index 8142696a90..c93908d19a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -75,14 +75,8 @@ private static RestAction sendDm(ISnowflake target, GenericEvent event) { String durationMessage = temporaryData == null ? "permanently" : "for " + temporaryData.duration(); - String dmMessage = - """ - Hey there, sorry to tell you but unfortunately you have been muted %s in the server %s. - This means you can no longer send any messages in the server until you have been unmuted again. - To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: - The reason for the mute is: %s - """ - .formatted(durationMessage, guild.getName(), reason); + String dmMessage = ModerationUtils.getDmAdvice(ModerationAction.MUTE, durationMessage, + guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java index d718483878..3b82b53223 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java @@ -64,13 +64,7 @@ private static void handleAlreadyQuarantinedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { String dmMessage = - """ - Hey there, sorry to tell you but unfortunately you have been put under quarantine in the server %s. - This means you can no longer interact with anyone in the server until you have been unquarantined again. - To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: - The reason for the quarantine is: %s - """ - .formatted(guild.getName(), reason); + ModerationUtils.getDmAdvice(ModerationAction.QUARANTINE, guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getIdLong()) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java index 0e388a2911..b88b7aac9c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java @@ -60,11 +60,8 @@ private static void handleNotMutedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { - String dmMessage = """ - Hey there, you have been unmuted in the server %s. - This means you can now send messages in the server again. - The reason for the unmute is: %s - """.formatted(guild.getName(), reason); + String dmMessage = + ModerationUtils.getDmAdvice(ModerationAction.UNMUTE, guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java index 2839d77b2f..2c9dc4cd28 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java @@ -64,11 +64,8 @@ private static void handleNotQuarantinedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { - String dmMessage = """ - Hey there, you have been put out of quarantine in the server %s. - This means you can now interact with others in the server again. - The reason for the unquarantine is: %s - """.formatted(guild.getName(), reason); + String dmMessage = + ModerationUtils.getDmAdvice(ModerationAction.UNQUARANTINE, guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getIdLong()) 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 d40c4489f9..330995b487 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 @@ -61,12 +61,7 @@ private static RestAction dmUser(ISnowflake target, String reason, Guil return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage( - """ - Hey there, sorry to tell you but unfortunately you have been warned in the server %s. - To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: - The reason for the warning is: %s - """ - .formatted(guild.getName(), reason))) + ModerationUtils.getDmAdvice(ModerationAction.WARN, guild.getName(), reason))) .mapToResult() .map(Result::isSuccess); } From dc616bcd951dcf97207bc8a55753164866b3a39c Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 12 Oct 2022 08:41:44 +0200 Subject: [PATCH 30/45] Removing unnecessary imports --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index e6cbe96c4d..3e75d15c5c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -4,7 +4,6 @@ import com.github.benmanes.caffeine.cache.Caffeine; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; @@ -13,8 +12,6 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.togetherjava.tjbot.commands.CommandVisibility; @@ -26,7 +23,6 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.util.List; -import java.util.Objects; import java.util.Optional; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; From ce287dff5fe15e2b6935ec8c35a5b9c840364c66 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 12 Oct 2022 09:13:24 +0200 Subject: [PATCH 31/45] Improving the logger warning --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 3e75d15c5c..2e4b363c59 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -4,6 +4,7 @@ import com.github.benmanes.caffeine.cache.Caffeine; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; +import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; @@ -103,9 +104,8 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { long userGuildId = event.getOption(OPTION_GUILD).getAsLong(); Optional modMailAuditLog = getModMailChannel(event.getJDA(), userGuildId); if (modMailAuditLog.isEmpty()) { - logger.warn( - "Cannot find the designated modmail channel in server %s server by the id of %d ." - .formatted(event.getGuild().getName(), userGuildId)); + logger.warn("Cannot find the designated modmail channel in server by id {}", + userGuildId); return; } From 93d91f08aecd3594c7338f2ca11670ee8ee14ff7 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 12 Oct 2022 09:20:08 +0200 Subject: [PATCH 32/45] Removing unnecessary import, ran spotless --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 1 - 1 file changed, 1 deletion(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 2e4b363c59..24b7bed70e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -4,7 +4,6 @@ import com.github.benmanes.caffeine.cache.Caffeine; import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; -import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; From 8b5394d9c2f8ba7f6f3efab6de2b89a642a3cc2a Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 12 Oct 2022 09:26:22 +0200 Subject: [PATCH 33/45] Manually fixing spotless errors --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 1 + 1 file changed, 1 insertion(+) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 24b7bed70e..da72b0e173 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -14,6 +14,7 @@ import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; + import org.togetherjava.tjbot.commands.CommandVisibility; import org.togetherjava.tjbot.commands.SlashCommandAdapter; import org.togetherjava.tjbot.commands.utils.DiscordClientAction; From 9f3b0f6ac1b7bce7043d705ada6a34230c1f8886 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Thu, 13 Oct 2022 14:49:44 +0200 Subject: [PATCH 34/45] Quick before zabu changes his mind --- .../tjbot/commands/moderation/ModerationUtils.java | 11 +++++------ .../commands/moderation/modmail/ModMailCommand.java | 3 ++- 2 files changed, 7 insertions(+), 7 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 256b504964..729fb4528d 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 @@ -17,7 +17,6 @@ import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; import java.util.Optional; -import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -391,20 +390,20 @@ public static String getDmAdvice(ModerationAction action, String... message) { To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: The reason for being %s is: %s """ - .formatted(action, message, message, message, message); + .formatted(action.getVerb(), message[0], message[1], action.getVerb(), message[2]); } else if (ModerationAction.UNMUTE.getVerb().equals(action.getVerb()) || ModerationAction.UNQUARANTINE.getVerb().equals(action.getVerb())) { return """ Hey there, you have been %s in the server %s. This means you can now interact with others in the server again. - The reason for the %s is: %s - """.formatted(action, message, action, message); + The reason for being %s is: %s + """.formatted(action.getVerb(), message[0], action.getVerb(), message[1]); } return """ Hey there, sorry to tell you but unfortunately you have been %s, which came from the server %s. To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: - The reason for the kick is: %s + The reason for being %s is: %s """ - .formatted(action, message, message); + .formatted(action.getVerb(), message[0], action.getVerb(), message[1]); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index da72b0e173..67238276f5 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -104,7 +104,8 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { long userGuildId = event.getOption(OPTION_GUILD).getAsLong(); Optional modMailAuditLog = getModMailChannel(event.getJDA(), userGuildId); if (modMailAuditLog.isEmpty()) { - logger.warn("Cannot find the designated modmail channel in server by id {}", + logger.warn( + "Cannot find the designated modmail channel in server by id {} with the pattern modmail", userGuildId); return; } From c98d66efaef81e5b7d78df15d65ecd46b370dbb8 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Thu, 13 Oct 2022 15:21:37 +0200 Subject: [PATCH 35/45] Push quick --- .../commands/moderation/modmail/ModMailCommand.java | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 67238276f5..20c3f89789 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -97,8 +97,10 @@ private Cache createCooldownCache() { public void onSlashCommand(SlashCommandInteractionEvent event) { long userId = event.getUser().getIdLong(); - handleCooldown(userId, event); - + if (handleIsOnCooldown(userId, event)) { + return; + } + authorToLastModMailInvocation.put(userId, Instant.now()); event.deferReply().setEphemeral(true).queue(); long userGuildId = event.getOption(OPTION_GUILD).getAsLong(); @@ -116,14 +118,14 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { } - private void handleCooldown(long userId, SlashCommandInteractionEvent event) { + private boolean handleIsOnCooldown(long userId, SlashCommandInteractionEvent event) { if (isChannelOnCooldown(userId)) { event.reply("Can only be used once per %s minutes.".formatted(COOLDOWN_DURATION_VALUE)) .setEphemeral(true) .queue(); - return; + return true; } - authorToLastModMailInvocation.put(userId, Instant.now()); + return false; } private Optional getModMailChannel(JDA jda, long userGuildI) { From 9445c30a8f29a49592a5a009fa7d01722fb92f9f Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Tue, 18 Oct 2022 15:02:40 +0200 Subject: [PATCH 36/45] Fixing the Global Command Problem --- .../tjbot/commands/moderation/BanCommand.java | 9 +++++++-- .../tjbot/commands/moderation/KickCommand.java | 7 ++++++- .../tjbot/commands/moderation/ModerationUtils.java | 3 +-- 3 files changed, 14 insertions(+), 5 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 eca2908c7b..751c15679e 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 @@ -88,8 +88,13 @@ private static RestAction sendDm(ISnowflake target, GenericEvent event) { String durationMessage = temporaryData == null ? "permanently" : "for " + temporaryData.duration(); - String dmMessage = ModerationUtils.getDmAdvice(ModerationAction.BAN, durationMessage, - guild.getName(), reason); + String dmMessage = + """ + Hey there, sorry to tell you but unfortunately you have been banned %s from the server %s. + If you think this was a mistake, please contact a moderator or admin of the server. + The reason for the ban is: %s + """ + .formatted(durationMessage, guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) 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 9de3e165f0..696476a3e6 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 @@ -73,7 +73,12 @@ private static RestAction sendDm(ISnowflake target, String reason, Guil return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage( - ModerationUtils.getDmAdvice(ModerationAction.KICK, guild.getName(), reason))) + """ + Hey there, sorry to tell you but unfortunately you have been kicked from the server %s. + If you think this was a mistake, please contact a moderator or admin of the server. + The reason for the kick is: %s + """ + .formatted(guild.getName(), reason))) .mapToResult() .map(Result::isSuccess); } 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 729fb4528d..52f6b673ce 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 @@ -377,8 +377,7 @@ record TemporaryData(Instant expiresAt, String duration) { * Gives out advice depending on the {@link ModerationAction} and the parameters passed into it. * * @param action gives out a {@link ModerationAction} to be able to respond and build a message - * appropriately such as {@link ModerationAction#BAN}, {@link ModerationAction#MUTE} - * etc.. + * appropriately such as {@link ModerationAction#MUTE} etc. * @param message is the message that is being used to build responses, such as * {@link Guild#getName()}, and reasoning for an action. * @return the appropriate advice. From e71b326de8c5db8a8d71f3927fda384cbf013acc Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Tue, 18 Oct 2022 17:45:27 +0200 Subject: [PATCH 37/45] please --- .../commands/moderation/ModerationUtils.java | 33 ++++--- .../commands/moderation/MuteCommand.java | 6 +- .../moderation/QuarantineCommand.java | 2 +- .../commands/moderation/UnmuteCommand.java | 2 +- .../moderation/UnquarantineCommand.java | 2 +- .../commands/moderation/WarnCommand.java | 2 +- .../moderation/modmail/ModMailCommand.java | 90 ++++++++++--------- 7 files changed, 73 insertions(+), 64 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 52f6b673ce..5fc4c52ecc 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 @@ -8,6 +8,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.utils.MessageUtils; import org.togetherjava.tjbot.config.Config; import javax.annotation.Nullable; @@ -376,33 +377,37 @@ record TemporaryData(Instant expiresAt, String duration) { /** * Gives out advice depending on the {@link ModerationAction} and the parameters passed into it. * - * @param action gives out a {@link ModerationAction} to be able to respond and build a message - * appropriately such as {@link ModerationAction#MUTE} etc. - * @param message is the message that is being used to build responses, such as - * {@link Guild#getName()}, and reasoning for an action. + * @param action the action that is being performed, such as banning a user. + * @param temporaryData is the message that is being used to display action duration. + * @param guild to retrieve the guild. + * @param reason for the action. * @return the appropriate advice. */ - public static String getDmAdvice(ModerationAction action, String... message) { - if (message.length == 3) { + public static String getDmAdvice(ModerationAction action, + @Nullable ModerationUtils.TemporaryData temporaryData, Guild guild, String reason) { + if (action == ModerationAction.MUTE) { + String durationMessage = + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); return """ - Hey there, sorry to tell you but unfortunately you have been %s %s from the server %s. + Hey there, sorry to tell you but unfortunately you have been %s %s in the server %s. To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: The reason for being %s is: %s """ - .formatted(action.getVerb(), message[0], message[1], action.getVerb(), message[2]); - } else if (ModerationAction.UNMUTE.getVerb().equals(action.getVerb()) - || ModerationAction.UNQUARANTINE.getVerb().equals(action.getVerb())) { + .formatted(action.getVerb(), durationMessage, guild.getName(), action.getVerb(), + reason); + } else if (action == ModerationAction.UNMUTE || action == ModerationAction.UNQUARANTINE) { return """ Hey there, you have been %s in the server %s. This means you can now interact with others in the server again. The reason for being %s is: %s - """.formatted(action.getVerb(), message[0], action.getVerb(), message[1]); + """.formatted(action.getVerb(), guild.getName(), action.getVerb(), reason); } return """ - Hey there, sorry to tell you but unfortunately you have been %s, which came from the server %s. - To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: + Hey there, sorry to tell you but unfortunately you have been %s, in the server %s. + To get in touch with a moderator, you can simply use the %s command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: The reason for being %s is: %s """ - .formatted(action.getVerb(), message[0], action.getVerb(), message[1]); + .formatted(action.getVerb(), guild.getName(), + MessageUtils.mentionSlashCommand(guild, "modmail"), action.getVerb(), reason); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java index c93908d19a..52a528f2aa 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -73,10 +73,8 @@ private static void handleAlreadyMutedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, @Nullable ModerationUtils.TemporaryData temporaryData, String reason, Guild guild, GenericEvent event) { - String durationMessage = - temporaryData == null ? "permanently" : "for " + temporaryData.duration(); - String dmMessage = ModerationUtils.getDmAdvice(ModerationAction.MUTE, durationMessage, - guild.getName(), reason); + String dmMessage = + ModerationUtils.getDmAdvice(ModerationAction.MUTE, temporaryData, guild, reason); return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java index 3b82b53223..9edf3225f3 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java @@ -64,7 +64,7 @@ private static void handleAlreadyQuarantinedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { String dmMessage = - ModerationUtils.getDmAdvice(ModerationAction.QUARANTINE, guild.getName(), reason); + ModerationUtils.getDmAdvice(ModerationAction.QUARANTINE, null, guild, reason); return event.getJDA() .openPrivateChannelById(target.getIdLong()) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java index b88b7aac9c..1ade30507e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java @@ -61,7 +61,7 @@ private static void handleNotMutedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { String dmMessage = - ModerationUtils.getDmAdvice(ModerationAction.UNMUTE, guild.getName(), reason); + ModerationUtils.getDmAdvice(ModerationAction.UNMUTE, null, guild, reason); return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage(dmMessage)) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java index 2c9dc4cd28..6fc4348b7c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java @@ -65,7 +65,7 @@ private static void handleNotQuarantinedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { String dmMessage = - ModerationUtils.getDmAdvice(ModerationAction.UNQUARANTINE, guild.getName(), reason); + ModerationUtils.getDmAdvice(ModerationAction.UNQUARANTINE, null, guild, reason); return event.getJDA() .openPrivateChannelById(target.getIdLong()) 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 330995b487..dc977af966 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 @@ -61,7 +61,7 @@ private static RestAction dmUser(ISnowflake target, String reason, Guil return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> channel.sendMessage( - ModerationUtils.getDmAdvice(ModerationAction.WARN, guild.getName(), reason))) + ModerationUtils.getDmAdvice(ModerationAction.WARN, null, guild, reason))) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 20c3f89789..e0295c9738 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -5,6 +5,7 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import net.dv8tion.jda.api.interactions.InteractionHook; @@ -12,6 +13,7 @@ import net.dv8tion.jda.api.interactions.commands.OptionType; import net.dv8tion.jda.api.interactions.commands.build.OptionData; import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; +import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -31,13 +33,8 @@ /** - * Implements the /modmail command, which allows users to contact a moderator within the server or - * even if not part of the server anymore, e.g. after a ban. - *

- * Therefore, the user uses the SlashCommand /modmail and the message are forwarded to moderators in - * a dedicated channel. - *

- * Messages are then forwarded to a dedicated channel, given by + * Implements the /modmail command, which allows users to contact a moderator within the server + * which forwards messages to moderators in a dedicated channel given by * {@link Config#getModAuditLogChannelPattern()}. */ @@ -53,6 +50,7 @@ public final class ModMailCommand extends SlashCommandAdapter { private static final Color AMBIENT_COLOR = Color.BLACK; private final Cache authorToLastModMailInvocation = createCooldownCache(); private final Predicate modMailChannelNamePredicate; + private final String configModMailChannelPattern; /** @@ -70,8 +68,7 @@ public ModMailCommand(JDA jda, Config config) { OptionData guildOption = new OptionData(OptionType.STRING, OPTION_GUILD, "The server to contact mods from", true); OptionData anonymousOption = new OptionData(OptionType.BOOLEAN, OPTION_STAY_ANONYMOUS, - "If set, your name is hidden - note that mods then can not get " + "back to you", - true); + "If set, your name is hidden - note that mods then can not get back to you", true); List choices = jda.getGuildCache() .stream() @@ -84,6 +81,12 @@ public ModMailCommand(JDA jda, Config config) { modMailChannelNamePredicate = Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); + + configModMailChannelPattern = config.getModMailChannelPattern(); + } + + private String getConfigModMailChannelPattern(Config config) { + return config.getModMailChannelPattern(); } private Cache createCooldownCache() { @@ -107,68 +110,71 @@ public void onSlashCommand(SlashCommandInteractionEvent event) { Optional modMailAuditLog = getModMailChannel(event.getJDA(), userGuildId); if (modMailAuditLog.isEmpty()) { logger.warn( - "Cannot find the designated modmail channel in server by id {} with the pattern modmail", - userGuildId); + "Cannot find the designated modmail channel in server by id {} with the pattern {}", + userGuildId, configModMailChannelPattern); return; } - MessageCreateAction message = createMessage(event, userId, modMailAuditLog.orElseThrow()); + MessageCreateAction message = + createModMessage(event, userId, modMailAuditLog.orElseThrow()); sendMessage(event, message); } private boolean handleIsOnCooldown(long userId, SlashCommandInteractionEvent event) { - if (isChannelOnCooldown(userId)) { - event.reply("Can only be used once per %s minutes.".formatted(COOLDOWN_DURATION_VALUE)) - .setEphemeral(true) - .queue(); - return true; + if (!isChannelOnCooldown(userId)) { + return false; } - return false; + event.reply("Can only be used once per %s minutes.".formatted(COOLDOWN_DURATION_VALUE)) + .setEphemeral(true) + .queue(); + return true; } - private Optional getModMailChannel(JDA jda, long userGuildI) { - return jda.getGuildById(userGuildI) + private Optional getModMailChannel(JDA jda, long guildId) { + return jda.getGuildById(guildId) .getTextChannelCache() .stream() .filter(channel -> modMailChannelNamePredicate.test(channel.getName())) .findAny(); } - private MessageCreateAction createMessage(SlashCommandInteractionEvent event, long userId, + private MessageCreateAction createModMessage(SlashCommandInteractionEvent event, long userId, TextChannel modMailAuditLog) { String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); - String user; - MessageCreateAction message; - if (wantsToStayAnonymous) { - user = "Anonymous"; - message = modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage)); - } else { - user = event.getUser().getAsMention(); - message = modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage)) - .addActionRow(DiscordClientAction.General.USER.asLinkButton("Author Profile", - String.valueOf(userId))); + + User user = event.getUser(); + MessageCreateAction message = + modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage)); + + if (!wantsToStayAnonymous) { + message.addActionRow(DiscordClientAction.General.USER.asLinkButton("Author Profile", + String.valueOf(userId))); } return message; } private void sendMessage(SlashCommandInteractionEvent event, MessageCreateAction message) { InteractionHook hook = event.getHook(); - message.mapToResult() - .map(result -> result.isSuccess() ? "Your message has been forwarded, thanks." - : "There was an issue forwarding your message, sorry. We are investigating.") - .flatMap(hook::editOriginal) - .queue(any -> { - }, error -> logger.warn( - "There was an problem with forwarding the message to the modmail channel.", - error)); // need to add on queue on success + message.mapToResult().map(result -> { + if (result.isSuccess()) { + return "Your message has been forwarded, thanks."; + } + logger.warn("There was an issue with forwarding users message."); + return "There was an issue forwarding your message, sorry. We are investigating."; + }).flatMap(hook::editOriginal).queue(any -> { + }, error -> logger.warn( + "There was an problem with forwarding the message to the modmail channel.", error)); } - private MessageEmbed createModMailMessage(String user, String userMessage) { - return new EmbedBuilder().setDescription("**/modmail from %s** ".formatted(user)) - .setFooter(userMessage) + private MessageEmbed createModMailMessage(@Nullable User author, String userMessage) { + String authorTag = author == null ? "Anonymous" : author.getAsTag(); + String authorAvatar = author == null ? null : author.getAvatarUrl(); + return new EmbedBuilder().setTitle("Modmail") + .setAuthor(authorTag, null, authorAvatar) + .setDescription(userMessage) .setColor(AMBIENT_COLOR) .build(); } From 9dff4366f04900c13e54d8007a6519a7d0f3dfb5 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Tue, 18 Oct 2022 17:55:15 +0200 Subject: [PATCH 38/45] UNUSED METHOD --- .../tjbot/commands/moderation/modmail/ModMailCommand.java | 4 ---- 1 file changed, 4 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index e0295c9738..139c27ab8b 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -85,10 +85,6 @@ public ModMailCommand(JDA jda, Config config) { configModMailChannelPattern = config.getModMailChannelPattern(); } - private String getConfigModMailChannelPattern(Config config) { - return config.getModMailChannelPattern(); - } - private Cache createCooldownCache() { return Caffeine.newBuilder() .maximumSize(1_000) From c1a71402861ad32ac5fb2ea74bd899675a381d69 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 19 Oct 2022 12:40:16 +0200 Subject: [PATCH 39/45] little by little I am over --- .../commands/moderation/ModerationUtils.java | 79 +++++++++++++------ .../commands/moderation/MuteCommand.java | 5 +- .../moderation/QuarantineCommand.java | 6 +- .../commands/moderation/UnmuteCommand.java | 5 +- .../moderation/UnquarantineCommand.java | 6 +- .../commands/moderation/WarnCommand.java | 4 +- .../moderation/modmail/ModMailCommand.java | 7 +- 7 files changed, 67 insertions(+), 45 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 5fc4c52ecc..6909504900 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 @@ -3,8 +3,12 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; +import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; +import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; +import net.dv8tion.jda.internal.requests.CompletedRestAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -17,7 +21,9 @@ import java.time.Instant; import java.time.temporal.ChronoUnit; import java.time.temporal.TemporalUnit; +import java.util.EnumSet; import java.util.Optional; +import java.util.Set; import java.util.function.Predicate; import java.util.regex.Pattern; @@ -46,6 +52,26 @@ private ModerationUtils() { */ static final Color AMBIENT_COLOR = Color.decode("#895FE8"); + /** + * Provides you with an Enum of actions which have a timely constraint, like being muted for 1 + * hour. + */ + private static final Set TEMPORARY_ACTIONS = + EnumSet.of(ModerationAction.MUTE); + /** + * Provides you with an Enum of actions which are revoking previously made actions on the user, + * like unmuting the user after it has been muted. + */ + private static final Set REVOKE_ACTIONS = + EnumSet.of(ModerationAction.UNMUTE, ModerationAction.UNQUARANTINE); + /** + * Provides you with an Enum of actions which are letting you know of a violation you have + * committed. + */ + private static final Set SOFT_ACTIONS = EnumSet.of(ModerationAction.WARN); + + + /** * Checks whether the given reason is valid. If not, it will handle the situation and respond to * the user. @@ -378,36 +404,41 @@ record TemporaryData(Instant expiresAt, String duration) { * Gives out advice depending on the {@link ModerationAction} and the parameters passed into it. * * @param action the action that is being performed, such as banning a user. - * @param temporaryData is the message that is being used to display action duration. - * @param guild to retrieve the guild. + * @param temporaryData if the action is a temporary action, such as a 1 hour mute. + * @param guild for which the action was triggered. * @param reason for the action. * @return the appropriate advice. */ - public static String getDmAdvice(ModerationAction action, - @Nullable ModerationUtils.TemporaryData temporaryData, Guild guild, String reason) { - if (action == ModerationAction.MUTE) { - String durationMessage = - temporaryData == null ? "permanently" : "for " + temporaryData.duration(); - return """ - Hey there, sorry to tell you but unfortunately you have been %s %s in the server %s. - To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: - The reason for being %s is: %s - """ - .formatted(action.getVerb(), durationMessage, guild.getName(), action.getVerb(), - reason); - } else if (action == ModerationAction.UNMUTE || action == ModerationAction.UNQUARANTINE) { - return """ + public static RestAction sendDmAdvice(ModerationAction action, + @Nullable ModerationUtils.TemporaryData temporaryData, Guild guild, String reason, + PrivateChannel textChannel) { + final String COMMAND_NAME = "modmail"; + if (REVOKE_ACTIONS.contains(action)) { + return new CompletedRestAction<>(guild.getJDA(), textChannel.sendMessage(""" Hey there, you have been %s in the server %s. This means you can now interact with others in the server again. The reason for being %s is: %s - """.formatted(action.getVerb(), guild.getName(), action.getVerb(), reason); + """.formatted(action.getVerb(), guild.getName(), action.getVerb(), reason))); } - return """ - Hey there, sorry to tell you but unfortunately you have been %s, in the server %s. - To get in touch with a moderator, you can simply use the %s command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: - The reason for being %s is: %s - """ - .formatted(action.getVerb(), guild.getName(), - MessageUtils.mentionSlashCommand(guild, "modmail"), action.getVerb(), reason); + String durationMessage; + if (SOFT_ACTIONS.contains(action)) { + durationMessage = ""; + } else if (TEMPORARY_ACTIONS.contains(action)) { + durationMessage = + temporaryData == null ? "permanently" : "for " + temporaryData.duration(); + } else { + throw new IllegalArgumentException( + "Action '%s' is not supported by this method".formatted(action)); + } + + return MessageUtils.mentionSlashCommand(guild, COMMAND_NAME) + .map(commandMention -> textChannel.sendMessage( + """ + Hey there, sorry to tell you but unfortunately you have been %s %s in the server %s. + To get in touch with a moderator, you can simply use the **%s** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon 😊 + The reason for being %s is: %s + """ + .formatted(action.getVerb(), durationMessage, guild.getName(), COMMAND_NAME, + action.getVerb(), reason))); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java index 52a528f2aa..a07d2ddf50 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -73,11 +73,10 @@ private static void handleAlreadyMutedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, @Nullable ModerationUtils.TemporaryData temporaryData, String reason, Guild guild, GenericEvent event) { - String dmMessage = - ModerationUtils.getDmAdvice(ModerationAction.MUTE, temporaryData, guild, reason); return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, temporaryData, + guild, reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java index 9edf3225f3..af9592adf8 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java @@ -63,12 +63,10 @@ private static void handleAlreadyQuarantinedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { - String dmMessage = - ModerationUtils.getDmAdvice(ModerationAction.QUARANTINE, null, guild, reason); - return event.getJDA() .openPrivateChannelById(target.getIdLong()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, null, guild, + reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java index 1ade30507e..6dfdf63741 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java @@ -60,11 +60,10 @@ private static void handleNotMutedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { - String dmMessage = - ModerationUtils.getDmAdvice(ModerationAction.UNMUTE, null, guild, reason); return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, null, guild, + reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java index 6fc4348b7c..83c6c852b7 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java @@ -64,12 +64,10 @@ private static void handleNotQuarantinedTarget(IReplyCallback event) { private static RestAction sendDm(ISnowflake target, String reason, Guild guild, GenericEvent event) { - String dmMessage = - ModerationUtils.getDmAdvice(ModerationAction.UNQUARANTINE, null, guild, reason); - return event.getJDA() .openPrivateChannelById(target.getIdLong()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, null, guild, + reason, channel)) .mapToResult() .map(Result::isSuccess); } 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 dc977af966..e71d3a57dd 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 @@ -60,8 +60,8 @@ private static RestAction dmUser(ISnowflake target, String reason, Guil SlashCommandInteractionEvent event) { return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage( - ModerationUtils.getDmAdvice(ModerationAction.WARN, null, guild, reason))) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, null, guild, + reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index 139c27ab8b..ab45aa01ac 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -141,10 +141,9 @@ private MessageCreateAction createModMessage(SlashCommandInteractionEvent event, String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); - User user = event.getUser(); + User user = wantsToStayAnonymous ? event.getUser() : null; MessageCreateAction message = modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage)); - if (!wantsToStayAnonymous) { message.addActionRow(DiscordClientAction.General.USER.asLinkButton("Author Profile", String.valueOf(userId))); @@ -160,9 +159,7 @@ private void sendMessage(SlashCommandInteractionEvent event, MessageCreateAction } logger.warn("There was an issue with forwarding users message."); return "There was an issue forwarding your message, sorry. We are investigating."; - }).flatMap(hook::editOriginal).queue(any -> { - }, error -> logger.warn( - "There was an problem with forwarding the message to the modmail channel.", error)); + }).flatMap(hook::editOriginal).queue(); } private MessageEmbed createModMailMessage(@Nullable User author, String userMessage) { From 0d1a2e3f5b5431ac116dec25ad7710c846e7c932 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 19 Oct 2022 13:56:52 +0200 Subject: [PATCH 40/45] Closer and closer --- .../commands/moderation/ModerationUtils.java | 24 +++++++++---------- 1 file changed, 11 insertions(+), 13 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 6909504900..302f85b1cf 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 @@ -7,8 +7,6 @@ import net.dv8tion.jda.api.interactions.callbacks.IReplyCallback; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.restaction.AuditableRestAction; -import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; -import net.dv8tion.jda.internal.requests.CompletedRestAction; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -53,20 +51,18 @@ private ModerationUtils() { static final Color AMBIENT_COLOR = Color.decode("#895FE8"); /** - * Provides you with an Enum of actions which have a timely constraint, like being muted for 1 - * hour. + * Actions with timely constraint, like being muted for 1 hour. */ private static final Set TEMPORARY_ACTIONS = EnumSet.of(ModerationAction.MUTE); /** - * Provides you with an Enum of actions which are revoking previously made actions on the user, - * like unmuting the user after it has been muted. + * Actions with revoking previously made actions on the user, like unmuting the user after it + * has been muted. */ private static final Set REVOKE_ACTIONS = EnumSet.of(ModerationAction.UNMUTE, ModerationAction.UNQUARANTINE); /** - * Provides you with an Enum of actions which are letting you know of a violation you have - * committed. + * Actions which are letting you know of a violation you have committed. */ private static final Set SOFT_ACTIONS = EnumSet.of(ModerationAction.WARN); @@ -407,18 +403,20 @@ record TemporaryData(Instant expiresAt, String duration) { * @param temporaryData if the action is a temporary action, such as a 1 hour mute. * @param guild for which the action was triggered. * @param reason for the action. + * @param textChannel for which messages are being sent to. + * * @return the appropriate advice. */ - public static RestAction sendDmAdvice(ModerationAction action, - @Nullable ModerationUtils.TemporaryData temporaryData, Guild guild, String reason, + public static RestAction sendDmAdvice(ModerationAction action, + @Nullable TemporaryData temporaryData, Guild guild, String reason, PrivateChannel textChannel) { final String COMMAND_NAME = "modmail"; if (REVOKE_ACTIONS.contains(action)) { - return new CompletedRestAction<>(guild.getJDA(), textChannel.sendMessage(""" + return textChannel.sendMessage(""" Hey there, you have been %s in the server %s. This means you can now interact with others in the server again. The reason for being %s is: %s - """.formatted(action.getVerb(), guild.getName(), action.getVerb(), reason))); + """.formatted(action.getVerb(), guild.getName(), action.getVerb(), reason)); } String durationMessage; if (SOFT_ACTIONS.contains(action)) { @@ -432,7 +430,7 @@ public static RestAction sendDmAdvice(ModerationAction acti } return MessageUtils.mentionSlashCommand(guild, COMMAND_NAME) - .map(commandMention -> textChannel.sendMessage( + .flatMap(commandMention -> textChannel.sendMessage( """ Hey there, sorry to tell you but unfortunately you have been %s %s in the server %s. To get in touch with a moderator, you can simply use the **%s** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon 😊 From 2b94ea13cd44d65b4523e3dcfaeda429a0885cee Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 19 Oct 2022 14:03:43 +0200 Subject: [PATCH 41/45] Improved the Return type --- .../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 302f85b1cf..8eae6f91c7 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 @@ -407,7 +407,7 @@ record TemporaryData(Instant expiresAt, String duration) { * * @return the appropriate advice. */ - public static RestAction sendDmAdvice(ModerationAction action, + public static RestAction sendDmAdvice(ModerationAction action, @Nullable TemporaryData temporaryData, Guild guild, String reason, PrivateChannel textChannel) { final String COMMAND_NAME = "modmail"; From c193b56c106993a9386d6290b937a4eb630ada25 Mon Sep 17 00:00:00 2001 From: DevSerendipity Date: Wed, 19 Oct 2022 14:12:54 +0200 Subject: [PATCH 42/45] Finish it --- .../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 8eae6f91c7..e0a4126d86 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 @@ -62,7 +62,7 @@ private ModerationUtils() { private static final Set REVOKE_ACTIONS = EnumSet.of(ModerationAction.UNMUTE, ModerationAction.UNQUARANTINE); /** - * Actions which are letting you know of a violation you have committed. + * Soft violations were the user still remains member of the guild, such as a warning */ private static final Set SOFT_ACTIONS = EnumSet.of(ModerationAction.WARN); From 0e46dcd40440cbbecc0660ace0a46b115cdd9799 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 19 Oct 2022 16:10:21 +0200 Subject: [PATCH 43/45] Fixed a few bugs here and there --- .../tjbot/commands/help/HelpSystemHelper.java | 4 +- .../commands/help/ImplicitAskListener.java | 6 +-- .../commands/moderation/ModerationUtils.java | 45 ++++++++++------ .../commands/moderation/MuteCommand.java | 1 + .../moderation/QuarantineCommand.java | 5 +- .../commands/moderation/UnmuteCommand.java | 5 +- .../moderation/UnquarantineCommand.java | 3 +- .../commands/moderation/WarnCommand.java | 4 +- .../moderation/modmail/ModMailCommand.java | 4 +- .../tjbot/commands/utils/MessageUtils.java | 52 +++++++++++++++---- 10 files changed, 88 insertions(+), 41 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java index 4dce9512e0..9f622837b1 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/HelpSystemHelper.java @@ -96,7 +96,7 @@ public HelpSystemHelper(JDA jda, Config config, Database database) { RestAction sendExplanationMessage(GuildMessageChannel threadChannel) { return MessageUtils - .mentionSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME, + .mentionGuildSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME, HelpThreadCommand.Subcommand.CLOSE.getCommandName()) .flatMap(closeCommandMention -> sendExplanationMessage(threadChannel, closeCommandMention)); @@ -313,7 +313,7 @@ private void executeUncategorizedAdviceCheck(long threadChannelId, long authorId // Still no category, send advice return MessageUtils - .mentionSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME, + .mentionGuildSlashCommand(threadChannel.getGuild(), HelpThreadCommand.COMMAND_NAME, HelpThreadCommand.CHANGE_SUBCOMMAND_GROUP, HelpThreadCommand.Subcommand.CHANGE_CATEGORY.getCommandName()) .flatMap(command -> { diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java index 3b550cb0b0..22ad2eca3f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/help/ImplicitAskListener.java @@ -118,7 +118,7 @@ private boolean handleIsNotOnCooldown(Message message) { String threadDescription = lastHelpThread == null ? "your previously created help thread" : lastHelpThread.getAsMention(); - MessageUtils.mentionSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME) + MessageUtils.mentionGuildSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME) .flatMap(command -> message.getChannel() .sendMessage(""" %s Please use %s to follow up on your question, \ @@ -185,7 +185,7 @@ private static RestAction sendInitialMessage(ThreadChannel threadChanne .build(); return MessageUtils - .mentionSlashCommand(originalMessage.getGuild(), HelpThreadCommand.COMMAND_NAME, + .mentionGuildSlashCommand(originalMessage.getGuild(), HelpThreadCommand.COMMAND_NAME, HelpThreadCommand.CHANGE_SUBCOMMAND_GROUP, HelpThreadCommand.Subcommand.CHANGE_CATEGORY.getCommandName()) .flatMap(command -> { @@ -204,7 +204,7 @@ private static RestAction sendInitialMessage(ThreadChannel threadChanne } private static RestAction notifyUser(IMentionable threadChannel, Message message) { - return MessageUtils.mentionSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME) + return MessageUtils.mentionGuildSlashCommand(message.getGuild(), AskCommand.COMMAND_NAME) .flatMap(command -> message.getChannel() .sendMessage( """ 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 e0a4126d86..b4877fc0e5 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 @@ -10,6 +10,7 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; import org.togetherjava.tjbot.commands.utils.MessageUtils; import org.togetherjava.tjbot.config.Config; @@ -23,6 +24,7 @@ import java.util.Optional; import java.util.Set; import java.util.function.Predicate; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -64,7 +66,8 @@ private ModerationUtils() { /** * Soft violations were the user still remains member of the guild, such as a warning */ - private static final Set SOFT_ACTIONS = EnumSet.of(ModerationAction.WARN); + private static final Set SOFT_ACTIONS = + EnumSet.of(ModerationAction.WARN, ModerationAction.QUARANTINE); @@ -401,6 +404,8 @@ record TemporaryData(Instant expiresAt, String duration) { * * @param action the action that is being performed, such as banning a user. * @param temporaryData if the action is a temporary action, such as a 1 hour mute. + * @param additionalDescription any extra description that should be part of the message, if + * desired * @param guild for which the action was triggered. * @param reason for the action. * @param textChannel for which messages are being sent to. @@ -408,35 +413,41 @@ record TemporaryData(Instant expiresAt, String duration) { * @return the appropriate advice. */ public static RestAction sendDmAdvice(ModerationAction action, - @Nullable TemporaryData temporaryData, Guild guild, String reason, - PrivateChannel textChannel) { - final String COMMAND_NAME = "modmail"; + @Nullable TemporaryData temporaryData, @Nullable String additionalDescription, + Guild guild, String reason, PrivateChannel textChannel) { + String additionalDescriptionInfix = + additionalDescription == null ? "" : "\n" + additionalDescription; + if (REVOKE_ACTIONS.contains(action)) { return textChannel.sendMessage(""" - Hey there, you have been %s in the server %s. - This means you can now interact with others in the server again. + Hey there, you have been %s in the server %s.%s The reason for being %s is: %s - """.formatted(action.getVerb(), guild.getName(), action.getVerb(), reason)); + """.formatted(action.getVerb(), guild.getName(), additionalDescriptionInfix, + action.getVerb(), reason)); } String durationMessage; if (SOFT_ACTIONS.contains(action)) { durationMessage = ""; } else if (TEMPORARY_ACTIONS.contains(action)) { durationMessage = - temporaryData == null ? "permanently" : "for " + temporaryData.duration(); + temporaryData == null ? " permanently" : " for " + temporaryData.duration(); } else { throw new IllegalArgumentException( "Action '%s' is not supported by this method".formatted(action)); } - return MessageUtils.mentionSlashCommand(guild, COMMAND_NAME) - .flatMap(commandMention -> textChannel.sendMessage( - """ - Hey there, sorry to tell you but unfortunately you have been %s %s in the server %s. - To get in touch with a moderator, you can simply use the **%s** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon 😊 - The reason for being %s is: %s - """ - .formatted(action.getVerb(), durationMessage, guild.getName(), COMMAND_NAME, - action.getVerb(), reason))); + UnaryOperator createDmMessage = + commandMention -> """ + Hey there, sorry to tell you but unfortunately you have been %s%s in the server %s.%s + To get in touch with a moderator, you can simply use the %s command here in this chat. \ + Your message will then be forwarded and a moderator will get back to you soon 😊 + The reason for being %s is: %s + """ + .formatted(action.getVerb(), durationMessage, guild.getName(), + additionalDescriptionInfix, commandMention, action.getVerb(), reason); + + return MessageUtils.mentionGlobalSlashCommand(guild.getJDA(), ModMailCommand.COMMAND_NAME) + .map(createDmMessage) + .flatMap(textChannel::sendMessage); } } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java index a07d2ddf50..94a4efed9a 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/MuteCommand.java @@ -76,6 +76,7 @@ private static RestAction sendDm(ISnowflake target, return event.getJDA() .openPrivateChannelById(target.getId()) .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, temporaryData, + "This means you can no longer send any messages in the server until you have been unmuted again.", guild, reason, channel)) .mapToResult() .map(Result::isSuccess); diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java index af9592adf8..dffb29292e 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/QuarantineCommand.java @@ -65,8 +65,9 @@ private static RestAction sendDm(ISnowflake target, String reason, Guil GenericEvent event) { return event.getJDA() .openPrivateChannelById(target.getIdLong()) - .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, null, guild, - reason, channel)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.QUARANTINE, null, + "This means you can no longer interact with anyone in the server until you have been unquarantined again.", + guild, reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java index 6dfdf63741..ce050fcd07 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnmuteCommand.java @@ -62,8 +62,9 @@ private static RestAction sendDm(ISnowflake target, String reason, Guil GenericEvent event) { return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, null, guild, - reason, channel)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.UNMUTE, null, + "This means you can now send messages in the server again 👌", guild, reason, + channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java index 83c6c852b7..771d9e787f 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/UnquarantineCommand.java @@ -66,7 +66,8 @@ private static RestAction sendDm(ISnowflake target, String reason, Guil GenericEvent event) { return event.getJDA() .openPrivateChannelById(target.getIdLong()) - .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, null, guild, + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.UNQUARANTINE, null, + "This means you can now interact with others in the server again 👌", guild, reason, channel)) .mapToResult() .map(Result::isSuccess); 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 e71d3a57dd..26b767b652 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 @@ -60,8 +60,8 @@ private static RestAction dmUser(ISnowflake target, String reason, Guil SlashCommandInteractionEvent event) { return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.MUTE, null, guild, - reason, channel)) + .flatMap(channel -> ModerationUtils.sendDmAdvice(ModerationAction.WARN, null, null, + guild, reason, channel)) .mapToResult() .map(Result::isSuccess); } diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java index ab45aa01ac..c50f8af208 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -41,7 +41,7 @@ public final class ModMailCommand extends SlashCommandAdapter { private static final Logger logger = LoggerFactory.getLogger(ModMailCommand.class); - private static final String COMMAND_NAME = "modmail"; + public static final String COMMAND_NAME = "modmail"; private static final String OPTION_MESSAGE = "message"; private static final String OPTION_STAY_ANONYMOUS = "stay-anonymous"; private static final String OPTION_GUILD = "server"; @@ -141,7 +141,7 @@ private MessageCreateAction createModMessage(SlashCommandInteractionEvent event, String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); - User user = wantsToStayAnonymous ? event.getUser() : null; + User user = wantsToStayAnonymous ? null : event.getUser(); MessageCreateAction message = modMailAuditLog.sendMessageEmbeds(createModMailMessage(user, userMessage)); if (!wantsToStayAnonymous) { 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 4768006d75..d92e7d4e00 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 @@ -1,5 +1,6 @@ package org.togetherjava.tjbot.commands.utils; +import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.interactions.commands.Command; @@ -9,6 +10,7 @@ import net.dv8tion.jda.api.utils.MarkdownSanitizer; import java.util.List; +import java.util.function.Supplier; /** * Utility methods for {@link Message}. @@ -62,8 +64,8 @@ public static String escapeMarkdown(String text) { } /** - * Converts a slash command text to a mentioned slash command, which you can directly click on - * in Discord. + * Converts a guild slash command text to a mentioned slash command, which you can directly + * click on in Discord. * * @param guild the {@link Guild} that contains the command * @param commandName the command's name @@ -71,20 +73,50 @@ public static String escapeMarkdown(String text) { * @return Formatted string for the mentioned slash command * @throws IllegalArgumentException when the command isn't found in the guild */ - public static RestAction mentionSlashCommand(Guild guild, String commandName, + public static RestAction mentionGuildSlashCommand(Guild guild, String commandName, String... subCommands) { - return guild.retrieveCommands().map(guildCommands -> { - Command guildCommand = guildCommands.stream() - .filter(c -> c.getName().equalsIgnoreCase(commandName)) + RestAction> availableCommands = guild.retrieveCommands(); + Supplier notFoundMessage = () -> "Command '%s' does not exist in guild %s" + .formatted(commandName, guild.getId()); + + return mentionSlashCommand(availableCommands, notFoundMessage, commandName, subCommands); + } + + /** + * Converts a global slash command text to a mentioned slash command, which you can directly + * click on in Discord. + * + * @param jda to retrieve global commands from + * @param commandName the command's name + * @param subCommands optional subcommand group & subcommand, depending on the base command used + * @return Formatted string for the mentioned slash command + * @throws IllegalArgumentException when the global command was not found + */ + public static RestAction mentionGlobalSlashCommand(JDA jda, String commandName, + String... subCommands) { + RestAction> availableCommands = jda.retrieveCommands(); + Supplier notFoundMessage = + () -> "The global command '%s' does not exist".formatted(commandName); + + return mentionSlashCommand(availableCommands, notFoundMessage, commandName, subCommands); + } + + private static RestAction mentionSlashCommand( + RestAction> availableCommands, Supplier notFoundMessage, + String commandName, String... subCommands) { + return availableCommands.map(commands -> { + Command command = commands.stream() + .filter(commandCandidate -> commandCandidate.getName() + .equalsIgnoreCase(commandName)) .findAny() - .orElseThrow( - () -> new IllegalArgumentException("Command '%s' does not exist in guild %s" - .formatted(commandName, guild.getId()))); + .orElseThrow(() -> new IllegalArgumentException(notFoundMessage.get())); + String commandPath = commandName; if (subCommands.length > 0) { commandPath += " " + String.join(" ", subCommands); } - return String.format("", String.join(" ", commandPath), guildCommand.getId()); + + return String.format("", String.join(" ", commandPath), command.getId()); }); } From 8da2eca4cd09aff6f6e76569763cc6ddaea940ab Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Wed, 19 Oct 2022 16:14:02 +0200 Subject: [PATCH 44/45] Shortened name in javadoc Co-authored-by: Tais993 <49957334+Tais993@users.noreply.github.com> --- .../tjbot/commands/moderation/attachment/package-info.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java index 4d8f9ad910..9fb7d29f53 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java @@ -1,7 +1,7 @@ /** * This packages offers all the functionality for checking attachment safety see - * {@link org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener} as - * main entry point. + * {@link org.togetherjava.tjbot.commands.moderation.attachment.BlacklistedAttachmentListener + * BlacklistedAttachmentListener} as main entry point. */ @MethodsReturnNonnullByDefault @ParametersAreNonnullByDefault From 9403005a2078593b95eb82cb844d1326472cdfc0 Mon Sep 17 00:00:00 2001 From: Zabuzard Date: Thu, 20 Oct 2022 09:55:45 +0200 Subject: [PATCH 45/45] Added missing command mentions --- .../BlacklistedAttachmentListener.java | 35 ++++++++++++------- .../commands/moderation/scam/ScamBlocker.java | 23 ++++++++---- 2 files changed, 39 insertions(+), 19 deletions(-) diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java index 304af4a119..69a8e6024c 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java @@ -3,18 +3,22 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; +import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.api.utils.messages.MessageCreateData; import org.togetherjava.tjbot.commands.MessageReceiverAdapter; +import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; +import org.togetherjava.tjbot.commands.utils.MessageUtils; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.moderation.ModAuditLogWriter; import java.awt.Color; import java.util.List; import java.util.Locale; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -53,29 +57,36 @@ private void handleBadMessage(Message message) { private RestAction dmUser(Message message) { return message.getAuthor() .openPrivateChannel() - .flatMap(privateChannel -> privateChannel.sendMessage(createDmMessage(message))); + .flatMap(privateChannel -> sendDmMessage(message, privateChannel)); } - private MessageCreateData createDmMessage(Message originalMessage) { + private RestAction sendDmMessage(Message originalMessage, PrivateChannel channel) { String contentRaw = originalMessage.getContentRaw(); String blacklistedAttachments = String.join(", ", getBlacklistedAttachmentsFromMessage(originalMessage)); - String dmMessageContent = - """ + UnaryOperator createDmText = + commandMention -> """ Hey there, you posted a message containing a blacklisted file attachment: %s. We had to delete your message for security reasons. - To get in touch with a moderator, you can simply use the **/modmail** command here in this chat. Your message will then be forwarded and a moderator will get back to you soon :thumbsup: + To get in touch with a moderator, you can simply use the %s command here in this chat. \ + Your message will then be forwarded and a moderator will get back to you soon 👍 Feel free to repost your message without, or with a different file instead. Sorry for any inconvenience caused by this 🙇️ """ - .formatted(blacklistedAttachments); - - // No embed needed if there was no message from the user - if (contentRaw.isEmpty()) { - return new MessageCreateBuilder().setContent(dmMessageContent).build(); - } - return createBaseResponse(contentRaw, dmMessageContent); + .formatted(blacklistedAttachments, commandMention); + + return MessageUtils + .mentionGlobalSlashCommand(originalMessage.getJDA(), ModMailCommand.COMMAND_NAME) + .map(createDmText) + .map(dmMessageContent -> { + // No embed needed if there was no message from the user + if (contentRaw.isEmpty()) { + return new MessageCreateBuilder().setContent(dmMessageContent).build(); + } + return createBaseResponse(contentRaw, dmMessageContent); + }) + .flatMap(channel::sendMessage); } private MessageCreateData createBaseResponse(String originalMessageContent, diff --git a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java index cb910da0d1..d38584ddf0 100644 --- a/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/scam/ScamBlocker.java @@ -3,6 +3,7 @@ import net.dv8tion.jda.api.EmbedBuilder; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.*; +import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; @@ -12,6 +13,7 @@ import net.dv8tion.jda.api.interactions.components.buttons.Button; import net.dv8tion.jda.api.interactions.components.buttons.ButtonStyle; import net.dv8tion.jda.api.requests.ErrorResponse; +import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.utils.messages.MessageCreateBuilder; import net.dv8tion.jda.api.utils.messages.MessageCreateData; import org.slf4j.Logger; @@ -25,6 +27,7 @@ import org.togetherjava.tjbot.commands.moderation.ModerationAction; import org.togetherjava.tjbot.commands.moderation.ModerationActionsStore; import org.togetherjava.tjbot.commands.moderation.ModerationUtils; +import org.togetherjava.tjbot.commands.moderation.modmail.ModMailCommand; import org.togetherjava.tjbot.commands.utils.MessageUtils; import org.togetherjava.tjbot.config.Config; import org.togetherjava.tjbot.config.ScamBlockerConfig; @@ -34,6 +37,7 @@ import java.util.*; import java.util.function.Consumer; import java.util.function.Predicate; +import java.util.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -249,19 +253,24 @@ private void dmUser(MessageReceivedEvent event) { } private void dmUser(Guild guild, long userId, JDA jda) { - String dmMessage = - """ + jda.openPrivateChannelById(userId).flatMap(channel -> dmUser(guild, channel)).queue(); + } + + private RestAction dmUser(Guild guild, PrivateChannel channel) { + UnaryOperator createDmMessage = + commandMention -> """ Hey there, we detected that you did send scam in the server %s and therefore put you under quarantine. This means you can no longer interact with anyone in the server until you have been unquarantined again. If you think this was a mistake (for example, your account was hacked, but you got back control over it), - you can get in touch with a moderator by using the **/modmail** command :thumbsup: + you can get in touch with a moderator by using the %s command. \ + Your message will then be forwarded and a moderator will get back to you soon 👍 """ - .formatted(guild.getName()); + .formatted(guild.getName(), commandMention); - jda.openPrivateChannelById(userId) - .flatMap(channel -> channel.sendMessage(dmMessage)) - .queue(); + return MessageUtils.mentionGlobalSlashCommand(guild.getJDA(), ModMailCommand.COMMAND_NAME) + .map(createDmMessage) + .flatMap(channel::sendMessage); } private Optional getReportChannel(Guild guild) {