From 7f925c82afb2ca616bc123fca740cc7821c4b6bf Mon Sep 17 00:00:00 2001 From: Michael Ritter Date: Sat, 7 Aug 2021 16:02:58 +0200 Subject: [PATCH] Remove blacklist functionality from !notify --- .../almightyalpaca/discord/jdabutler/Bot.java | 3 - .../commands/AnnouncementCommand.java | 2 +- .../commands/commands/DocsCommand.java | 6 +- .../commands/commands/HelpCommand.java | 2 +- .../commands/commands/NotifyCommand.java | 202 +----------------- .../discord/jdabutler/config/RootConfig.java | 7 +- 6 files changed, 9 insertions(+), 213 deletions(-) diff --git a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/Bot.java b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/Bot.java index dd0a5f05..20fb5e01 100644 --- a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/Bot.java +++ b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/Bot.java @@ -5,7 +5,6 @@ import ch.qos.logback.classic.encoder.PatternLayoutEncoder; import ch.qos.logback.classic.filter.ThresholdFilter; import com.almightyalpaca.discord.jdabutler.commands.Dispatcher; -import com.almightyalpaca.discord.jdabutler.commands.commands.NotifyCommand; import com.almightyalpaca.discord.jdabutler.config.Config; import com.almightyalpaca.discord.jdabutler.config.ConfigFactory; import com.almightyalpaca.discord.jdabutler.config.exception.KeyNotFoundException; @@ -140,8 +139,6 @@ public static void main(final String[] args) throws JsonIOException, JsonSyntaxE root.addAppender(appender); } - NotifyCommand.reloadBlacklist(null); - EXECUTOR.submit(() -> { VersionCheckerRegistry.init(); diff --git a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/AnnouncementCommand.java b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/AnnouncementCommand.java index 7debce44..10ddd724 100644 --- a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/AnnouncementCommand.java +++ b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/AnnouncementCommand.java @@ -120,7 +120,7 @@ public void dispatch(final User sender, final TextChannel channel, final Message eb.setThumbnail(image); eb.setFooter(sender.getName(), sender.getEffectiveAvatarUrl()); - mb.setEmbed(eb.build()); + mb.setEmbeds(eb.build()); MiscUtils.announce(channel, role, mb.build(), true); diff --git a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/DocsCommand.java b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/DocsCommand.java index c474eb99..0ba6dc9e 100644 --- a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/DocsCommand.java +++ b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/DocsCommand.java @@ -53,7 +53,7 @@ else if(fields != null && fields.get("Incubating") != null) if (documentation.getContent().length() > MessageEmbed.TEXT_MAX_LENGTH) { embed.appendDescription("Description too long. Please refer to [the online docs](" + documentation.getUrl(jDocBase) + ')'); - return new MessageBuilder().setEmbed(embed.build()).build(); + return new MessageBuilder().setEmbeds(embed.build()).build(); } if (documentation.getContent().length() == 0) { @@ -78,7 +78,7 @@ else if(fields != null && fields.get("Incubating") != null) } } } - return new MessageBuilder().setEmbed(embed.build()).build(); + return new MessageBuilder().setEmbeds(embed.build()).build(); } private void showPaginatorEmbed(GuildMessageReceivedEvent event, String jDocBase, Set items) @@ -132,7 +132,7 @@ private static Message getMultiResult(String jDocBase, List searc Documentation documentation = search.get(index); embed.appendDescription('[' + documentation.getShortTitle() + "](" + documentation.getUrl(jDocBase) + ")\n"); } - return new MessageBuilder().setEmbed(embed.build()).build(); + return new MessageBuilder().setEmbeds(embed.build()).build(); } private static EmbedBuilder getDefaultEmbed() diff --git a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/HelpCommand.java b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/HelpCommand.java index 367967ad..2e9d135e 100644 --- a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/HelpCommand.java +++ b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/HelpCommand.java @@ -32,7 +32,7 @@ public void dispatch(final User sender, final TextChannel channel, final Message final String help = Bot.dispatcher.getCommands().stream().sorted(Comparator.comparing(Command::getName)).filter(c -> c.getHelp() != null).map(c -> String.format("`%s` - %s", StringUtils.rightPad(prefix + c.getName().toLowerCase() + "", size, "."), c.getHelp())).collect(Collectors.joining("\n")); builder.setAuthor(message.getMember().getEffectiveName(), null, sender.getEffectiveAvatarUrl()); builder.setDescription(help); - reply(event, new MessageBuilder().setEmbed(builder.build()).build()); + reply(event, new MessageBuilder().setEmbeds(builder.build()).build()); } @Override diff --git a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/NotifyCommand.java b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/NotifyCommand.java index 642bf3d7..b422c2cd 100644 --- a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/NotifyCommand.java +++ b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/commands/commands/NotifyCommand.java @@ -4,18 +4,11 @@ import com.almightyalpaca.discord.jdabutler.commands.Command; import com.kantenkugel.discordbot.versioncheck.VersionCheckerRegistry; import com.kantenkugel.discordbot.versioncheck.items.VersionedItem; -import gnu.trove.set.TLongSet; -import gnu.trove.set.hash.TLongHashSet; import net.dv8tion.jda.api.EmbedBuilder; -import net.dv8tion.jda.api.audit.ActionType; -import net.dv8tion.jda.api.audit.AuditLogChange; -import net.dv8tion.jda.api.audit.AuditLogKey; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent; -import java.time.OffsetDateTime; import java.util.List; -import java.util.Map; import java.util.Objects; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; @@ -23,11 +16,8 @@ public class NotifyCommand extends Command { - private static final long BLACKLIST_CHANNEL_ID = 454657809397710859L; private static final String[] ALIASES = { "subscribe" }; - private static final TLongSet BLACKLIST = new TLongHashSet(); - @Override public void dispatch(final User sender, final TextChannel channel, final Message message, final String content, final GuildMessageReceivedEvent event) { @@ -40,20 +30,7 @@ public void dispatch(final User sender, final TextChannel channel, final Message return; } - if(content.startsWith("blacklist")) - { - if(Bot.isAdmin(sender)) - { - String subContent = content.substring(Math.min("blacklist".length() + 1, content.length())); - handleBlacklist(event, message, subContent); - } - else - { - sendFailed(message); - } - return; - } - else if(content.equalsIgnoreCase("list")) + if(content.equalsIgnoreCase("list")) { EmbedBuilder embed = new EmbedBuilder(); embed.setDescription("You can subscribe to one of the following items. To unsubscribe simply type the command again."); @@ -79,12 +56,6 @@ else if(content.equalsIgnoreCase("list")) return; } - if(BLACKLIST.contains(sender.getIdLong())) - { - message.addReaction("\uD83D\uDE49").queue(); - return; - } - final List roles; if(content.trim().isEmpty()) { @@ -174,177 +145,6 @@ public String getName() return "notify"; } - public static void reloadBlacklist(GuildMessageReceivedEvent event) - { - TextChannel blacklistChannel = getBlacklistChannel(); - BLACKLIST.clear(); - blacklistChannel.getIterableHistory().forEachAsync(message -> - { - String[] split = message.getContentRaw().split("\\s+"); - try - { - long userId = Long.parseUnsignedLong(split[0]); - BLACKLIST.add(userId); - } - catch(NumberFormatException ex) - { - if(event != null) - event.getChannel().sendMessageFormat("Message `%s` is not a valid blacklist message", message.getContentStripped()) - .queue(msg -> linkMessage(event.getMessageIdLong(), msg.getIdLong())); - } - return true; - }).thenRun(() -> - { - if(event != null) - event.getChannel().sendMessage("Reloaded " + BLACKLIST.size() + " users into blacklist").queue(msg -> - linkMessage(event.getMessageIdLong(), msg.getIdLong())); - }); - } - - private void handleBlacklist(GuildMessageReceivedEvent event, Message msg, String content) - { - if(content.isEmpty()) - { - sendFailed(msg); - return; - } - String[] args = content.split("\\s+", 2); - TextChannel blacklistChannel = getBlacklistChannel(); - switch(args[0].toLowerCase()) - { - case "fetch": - case "generate": - case "get": - TextChannel searchChannel = msg.getMentionedChannels().isEmpty() - ? VersionCheckerRegistry.getItem("jda").getAnnouncementChannel() - : msg.getMentionedChannels().get(0); - if(searchChannel == null) - reply(event, "Could not determine channel to search in"); - else - fetchBlacklist(searchChannel, event); - break; - case "update": - case "import": - case "reload": - reloadBlacklist(event); - break; - case "add": - msg.getMentionedUsers().forEach(u -> - { - if(!BLACKLIST.contains(u.getIdLong())) - { - BLACKLIST.add(u.getIdLong()); - sendBlacklistAdditionMessage(blacklistChannel, u); - } - }); - msg.addReaction("\u2705").queue(); - break; - case "rm": - case "remove": - TLongSet removedIds = new TLongHashSet(); - msg.getMentionedUsers().forEach(u -> - { - if(BLACKLIST.contains(u.getIdLong())) - { - BLACKLIST.remove(u.getIdLong()); - removedIds.add(u.getIdLong()); - } - }); - removeFromChannel(blacklistChannel, removedIds); - msg.addReaction("\u2705").queue(); - break; - default: - reply(event, "Unknown subcommand"); - } - } - - private void fetchBlacklist(TextChannel searchChannel, GuildMessageReceivedEvent event) - { - Message mentionMessage = searchChannel.getIterableHistory().stream() - .filter(message -> message.getAuthor().isBot() && !message.getMentionedRoles().isEmpty()) - .limit(500).findFirst().orElse(null); - if(mentionMessage == null) - { - reply(event, "Could not find announcement message within 500 messages"); - return; - } - - Role announcementRole = mentionMessage.getMentionedRoles().get(0); - OffsetDateTime abortTime = mentionMessage.getTimeCreated(); - - TLongSet blacklistedUsers = new TLongHashSet(); - - searchChannel.getGuild().retrieveAuditLogs().type(ActionType.MEMBER_ROLE_UPDATE).forEachAsync(log -> - { - if(log.getTimeCreated().isBefore(abortTime)) - return false; - AuditLogChange removedRoles = log.getChangeByKey(AuditLogKey.MEMBER_ROLES_REMOVE); - if(removedRoles == null) - return true; - - if(log.getUser() == null || log.getUser().isBot() || !Bot.isAdmin(log.getUser())) - return true; - - - List> removedRoleMap = removedRoles.getNewValue(); - if(removedRoleMap.stream().mapToLong(map -> Long.parseUnsignedLong(map.get("id"))).noneMatch(rem -> rem == announcementRole.getIdLong())) - return true; - - blacklistedUsers.add(log.getTargetIdLong()); - - return true; - }).thenRun(() -> - { - if(blacklistedUsers.isEmpty() || (blacklistedUsers.removeAll(BLACKLIST) && blacklistedUsers.isEmpty())) - { - reply(event, "No1 matching blacklist criteria found!"); - return; - } - BLACKLIST.addAll(blacklistedUsers); - TextChannel blacklistChannel = getBlacklistChannel(); - blacklistedUsers.forEach(userId -> - { - sendBlacklistAdditionMessage(blacklistChannel, Bot.jda.getUserById(userId)); - return true; - }); - reply(event, "Added " + blacklistedUsers.size() + " users to notify blacklist"); - }); - } - - private static void sendBlacklistAdditionMessage(TextChannel blacklistChannel, User blacklisted) - { - blacklistChannel.sendMessageFormat("%d - %#s", blacklisted.getIdLong(), blacklisted).queue(); - } - - private static void removeFromChannel(TextChannel blacklistChannel, TLongSet toRemove) - { - if(toRemove.isEmpty()) - return; - blacklistChannel.getIterableHistory().forEachAsync(msg -> - { - String[] splits = msg.getContentRaw().split("\\s+"); - try - { - long idFromMessage = Long.parseUnsignedLong(splits[0]); - if(toRemove.contains(idFromMessage)) - { - toRemove.remove(idFromMessage); - msg.delete().queue(); - if(toRemove.isEmpty()) - return false; - } - } - catch(NumberFormatException ignored) {} - - return true; - }); - } - - private static TextChannel getBlacklistChannel() - { - return Bot.jda.getTextChannelById(BLACKLIST_CHANNEL_ID); - } - private static void respond(Message origMsg, String newMessageContent) { origMsg.getChannel().sendMessage(newMessageContent).queue(responseMsg -> diff --git a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/config/RootConfig.java b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/config/RootConfig.java index afa1eae9..1fd9f77e 100644 --- a/bot/src/main/java/com/almightyalpaca/discord/jdabutler/config/RootConfig.java +++ b/bot/src/main/java/com/almightyalpaca/discord/jdabutler/config/RootConfig.java @@ -7,6 +7,7 @@ import org.apache.commons.text.translate.UnicodeUnescaper; import java.io.*; +import java.nio.charset.StandardCharsets; public class RootConfig extends Config { @@ -15,7 +16,7 @@ public class RootConfig extends Config RootConfig(final File file) throws WrongTypeException, KeyNotFoundException, JsonIOException, JsonSyntaxException, FileNotFoundException { - super(null, new JsonParser().parse(new FileReader(file)).getAsJsonObject()); + super(null, JsonParser.parseReader(new FileReader(file)).getAsJsonObject()); this.configFile = file; } @@ -30,11 +31,9 @@ public void save() throws ConfigSaveException { final Gson gson = new GsonBuilder().serializeNulls().setPrettyPrinting().serializeSpecialFloatingPointValues().create(); final String json = gson.toJson(this.config); - try + try(Writer writer = new OutputStreamWriter(new FileOutputStream(this.configFile), StandardCharsets.UTF_8)) { - final BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(this.configFile), "UTF-8")); new UnicodeUnescaper().translate(json, writer); - writer.close(); } catch (final IOException e) {