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/Features.java b/application/src/main/java/org/togetherjava/tjbot/commands/Features.java index 581296a77d..28c4f1284f 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; @@ -126,6 +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 ModMailCommand(jda, config)); features.add(new HelpThreadCommand(config, helpSystemHelper)); // Mixtures 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 58a2e232ce..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 @@ -3,11 +3,15 @@ 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 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; import javax.annotation.Nullable; @@ -16,8 +20,11 @@ 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.function.UnaryOperator; import java.util.regex.Pattern; /** @@ -45,6 +52,25 @@ private ModerationUtils() { */ static final Color AMBIENT_COLOR = Color.decode("#895FE8"); + /** + * Actions with timely constraint, like being muted for 1 hour. + */ + private static final Set TEMPORARY_ACTIONS = + EnumSet.of(ModerationAction.MUTE); + /** + * 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); + /** + * 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, ModerationAction.QUARANTINE); + + + /** * Checks whether the given reason is valid. If not, it will handle the situation and respond to * the user. @@ -372,4 +398,56 @@ 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 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. + * + * @return the appropriate advice. + */ + public static RestAction sendDmAdvice(ModerationAction action, + @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.%s + The reason for being %s is: %s + """.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(); + } else { + throw new IllegalArgumentException( + "Action '%s' is not supported by this method".formatted(action)); + } + + 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 c925496ad1..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 @@ -73,19 +73,11 @@ 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 = - """ - 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. - The reason for the mute is: %s - """ - .formatted(durationMessage, guild.getName(), reason); return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .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 7dd2efdb5d..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 @@ -63,18 +63,11 @@ 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. - If you think this was a mistake, or the reason no longer applies, please contact a moderator or admin of the server. - The reason for the quarantine is: %s - """ - .formatted(guild.getName(), reason); - return event.getJDA() .openPrivateChannelById(target.getIdLong()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .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 0e388a2911..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 @@ -60,14 +60,11 @@ 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); return event.getJDA() .openPrivateChannelById(target.getId()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .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 2839d77b2f..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 @@ -64,15 +64,11 @@ 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); - return event.getJDA() .openPrivateChannelById(target.getIdLong()) - .flatMap(channel -> channel.sendMessage(dmMessage)) + .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 0e52fea049..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,13 +60,8 @@ private static RestAction dmUser(ISnowflake target, String reason, Guil SlashCommandInteractionEvent event) { 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. - If you think this was a mistake, please contact a moderator or admin of the server. - The reason for the warning is: %s - """ - .formatted(guild.getName(), reason))) + .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/attachment/BlacklistedAttachmentListener.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/BlacklistedAttachmentListener.java index cd42cc2d82..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,28 +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 %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/attachment/package-info.java b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/attachment/package-info.java index cb62b969b0..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,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 + * 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 new file mode 100644 index 0000000000..c50f8af208 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/ModMailCommand.java @@ -0,0 +1,183 @@ +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.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; +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.Nullable; +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 java.awt.*; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; +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 + * which forwards messages to moderators in a dedicated channel given by + * {@link Config#getModAuditLogChannelPattern()}. + */ + +public final class ModMailCommand extends SlashCommandAdapter { + + private static final Logger logger = LoggerFactory.getLogger(ModMailCommand.class); + 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"; + 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 authorToLastModMailInvocation = createCooldownCache(); + private final Predicate modMailChannelNamePredicate; + private final String configModMailChannelPattern; + + + /** + * Creates a new instance. + * + * @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, "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_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); + + List choices = jda.getGuildCache() + .stream() + .map(guild -> new Command.Choice(guild.getName(), guild.getIdLong())) + .toList(); + + guildOption.addChoices(choices); + + getData().addOptions(messageOption, guildOption, anonymousOption); + + modMailChannelNamePredicate = + Pattern.compile(config.getModMailChannelPattern()).asMatchPredicate(); + + configModMailChannelPattern = config.getModMailChannelPattern(); + } + + private Cache createCooldownCache() { + return Caffeine.newBuilder() + .maximumSize(1_000) + .expireAfterAccess(COOLDOWN_DURATION_VALUE, TimeUnit.of(COOLDOWN_DURATION_UNIT)) + .build(); + } + + @Override + public void onSlashCommand(SlashCommandInteractionEvent event) { + long userId = event.getUser().getIdLong(); + + if (handleIsOnCooldown(userId, event)) { + return; + } + authorToLastModMailInvocation.put(userId, Instant.now()); + 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 by id {} with the pattern {}", + userGuildId, configModMailChannelPattern); + return; + } + + MessageCreateAction message = + createModMessage(event, userId, modMailAuditLog.orElseThrow()); + + sendMessage(event, message); + + } + + private boolean handleIsOnCooldown(long userId, SlashCommandInteractionEvent event) { + if (!isChannelOnCooldown(userId)) { + 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 guildId) { + return jda.getGuildById(guildId) + .getTextChannelCache() + .stream() + .filter(channel -> modMailChannelNamePredicate.test(channel.getName())) + .findAny(); + } + + private MessageCreateAction createModMessage(SlashCommandInteractionEvent event, long userId, + TextChannel modMailAuditLog) { + String userMessage = event.getOption(OPTION_MESSAGE).getAsString(); + boolean wantsToStayAnonymous = event.getOption(OPTION_STAY_ANONYMOUS).getAsBoolean(); + + User user = wantsToStayAnonymous ? null : 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 -> { + 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(); + } + + 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(); + } + + private boolean isChannelOnCooldown(long userId) { + return Optional.ofNullable(authorToLastModMailInvocation.getIfPresent(userId)) + .map(sinceCommandInvoked -> sinceCommandInvoked.plus(COOLDOWN_DURATION_VALUE, + COOLDOWN_DURATION_UNIT)) + .filter(Instant.now()::isBefore) + .isPresent(); + } + +} 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..d0a2de9825 --- /dev/null +++ b/application/src/main/java/org/togetherjava/tjbot/commands/moderation/modmail/package-info.java @@ -0,0 +1,11 @@ +/** + * 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 +package org.togetherjava.tjbot.commands.moderation.modmail; + +import org.togetherjava.tjbot.annotations.MethodsReturnNonnullByDefault; + +import javax.annotation.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 6cb668ab08..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), - please contact a moderator or admin of the server. + 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) { 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()); }); } 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..7c078a97f7 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; @@ -44,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, @@ -71,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); @@ -117,6 +121,16 @@ public String getModAuditLogChannelPattern() { return modAuditLogChannelPattern; } + /** + * Gets the REGEX pattern used to identify the channel that is supposed to contain all messages + * from users who want to contact a moderator. + * + * @return the channel name pattern + */ + public String getModMailChannelPattern() { + return modMailChannelPattern; + } + /** * Gets the token of the Discord bot to connect this application to. *