Search in sources :

Example 71 with Consumer

use of java.util.function.Consumer in project jdk8u_jdk by JetBrains.

the class SerializedLambdaTest method testDiscardReturnBound.

//Test throwing away return type
public void testDiscardReturnBound() throws IOException, ClassNotFoundException {
    List<String> list = new ArrayList<>();
    Consumer<String> c = (Consumer<String> & Serializable) list::add;
    assertSerial(c, cc -> {
        assertTrue(cc instanceof Consumer);
    });
    AtomicLong a = new AtomicLong();
    LongConsumer lc = (LongConsumer & Serializable) a::addAndGet;
    assertSerial(lc, plc -> {
        plc.accept(3);
    });
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) LongConsumer(java.util.function.LongConsumer) LongConsumer(java.util.function.LongConsumer) Consumer(java.util.function.Consumer) ArrayList(java.util.ArrayList)

Example 72 with Consumer

use of java.util.function.Consumer in project MantaroBot by Mantaro.

the class ReactionOperations method createOrGet.

public static Future<Void> createOrGet(Message message, long timeoutSeconds, ReactionOperation operation, String... defaultReactions) {
    // We should be getting Mantaro's messages
    if (!message.getAuthor().equals(message.getJDA().getSelfUser()))
        throw new IllegalArgumentException("Must provide a message sent by the bot");
    Future<Void> f = createOrGet(message.getIdLong(), timeoutSeconds, operation);
    if (defaultReactions.length > 0) {
        AtomicInteger index = new AtomicInteger();
        AtomicReference<Consumer<Void>> c = new AtomicReference<>();
        // Ignore errors (Like unknown message).
        Consumer<Throwable> ignore = (t) -> {
        };
        c.set(ignored -> {
            if (f.isCancelled())
                return;
            int i = index.incrementAndGet();
            if (i < defaultReactions.length) {
                message.addReaction(reaction(defaultReactions[i])).queue(c.get(), ignore);
            }
        });
        message.addReaction(reaction(defaultReactions[0])).queue(c.get(), ignore);
    }
    return f;
}
Also used : MessageReactionAddEvent(net.dv8tion.jda.core.events.message.react.MessageReactionAddEvent) ExpiringMap(net.jodah.expiringmap.ExpiringMap) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicReference(java.util.concurrent.atomic.AtomicReference) Message(net.dv8tion.jda.core.entities.Message) MessageReactionRemoveEvent(net.dv8tion.jda.core.events.message.react.MessageReactionRemoveEvent) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Future(java.util.concurrent.Future) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Event(net.dv8tion.jda.core.events.Event) ReactionOperation(net.kodehawa.mantarobot.core.listeners.operations.core.ReactionOperation) EventListener(net.dv8tion.jda.core.hooks.EventListener) MessageReactionRemoveAllEvent(net.dv8tion.jda.core.events.message.react.MessageReactionRemoveAllEvent) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) Consumer(java.util.function.Consumer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicReference(java.util.concurrent.atomic.AtomicReference)

Example 73 with Consumer

use of java.util.function.Consumer in project MantaroBot by Mantaro.

the class CommandOptions method onRegister.

@Subscribe
public void onRegister(OptionRegistryEvent e) {
    // region disallow
    registerOption("server:command:disallow", "Command disallow", "Disallows a command from being triggered at all. Use the command name\n" + "**Example:** `~>opts server command disallow 8ball`", "Disallows a command from being triggered at all.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        String commandName = args[0];
        if (DefaultCommandProcessor.REGISTRY.commands().get(commandName) == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "No command called " + commandName).queue();
            return;
        }
        if (commandName.equals("opts") || commandName.equals("help")) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot disable the options or the help command.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.getDisabledCommands().add(commandName);
        event.getChannel().sendMessage(EmoteReference.MEGA + "Disabled " + commandName + " on this server.").queue();
        dbGuild.saveAsync();
    });
    // endregion
    // region allow
    registerOption("server:command:allow", "Command allow", "Allows a command from being triggered. Use the command name\n" + "**Example:** `~>opts server command allow 8ball`", "Allows a command from being triggered.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        String commandName = args[0];
        if (DefaultCommandProcessor.REGISTRY.commands().get(commandName) == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "No command called " + commandName).queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.getDisabledCommands().remove(commandName);
        event.getChannel().sendMessage(EmoteReference.MEGA + "Enabled " + commandName + " on this server.").queue();
        dbGuild.saveAsync();
    });
    // endregion
    // region specific
    registerOption("server:command:specific:disallow", "Specific command disallow", "Disallows a command from being triggered at all in a specific channel. Use the channel **name** and command name\n" + "**Example:** `~>opts server command specific disallow general 8ball`", "Disallows a command from being triggered at all in a specific channel.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the channel name and the command to disallow!").queue();
            return;
        }
        String channelName = args[0];
        String commandName = args[1];
        if (DefaultCommandProcessor.REGISTRY.commands().get(commandName) == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "No command called " + commandName).queue();
            return;
        }
        if (commandName.equals("opts") || commandName.equals("help")) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot disable the options or the help command.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        TextChannel channel = Utils.findChannel(event, channelName);
        if (channel == null)
            return;
        String id = channel.getId();
        guildData.getChannelSpecificDisabledCommands().computeIfAbsent(id, k -> new ArrayList<>());
        guildData.getChannelSpecificDisabledCommands().get(id).add(commandName);
        event.getChannel().sendMessage(EmoteReference.MEGA + "Disabled " + commandName + " on channel #" + channel.getName() + ".").queue();
        dbGuild.saveAsync();
    });
    registerOption("server:command:specific:allow", "Specific command allow", "Re-allows a command from being triggered in a specific channel. Use the channel **name** and command name\n" + "**Example:** `~>opts server command specific allow general 8ball`", "Re-allows a command from being triggered in a specific channel.", ((event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the channel name and the command to disallow!").queue();
            return;
        }
        String channelName = args[0];
        String commandName = args[1];
        if (DefaultCommandProcessor.REGISTRY.commands().get(commandName) == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "No command called " + commandName).queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        TextChannel channel = Utils.findChannel(event, channelName);
        if (channel == null)
            return;
        String id = channel.getId();
        guildData.getChannelSpecificDisabledCommands().computeIfAbsent(id, k -> new ArrayList<>());
        guildData.getChannelSpecificDisabledCommands().get(id).remove(commandName);
        event.getChannel().sendMessage(EmoteReference.MEGA + "Enabled " + commandName + " on channel #" + channel.getName() + ".").queue();
        dbGuild.saveAsync();
    }));
    // endregion
    // region channel
    // region disallow
    registerOption("server:channel:disallow", "Channel disallow", "Disallows a channel from commands. Use the channel **name**\n" + "**Example:** `~>opts server channel disallow general`", "Disallows a channel from commands.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        if (args[0].equals("*")) {
            Set<String> allChannelsMinusCurrent = event.getGuild().getTextChannels().stream().filter(textChannel -> textChannel.getId().equals(event.getChannel().getId())).map(ISnowflake::getId).collect(Collectors.toSet());
            guildData.getDisabledChannels().addAll(allChannelsMinusCurrent);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Disallowed all channels except the current one. " + "You can start allowing channels one by one again with `opts server channel allow` from **this** channel. " + "You can disallow this channel later if you so desire.").queue();
            return;
        }
        if ((guildData.getDisabledChannels().size() + 1) >= event.getGuild().getTextChannels().size()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot disable more channels since the bot wouldn't be able to talk otherwise :<").queue();
            return;
        }
        Consumer<TextChannel> consumer = textChannel -> {
            guildData.getDisabledChannels().add(textChannel.getId());
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.OK + "Channel " + textChannel.getAsMention() + " will not longer listen to commands").queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, args[0], consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    // endregion
    // region allow
    registerOption("server:channel:allow", "Channel allow", "Allows a channel from commands. Use the channel **name**\n" + "**Example:** `~>opts server channel allow general`", "Re-allows a channel from commands.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        if (args[0].equals("*")) {
            guildData.getDisabledChannels().clear();
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "All channels are allowed now.").queue();
            return;
        }
        Consumer<TextChannel> consumer = textChannel -> {
            guildData.getDisabledChannels().remove(textChannel.getId());
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.OK + "Channel " + textChannel.getAsMention() + " will now listen to commands").queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, args[0], consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    // endregion
    // endregion
    // region category
    registerOption("category:disable", "Disable categories", "Disables a specified category.\n" + "If a non-valid category it's specified, it will display a list of valid categories\n" + "You need the category name, for example ` ~>opts category disable Action`", "Disables a specified category", (event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toDisable = Category.lookupFromString(args[0]);
        if (toDisable == null) {
            AtomicInteger at = new AtomicInteger();
            event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
            return;
        }
        if (guildData.getDisabledCategories().contains(toDisable)) {
            event.getChannel().sendMessage(EmoteReference.WARNING + "This category is already disabled.").queue();
            return;
        }
        if (toDisable.toString().equals("Moderation")) {
            event.getChannel().sendMessage(EmoteReference.WARNING + "You cannot disable moderation since it contains this command.").queue();
            return;
        }
        guildData.getDisabledCategories().add(toDisable);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Disabled category `" + toDisable.toString() + "`").queue();
    });
    registerOption("category:enable", "Enable categories", "Enables a specified category.\n" + "If a non-valid category it's specified, it will display a list of valid categories\n" + "You need the category name, for example ` ~>opts category enable Action`", "Enables a specified category", (event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toEnable = Category.lookupFromString(args[0]);
        if (toEnable == null) {
            AtomicInteger at = new AtomicInteger();
            event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
            return;
        }
        guildData.getDisabledCategories().remove(toEnable);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Enabled category `" + toEnable.toString() + "`").queue();
    });
    // region specific
    registerOption("category:specific:disable", "Disable categories on a specific channel", "Disables a specified category on a specific channel.\n" + "If a non-valid category it's specified, it will display a list of valid categories\n" + "You need the category name and the channel name, for example ` ~>opts category specific disable Action general`", "Disables a specified category", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable and the channel where.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toDisable = Category.lookupFromString(args[0]);
        String channelName = args[1];
        Consumer<TextChannel> consumer = selectedChannel -> {
            if (toDisable == null) {
                AtomicInteger at = new AtomicInteger();
                event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
                return;
            }
            guildData.getChannelSpecificDisabledCategories().computeIfAbsent(selectedChannel.getId(), uwu -> new ArrayList<>());
            if (guildData.getChannelSpecificDisabledCategories().get(selectedChannel.getId()).contains(toDisable)) {
                event.getChannel().sendMessage(EmoteReference.WARNING + "This category is already disabled.").queue();
                return;
            }
            if (toDisable.toString().equals("Moderation")) {
                event.getChannel().sendMessage(EmoteReference.WARNING + "You cannot disable moderation since it contains this command.").queue();
                return;
            }
            guildData.getChannelSpecificDisabledCategories().get(selectedChannel.getId()).add(toDisable);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Disabled category `" + toDisable.toString() + "` on channel " + selectedChannel.getAsMention()).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    registerOption("category:specific:enable", "Enable categories on a specific channel", "Enables a specified category on a specific channel.\n" + "If a non-valid category it's specified, it will display a list of valid categories\n" + "You need the category name and the channel name, for example ` ~>opts category specific enable Action general`", "Enables a specified category", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable and the channel where.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toEnable = Category.lookupFromString(args[0]);
        String channelName = args[1];
        Consumer<TextChannel> consumer = selectedChannel -> {
            if (toEnable == null) {
                AtomicInteger at = new AtomicInteger();
                event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
                return;
            }
            if (selectedChannel == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a valid channel!").queue();
                return;
            }
            List l = guildData.getChannelSpecificDisabledCategories().computeIfAbsent(selectedChannel.getId(), uwu -> new ArrayList<>());
            if (l.isEmpty() || !l.contains(toEnable)) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "This category wasn't disabled?").queue();
                return;
            }
            guildData.getChannelSpecificDisabledCategories().get(selectedChannel.getId()).remove(toEnable);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Enabled category `" + toEnable.toString() + "` on channel " + selectedChannel.getAsMention()).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    // endregion
    // endregion
    registerOption("server:role:specific:disallow", "Disallows a role from executing an specific command", "Disallows a role from executing an specific command\n" + "This command takes the command to disallow and the role name afterwards. If the role name contains spaces, wrap it in quotes \"like this\"\n" + "Example: `~>opts server role specific disallow daily Member`", "Disallows a role from executing an specific command", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need the role and the command to disallow!").queue();
            return;
        }
        String commandDisallow = args[0];
        String roleDisallow = args[1];
        Consumer<Role> consumer = role -> {
            DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
            GuildData guildData = dbGuild.getData();
            if (!DefaultCommandProcessor.REGISTRY.commands().containsKey(commandDisallow)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That command doesn't exist!").queue();
                return;
            }
            if (commandDisallow.equals("opts") || commandDisallow.equals("help")) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot disable the options or the help command.").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCommands().computeIfAbsent(role.getId(), key -> new ArrayList<>());
            if (guildData.getRoleSpecificDisabledCommands().get(role.getId()).contains(commandDisallow)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "This command was already disabled for the specified role.").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCommands().get(role.getId()).add(commandDisallow);
            dbGuild.save();
            event.getChannel().sendMessage(String.format("%sSuccessfully restricted command `%s` for role `%s`", EmoteReference.CORRECT, commandDisallow, role.getName())).queue();
        };
        Role role = Utils.findRoleSelect(event, roleDisallow, consumer);
        if (role != null) {
            consumer.accept(role);
        }
    });
    registerOption("server:role:specific:allow", "Allows a role from executing an specific command", "Allows a role from executing an specific command\n" + "This command takes either the role name, id or mention and the command to disallow afterwards. If the role name contains spaces, wrap it in quotes \"like this\"\n" + "Example: `~>opts server role specific allow daily Member`", "Allows a role from executing an specific command", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need the role and the command to allow!").queue();
            return;
        }
        String commandAllow = args[0];
        String roleAllow = args[1];
        Consumer<Role> consumer = role -> {
            if (role == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a valid role!").queue();
                return;
            }
            DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
            GuildData guildData = dbGuild.getData();
            if (!DefaultCommandProcessor.REGISTRY.commands().containsKey(commandAllow)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That command doesn't exist!").queue();
                return;
            }
            List l = guildData.getRoleSpecificDisabledCommands().computeIfAbsent(role.getId(), key -> new ArrayList<>());
            if (l.isEmpty() || !l.contains(commandAllow)) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "This command wasn't disabled for this role?").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCommands().get(role.getId()).remove(commandAllow);
            dbGuild.save();
            event.getChannel().sendMessage(String.format("%sSuccessfully un-restricted command `%s` for role `%s`", EmoteReference.CORRECT, commandAllow, role.getName())).queue();
        };
        Role role = Utils.findRoleSelect(event, roleAllow, consumer);
        if (role != null) {
            consumer.accept(role);
        }
    });
    registerOption("category:role:specific:disable", "Disables a role from executing commands in an specified category.", "Disables a role from executing commands in an specified category\n" + "This command takes the category name and the role to disable afterwards. If the role name contains spaces, wrap it in quotes \"like this\"\n" + "Example: `~>opts category role specific disable Currency Member`", "Disables a role from executing commands in an specified category.", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable and the role to.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toDisable = Category.lookupFromString(args[0]);
        String roleName = args[1];
        Consumer<Role> consumer = role -> {
            if (toDisable == null) {
                AtomicInteger at = new AtomicInteger();
                event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCategories().computeIfAbsent(role.getId(), cat -> new ArrayList<>());
            if (guildData.getRoleSpecificDisabledCategories().get(role.getId()).contains(toDisable)) {
                event.getChannel().sendMessage(EmoteReference.WARNING + "This category is already disabled.").queue();
                return;
            }
            if (toDisable.toString().equals("Moderation")) {
                event.getChannel().sendMessage(EmoteReference.WARNING + "You cannot disable moderation since it contains this command.").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCategories().get(role.getId()).add(toDisable);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Disabled category `" + toDisable.toString() + "` for role " + role.getName()).queue();
        };
        Role role = Utils.findRoleSelect(event, roleName, consumer);
        if (role != null) {
            consumer.accept(role);
        }
    });
    registerOption("category:role:specific:enable", "Enables a role from executing commands in an specified category.", "Enables a role from executing commands in an specified category\n" + "This command takes the category name and the role to enable afterwards. If the role name contains spaces, wrap it in quotes \"like this\"\n" + "Example: `~>opts category role specific enable Currency Member`", "Enables a role from executing commands in an specified category.", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable and the channel where.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toEnable = Category.lookupFromString(args[0]);
        String roleName = args[1];
        Consumer<Role> consumer = role -> {
            if (toEnable == null) {
                AtomicInteger at = new AtomicInteger();
                event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
                return;
            }
            if (role == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a valid role!").queue();
                return;
            }
            List l = guildData.getRoleSpecificDisabledCategories().computeIfAbsent(role.getId(), cat -> new ArrayList<>());
            if (l.isEmpty() || !l.contains(toEnable)) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "This category wasn't disabled?").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCategories().get(role.getId()).remove(toEnable);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Enabled category `" + toEnable.toString() + "` for role " + role.getName()).queue();
        };
        Role role = Utils.findRoleSelect(event, roleName, consumer);
        if (role != null) {
            consumer.accept(role);
        }
    });
}
Also used : Role(net.dv8tion.jda.core.entities.Role) DefaultCommandProcessor(net.kodehawa.mantarobot.core.processor.DefaultCommandProcessor) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Option(net.kodehawa.mantarobot.options.annotations.Option) Utils(net.kodehawa.mantarobot.utils.Utils) Set(java.util.Set) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Consumer(java.util.function.Consumer) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Subscribe(com.google.common.eventbus.Subscribe) OptionType(net.kodehawa.mantarobot.options.core.OptionType) OptionRegistryEvent(net.kodehawa.mantarobot.options.event.OptionRegistryEvent) OptionHandler(net.kodehawa.mantarobot.options.core.OptionHandler) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) ArrayList(java.util.ArrayList) Role(net.dv8tion.jda.core.entities.Role) TextChannel(net.dv8tion.jda.core.entities.TextChannel) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) List(java.util.List) Subscribe(com.google.common.eventbus.Subscribe)

Example 74 with Consumer

use of java.util.function.Consumer in project MantaroBot by Mantaro.

the class GeneralOptions method onRegistry.

@Subscribe
public void onRegistry(OptionRegistryEvent e) {
    registerOption("lobby:reset", "Lobby reset", "Fixes stuck game/poll/operations session.", event -> {
        GameLobby.LOBBYS.remove(event.getChannel());
        Poll.getRunningPolls().remove(event.getChannel().getId());
        Future<Void> stuck = InteractiveOperations.get(event.getChannel());
        if (stuck != null)
            stuck.cancel(true);
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Reset the lobby correctly.").queue();
    });
    registerOption("modlog:blacklist", "Modlog blacklist", "Prevents an user from appearing in modlogs.\n" + "You need the user mention.\n" + "Example: ~>opts modlog blacklist @user", "Prevents an user from appearing in modlogs", event -> {
        List<User> mentioned = event.getMessage().getMentionedUsers();
        if (mentioned.isEmpty()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "**You need to specify the users to locally blacklist from mod logs.**").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        List<String> toBlackList = mentioned.stream().map(ISnowflake::getId).collect(Collectors.toList());
        String blacklisted = mentioned.stream().map(user -> user.getName() + "#" + user.getDiscriminator()).collect(Collectors.joining(","));
        guildData.getModlogBlacklistedPeople().addAll(toBlackList);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Locally blacklisted users from mod-log: **" + blacklisted + "**").queue();
    });
    registerOption("modlog:whitelist", "Modlog whitelist", "Allows an user from appearing in modlogs.\n" + "You need the user mention.\n" + "Example: ~>opts modlog whitelist @user", "Allows an user from appearing in modlogs (everyone by default)", event -> {
        List<User> mentioned = event.getMessage().getMentionedUsers();
        if (mentioned.isEmpty()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "**You need to specify the users to locally whitelist from mod logs.**").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        List<String> toUnBlacklist = mentioned.stream().map(ISnowflake::getId).collect(Collectors.toList());
        String unBlacklisted = mentioned.stream().map(user -> user.getName() + "#" + user.getDiscriminator()).collect(Collectors.joining(","));
        guildData.getModlogBlacklistedPeople().removeAll(toUnBlacklist);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Locally un-blacklisted users from mod-log: **" + unBlacklisted + "**").queue();
    });
    registerOption("linkprotection:toggle", "Link-protection toggle", "Toggles anti-link protection.", event -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        boolean toggler = guildData.isLinkProtection();
        guildData.setLinkProtection(!toggler);
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Set link protection to " + "`" + !toggler + "`").queue();
        dbGuild.save();
    });
    registerOption("linkprotection:channel:allow", "Link-protection channel allow", "Allows the posting of invites on a channel.\n" + "You need the channel name.\n" + "Example: ~>opts linkprotection channel allow promote-here", "Allows the posting of invites on a channel.", (event, args) -> {
        if (args.length == 0) {
            OptsCmd.onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String channelName = args[0];
        Consumer<TextChannel> consumer = tc -> {
            guildData.getLinkProtectionAllowedChannels().add(tc.getId());
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.OK + tc.getAsMention() + " can now be used to send discord invites.").queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    registerOption("linkprotection:channel:disallow", "Link-protection channel disallow", "Disallows the posting of invites on a channel.\n" + "You need the channel name.\n" + "Example: ~>opts linkprotection channel disallow general", "Disallows the posting of invites on a channel (every channel by default)", (event, args) -> {
        if (args.length == 0) {
            OptsCmd.onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String channelName = args[0];
        Consumer<TextChannel> consumer = tc -> {
            guildData.getLinkProtectionAllowedChannels().remove(tc.getId());
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.OK + tc.getAsMention() + " cannot longer be used to send discord invites.").queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    registerOption("linkprotection:user:allow", "Link-protection user whitelist", "Allows an user to post invites.\n" + "You need to mention the user.", "Allows an user to post invites.", (event, args) -> {
        if (args.length == 0) {
            OptsCmd.onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        if (event.getMessage().getMentionedUsers().isEmpty()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention the user to whitelist from posting invites!").queue();
            return;
        }
        User toWhiteList = event.getMessage().getMentionedUsers().get(0);
        guildData.getLinkProtectionAllowedUsers().add(toWhiteList.getId());
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully whitelisted " + toWhiteList.getName() + "#" + toWhiteList.getDiscriminator() + " from posting discord invites.").queue();
    });
    registerOption("linkprotection:user:disallow", "Link-protection user blacklist", "Disallows an user to post invites.\n" + "You need to mention the user. (This is the default behaviour)", "Allows an user to post invites (This is the default behaviour)", (event, args) -> {
        if (args.length == 0) {
            OptsCmd.onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        if (event.getMessage().getMentionedUsers().isEmpty()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention the user to blacklist from posting invites!").queue();
            return;
        }
        User toBlackList = event.getMessage().getMentionedUsers().get(0);
        if (!guildData.getLinkProtectionAllowedUsers().contains(toBlackList.getId())) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "This user isn't in the invite posting whitelist!").queue();
            return;
        }
        guildData.getLinkProtectionAllowedUsers().remove(toBlackList.getId());
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully blacklisted " + toBlackList.getName() + "#" + toBlackList.getDiscriminator() + " from posting discord invites.").queue();
    });
    registerOption("imageboard:tags:blacklist:add", "Blacklist imageboard tags", "Blacklists the specified imageboard tag from being looked up.", "Blacklist imageboard tags", (event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify at least a tag to blacklist!").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        for (String tag : args) {
            guildData.getBlackListedImageTags().add(tag.toLowerCase());
        }
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully blacklisted " + String.join(" ,", args) + " from image search.").queue();
    });
    registerOption("imageboard:tags:blacklist:remove", "Un-blacklist imageboard tags", "Un-blacklist the specified imageboard tag from being looked up.", "Un-blacklist imageboard tags", (event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify at least a tag to un-blacklist!").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        for (String tag : args) {
            guildData.getBlackListedImageTags().remove(tag.toLowerCase());
        }
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully un-blacklisted " + String.join(" ,", args) + " from image search.").queue();
    });
}
Also used : Poll(net.kodehawa.mantarobot.commands.interaction.polls.Poll) GameLobby(net.kodehawa.mantarobot.commands.game.core.GameLobby) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Option(net.kodehawa.mantarobot.options.annotations.Option) Utils(net.kodehawa.mantarobot.utils.Utils) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) OptsCmd(net.kodehawa.mantarobot.commands.OptsCmd) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) Future(java.util.concurrent.Future) User(net.dv8tion.jda.core.entities.User) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Subscribe(com.google.common.eventbus.Subscribe) OptionRegistryEvent(net.kodehawa.mantarobot.options.event.OptionRegistryEvent) OptionHandler(net.kodehawa.mantarobot.options.core.OptionHandler) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) TextChannel(net.dv8tion.jda.core.entities.TextChannel) User(net.dv8tion.jda.core.entities.User) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Subscribe(com.google.common.eventbus.Subscribe)

Example 75 with Consumer

use of java.util.function.Consumer in project MantaroBot by Mantaro.

the class ModerationOptions method onRegistry.

@Subscribe
public void onRegistry(OptionRegistryEvent e) {
    registerOption("localblacklist:add", "Local Blacklist add", "Adds someone to the local blacklist.\n" + "You need to mention the user. You can mention multiple users.\n" + "**Example:** `~>opts localblacklist add @user1 @user2`", "Adds someone to the local blacklist.", (event, args) -> {
        List<User> mentioned = event.getMessage().getMentionedUsers();
        if (mentioned.isEmpty()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "**You need to specify the users to locally blacklist.**").queue();
            return;
        }
        if (mentioned.contains(event.getAuthor())) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Why are you trying to blacklist yourself?...").queue();
            return;
        }
        Guild guild = event.getGuild();
        if (mentioned.stream().anyMatch(u -> CommandPermission.ADMIN.test(guild.getMember(u)))) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "One (or more) of the users you're trying to blacklist are admins or Bot Commanders!").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(guild);
        GuildData guildData = dbGuild.getData();
        List<String> toBlackList = mentioned.stream().map(ISnowflake::getId).collect(Collectors.toList());
        String blacklisted = mentioned.stream().map(user -> user.getName() + "#" + user.getDiscriminator()).collect(Collectors.joining(","));
        guildData.getDisabledUsers().addAll(toBlackList);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Locally blacklisted users: **" + blacklisted + "**").queue();
    });
    registerOption("localblacklist:remove", "Local Blacklist remove", "Removes someone from the local blacklist.\n" + "You need to mention the user. You can mention multiple users.\n" + "**Example:** `~>opts localblacklist remove @user1 @user2`", "Removes someone from the local blacklist.", (event, args) -> {
        List<User> mentioned = event.getMessage().getMentionedUsers();
        if (mentioned.isEmpty()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "**You need to specify the users to locally blacklist.**").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        List<String> toUnBlackList = mentioned.stream().map(ISnowflake::getId).collect(Collectors.toList());
        String unBlackListed = mentioned.stream().map(user -> user.getName() + "#" + user.getDiscriminator()).collect(Collectors.joining(","));
        guildData.getDisabledUsers().removeAll(toUnBlackList);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Locally unblacklisted users: **" + unBlackListed + "**").queue();
    });
    // region logs
    // region enable
    registerOption("logs:enable", "Enable logs", "Enables logs. You need to use the channel name.\n" + "**Example:** `~>opts logs enable mod-logs`", "Enables logs.", (event, args) -> {
        if (args.length < 1) {
            onHelp(event);
            return;
        }
        String logChannel = args[0];
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Consumer<TextChannel> consumer = textChannel -> {
            guildData.setGuildLogChannel(textChannel.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(String.format(EmoteReference.MEGA + "Message logging has been enabled with parameters -> ``Channel #%s (%s)``", textChannel.getName(), textChannel.getId())).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, logChannel, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    registerOption("logs:exclude", "Exclude log channel.", "Excludes a channel from logging. You need to use the channel name, *not* the mention.\n" + "**Example:** `~>opts logs exclude staff`", "Excludes a channel from logging.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        if (args[0].equals("clearchannels")) {
            guildData.getLogExcludedChannels().clear();
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.OK + "Cleared log exceptions!").queue();
            return;
        }
        if (args[0].equals("remove")) {
            if (args.length < 2) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Incorrect argument length.").queue();
                return;
            }
            String channel = args[1];
            List<TextChannel> channels = event.getGuild().getTextChannelsByName(channel, true);
            if (channels.size() == 0) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "I didn't find a channel with that name!").queue();
            } else if (channels.size() == 1) {
                TextChannel ch = channels.get(0);
                guildData.getLogExcludedChannels().remove(ch.getId());
                dbGuild.saveAsync();
                event.getChannel().sendMessage(EmoteReference.OK + "Removed logs exception on channel: " + ch.getAsMention()).queue();
            } else {
                DiscordUtils.selectList(event, channels, ch -> String.format("%s (ID: %s)", ch.getName(), ch.getId()), s -> ((SimpleCommand) optsCmd).baseEmbed(event, "Select the Channel:").setDescription(s).build(), ch -> {
                    guildData.getLogExcludedChannels().remove(ch.getId());
                    dbGuild.saveAsync();
                    event.getChannel().sendMessage(EmoteReference.OK + "Removed logs exception on channel: " + ch.getAsMention()).queue();
                });
            }
            return;
        }
        String channel = args[0];
        List<TextChannel> channels = event.getGuild().getTextChannelsByName(channel, true);
        if (channels.size() == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I didn't find a channel with that name!").queue();
        } else if (channels.size() == 1) {
            TextChannel ch = channels.get(0);
            guildData.getLogExcludedChannels().add(ch.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.OK + "Added logs exception on channel: " + ch.getAsMention()).queue();
        } else {
            DiscordUtils.selectList(event, channels, ch -> String.format("%s (ID: %s)", ch.getName(), ch.getId()), s -> ((SimpleCommand) optsCmd).baseEmbed(event, "Select the Channel:").setDescription(s).build(), ch -> {
                guildData.getLogExcludedChannels().add(ch.getId());
                dbGuild.saveAsync();
                event.getChannel().sendMessage(EmoteReference.OK + "Added logs exception on channel: " + ch.getAsMention()).queue();
            });
        }
    });
    // endregion
    // region disable
    registerOption("logs:disable", "Disable logs", "Disables logs.\n" + "**Example:** `~>opts logs disable`", "Disables logs.", (event) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setGuildLogChannel(null);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.MEGA + "Message logging has been disabled.").queue();
    });
// endregion
// endregion
}
Also used : TextChannel(net.dv8tion.jda.core.entities.TextChannel) Option(net.kodehawa.mantarobot.options.annotations.Option) Utils(net.kodehawa.mantarobot.utils.Utils) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) Consumer(java.util.function.Consumer) Guild(net.dv8tion.jda.core.entities.Guild) List(java.util.List) User(net.dv8tion.jda.core.entities.User) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) OptionType(net.kodehawa.mantarobot.options.core.OptionType) OptionRegistryEvent(net.kodehawa.mantarobot.options.event.OptionRegistryEvent) OptionHandler(net.kodehawa.mantarobot.options.core.OptionHandler) OptsCmd.optsCmd(net.kodehawa.mantarobot.commands.OptsCmd.optsCmd) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) TextChannel(net.dv8tion.jda.core.entities.TextChannel) User(net.dv8tion.jda.core.entities.User) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Guild(net.dv8tion.jda.core.entities.Guild) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Consumer (java.util.function.Consumer)908 List (java.util.List)445 ArrayList (java.util.ArrayList)288 Test (org.junit.Test)250 Map (java.util.Map)228 IOException (java.io.IOException)223 Collectors (java.util.stream.Collectors)205 Collections (java.util.Collections)185 Arrays (java.util.Arrays)181 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)163 TimeUnit (java.util.concurrent.TimeUnit)157 HashMap (java.util.HashMap)152 Set (java.util.Set)149 AtomicBoolean (java.util.concurrent.atomic.AtomicBoolean)146 Optional (java.util.Optional)132 Collection (java.util.Collection)127 Function (java.util.function.Function)119 CountDownLatch (java.util.concurrent.CountDownLatch)116 File (java.io.File)112 AtomicReference (java.util.concurrent.atomic.AtomicReference)111