Skip to content

Remove blacklist functionality from !notify #84

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -140,8 +139,6 @@ public static void main(final String[] args) throws JsonIOException, JsonSyntaxE
root.addAppender(appender);
}

NotifyCommand.reloadBlacklist(null);

EXECUTOR.submit(() ->
{
VersionCheckerRegistry.init();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
{
Expand All @@ -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<Documentation> items)
Expand Down Expand Up @@ -132,7 +132,7 @@ private static Message getMultiResult(String jDocBase, List<Documentation> 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()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,30 +4,20 @@
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;

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)
{
Expand All @@ -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.");
Expand All @@ -79,12 +56,6 @@ else if(content.equalsIgnoreCase("list"))
return;
}

if(BLACKLIST.contains(sender.getIdLong()))
{
message.addReaction("\uD83D\uDE49").queue();
return;
}

final List<Role> roles;
if(content.trim().isEmpty())
{
Expand Down Expand Up @@ -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<Map<String, String>> 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 ->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import org.apache.commons.text.translate.UnicodeUnescaper;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class RootConfig extends Config
{
Expand All @@ -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;
}

Expand All @@ -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)
{
Expand Down