Search in sources :

Example 1 with ISnowflake

use of net.dv8tion.jda.core.entities.ISnowflake in project MantaroBot by Mantaro.

the class CustomCmds method custom.

@Subscribe
public void custom(CommandRegistry cr) {
    String any = "[\\d\\D]*?";
    cr.register("custom", new SimpleCommand(Category.UTILS) {

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length < 1) {
                onHelp(event);
                return;
            }
            String action = args[0];
            if (action.equals("list") || action.equals("ls")) {
                if (!MantaroCore.hasLoadedCompletely()) {
                    event.getChannel().sendMessage("The bot hasn't been fully booted up yet... custom commands will be available shortly!").queue();
                    return;
                }
                String filter = event.getGuild().getId() + ":";
                List<String> commands = customCommands.keySet().stream().filter(s -> s.startsWith(filter)).map(s -> s.substring(filter.length())).collect(Collectors.toList());
                EmbedBuilder builder = new EmbedBuilder().setAuthor("Commands for this guild", null, event.getGuild().getIconUrl()).setColor(event.getMember().getColor());
                builder.setDescription(commands.isEmpty() ? "There is nothing here, just dust." : checkString(forType(commands)));
                event.getChannel().sendMessage(builder.build()).queue();
                return;
            }
            if (action.equals("view")) {
                if (args.length < 2) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the command and the response number!").queue();
                    return;
                }
                String cmd = args[1];
                CustomCommand command = db().getCustomCommand(event.getGuild(), cmd);
                if (command == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There isn't a custom command with that name here!").queue();
                    return;
                }
                int number;
                try {
                    number = Integer.parseInt(args[2]) - 1;
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a number...").queue();
                    return;
                }
                if (command.getValues().size() < number) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "This commands has less responses than the number you specified...").queue();
                    return;
                }
                event.getChannel().sendMessage(String.format("**Response `%d` for custom command `%s`:** \n```\n%s```", (number + 1), command.getName(), command.getValues().get(number))).queue();
                return;
            }
            if (action.equals("raw")) {
                if (args.length < 2) {
                    onHelp(event);
                    return;
                }
                String cmd = args[1];
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
                if (custom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                Pair<String, Integer> pair = DiscordUtils.embedList(custom.getValues(), Object::toString);
                String pasted = null;
                if (pair.getRight() < custom.getValues().size()) {
                    AtomicInteger i = new AtomicInteger();
                    pasted = Utils.paste(custom.getValues().stream().map(s -> i.incrementAndGet() + s).collect(Collectors.joining("\n")));
                }
                EmbedBuilder embed = baseEmbed(event, "Command \"" + cmd + "\":").setDescription(pair.getLeft()).setFooter("(Showing " + pair.getRight() + " responses of " + custom.getValues().size() + ")", null);
                if (pasted != null && pasted.contains("hastebin.com")) {
                    embed.addField("Pasted content", pasted, false);
                }
                event.getChannel().sendMessage(embed.build()).queue();
                return;
            }
            if (db().getGuild(event.getGuild()).getData().isCustomAdminLock() && !CommandPermission.ADMIN.test(event.getMember())) {
                event.getChannel().sendMessage("This guild only accepts custom command creation, edits, imports and eval from administrators.").queue();
                return;
            }
            if (action.equals("clear")) {
                if (!CommandPermission.ADMIN.test(event.getMember())) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot do that, silly.").queue();
                    return;
                }
                List<CustomCommand> customCommands = db().getCustomCommands(event.getGuild());
                if (customCommands.isEmpty()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There's no Custom Commands registered in this Guild, just dust.").queue();
                }
                int size = customCommands.size();
                customCommands.forEach(CustomCommand::deleteAsync);
                customCommands.forEach(c -> CustomCmds.customCommands.remove(c.getId()));
                event.getChannel().sendMessage(EmoteReference.PENCIL + "Cleared **" + size + " Custom Commands**!").queue();
                return;
            }
            if (args.length < 2) {
                onHelp(event);
                return;
            }
            String cmd = args[1];
            if (action.equals("make")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                List<String> responses = new ArrayList<>();
                boolean created = InteractiveOperations.create(event.getChannel(), 60, e -> {
                    if (!e.getAuthor().equals(event.getAuthor()))
                        return Operation.IGNORED;
                    String c = e.getMessage().getContentRaw();
                    if (!c.startsWith("&"))
                        return Operation.IGNORED;
                    c = c.substring(1);
                    if (c.startsWith("~>cancel") || c.startsWith("~>stop")) {
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "Command Creation canceled.").queue();
                        return Operation.COMPLETED;
                    }
                    if (c.startsWith("~>save")) {
                        String arg = c.substring(6).trim();
                        String saveTo = !arg.isEmpty() ? arg : cmd;
                        if (!NAME_PATTERN.matcher(cmd).matches()) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                            return Operation.RESET_TIMEOUT;
                        }
                        if (cmd.length() >= 100) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "Name is too long.").queue();
                            return Operation.RESET_TIMEOUT;
                        }
                        if (DefaultCommandProcessor.REGISTRY.commands().containsKey(saveTo) && !DefaultCommandProcessor.REGISTRY.commands().get(saveTo).equals(customCommand)) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                            return Operation.RESET_TIMEOUT;
                        }
                        if (responses.isEmpty()) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "No responses were added. Stopping creation without saving...").queue();
                        } else {
                            CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmd, responses);
                            // save at DB
                            custom.saveAsync();
                            // reflect at local
                            customCommands.put(custom.getId(), custom.getValues());
                            // add mini-hack
                            DefaultCommandProcessor.REGISTRY.commands().put(cmd, customCommand);
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Saved to command ``" + cmd + "``!").queue();
                            // easter egg :D
                            TextChannelGround.of(event).dropItemWithChance(8, 2);
                        }
                        return Operation.COMPLETED;
                    }
                    responses.add(c.replace("@everyone", "[nice meme]").replace("@here", "[you tried]"));
                    e.getMessage().addReaction(EmoteReference.CORRECT.getUnicode()).queue();
                    return Operation.RESET_TIMEOUT;
                }) != null;
                if (created) {
                    event.getChannel().sendMessage(EmoteReference.PENCIL + "Started **\"Creation of Custom Command ``" + cmd + "``\"**!\nSend ``&~>stop`` to stop creation **without saving**.\nSend ``&~>save`` to stop creation an **save the new Command**. Send any text beginning with ``&`` to be added to the Command Responses.\nThis Interactive Operation ends without saving after 60 seconds of inactivity.").queue();
                } else {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There's already an Interactive Operation happening on this channel.").queue();
                }
                return;
            }
            if (action.equals("eval")) {
                try {
                    runCustom(content.replace("eval ", ""), event);
                } catch (Exception e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There was an error while evaluating your command!" + (e.getMessage() == null ? "" : " (E: " + e.getMessage() + ")")).queue();
                }
                return;
            }
            if (action.equals("remove") || action.equals("rm")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
                if (custom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                // delete at DB
                custom.deleteAsync();
                // reflect at local
                customCommands.remove(custom.getId());
                // clear commands if none
                if (customCommands.keySet().stream().noneMatch(s -> s.endsWith(":" + cmd)))
                    DefaultCommandProcessor.REGISTRY.commands().remove(cmd);
                event.getChannel().sendMessage(EmoteReference.PENCIL + "Removed Custom Command ``" + cmd + "``!").queue();
                return;
            }
            if (action.equals("import")) {
                if (!NAME_WILDCARD_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                Map<String, Guild> mapped = MantaroBot.getInstance().getMutualGuilds(event.getAuthor()).stream().collect(Collectors.toMap(ISnowflake::getId, g -> g));
                List<Pair<Guild, CustomCommand>> filtered = MantaroData.db().getCustomCommandsByName(("*" + cmd + "*").replace("*", any)).stream().map(customCommand -> {
                    Guild guild = mapped.get(customCommand.getGuildId());
                    return guild == null ? null : Pair.of(guild, customCommand);
                }).filter(Objects::nonNull).collect(Collectors.toList());
                if (filtered.size() == 0) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There are no custom commands matching your search query.").queue();
                    return;
                }
                DiscordUtils.selectList(event, filtered, pair -> "``" + pair.getValue().getName() + "`` - Guild: ``" + pair.getKey() + "``", s -> baseEmbed(event, "Select the Command:").setDescription(s).setFooter("(You can only select custom commands from guilds that you are a member of)", null).build(), pair -> {
                    String cmdName = pair.getValue().getName();
                    List<String> responses = pair.getValue().getValues();
                    CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmdName, responses);
                    // save at DB
                    custom.saveAsync();
                    // reflect at local
                    customCommands.put(custom.getId(), custom.getValues());
                    event.getChannel().sendMessage(String.format("Imported custom command ``%s`` from guild `%s` with responses ``%s``", cmdName, pair.getKey().getName(), String.join("``, ``", responses))).queue();
                    // easter egg :D
                    TextChannelGround.of(event).dropItemWithChance(8, 2);
                });
                return;
            }
            if (args.length < 3) {
                onHelp(event);
                return;
            }
            String value = args[2];
            if (action.equals("edit")) {
                CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
                if (custom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                String[] vals = StringUtils.splitArgs(value, 2);
                int where;
                try {
                    where = Math.abs(Integer.parseInt(vals[0]));
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a correct number to change!").queue();
                    return;
                }
                List<String> values = custom.getValues();
                if (where - 1 > values.size()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot edit a non-existent index!").queue();
                    return;
                }
                if (vals[1].isEmpty()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot edit to an empty response!").queue();
                    return;
                }
                custom.getValues().set(where - 1, vals[1]);
                custom.saveAsync();
                customCommands.put(custom.getId(), custom.getValues());
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Edited response **#" + where + "** of the command `" + custom.getName() + "` correctly!").queue();
                return;
            }
            if (action.equals("rename")) {
                if (!NAME_PATTERN.matcher(cmd).matches() || !NAME_PATTERN.matcher(value).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                if (DefaultCommandProcessor.REGISTRY.commands().containsKey(value) && !DefaultCommandProcessor.REGISTRY.commands().get(value).equals(customCommand)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                    return;
                }
                CustomCommand oldCustom = db().getCustomCommand(event.getGuild(), cmd);
                if (oldCustom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                CustomCommand newCustom = CustomCommand.of(event.getGuild().getId(), value, oldCustom.getValues());
                // change at DB
                oldCustom.deleteAsync();
                newCustom.saveAsync();
                // reflect at local
                customCommands.remove(oldCustom.getId());
                customCommands.put(newCustom.getId(), newCustom.getValues());
                // add mini-hack
                DefaultCommandProcessor.REGISTRY.commands().put(value, customCommand);
                // clear commands if none
                if (customCommands.keySet().stream().noneMatch(s -> s.endsWith(":" + cmd)))
                    DefaultCommandProcessor.REGISTRY.commands().remove(cmd);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Renamed command ``" + cmd + "`` to ``" + value + "``!").queue();
                // easter egg :D
                TextChannelGround.of(event).dropItemWithChance(8, 2);
                return;
            }
            if (action.equals("add") || action.equals("new")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                if (cmd.length() >= 100) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Name is too long.").queue();
                    return;
                }
                if (DefaultCommandProcessor.REGISTRY.commands().containsKey(cmd) && !DefaultCommandProcessor.REGISTRY.commands().get(cmd).equals(customCommand)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                    return;
                }
                CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmd, Collections.singletonList(value.replace("@everyone", "[nice meme]").replace("@here", "[you tried]")));
                if (action.equals("add")) {
                    CustomCommand c = db().getCustomCommand(event, cmd);
                    if (c != null)
                        custom.getValues().addAll(c.getValues());
                }
                // save at DB
                custom.saveAsync();
                // reflect at local
                customCommands.put(custom.getId(), custom.getValues());
                // add mini-hack
                DefaultCommandProcessor.REGISTRY.commands().put(cmd, customCommand);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Saved to command ``" + cmd + "``!").queue();
                // easter egg :D
                TextChannelGround.of(event).dropItemWithChance(8, 2);
                return;
            }
            onHelp(event);
        }

        @Override
        public String[] splitArgs(String content) {
            return SPLIT_PATTERN.split(content, 3);
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "CustomCommand Manager").setDescription("**Manages the Custom Commands of the Guild.**").addField("Guide", "https://github.com/Mantaro/MantaroBot/wiki/Custom-Commands", false).addField("Usage:", "`~>custom` - Shows this help\n" + "`~>custom <list|ls>` - **List all commands. If detailed is supplied, it prints the responses of each command.**\n" + "`~>custom clear` - **Remove all Custom Commands from this Guild. (ADMIN-ONLY)**\n" + "`~>custom add <name> <response>` - **Creates or adds the response provided to a custom command.**\n" + "`~>custom make <name>` - **Starts a Interactive Operation to create a command with the specified name.**\n" + "`~>custom <remove|rm> <name>` - **Removes a command with an specific name.**\n" + "`~>custom import <search>` - **Imports a command from another guild you're in.**\n" + "`~>custom eval <response>` - **Tests how a custom command response will look**\n" + "`~>custom edit <name> <response number> <new content>` - **Edits one response of the specified command**\n" + "`~>custom view <name> <response number>` - **Views the content of one response**\n" + "`~>custom rename <previous name> <new name>` - **Renames a custom command**", false).addField("Considerations", "If you wish to dissallow normal people from making custom commands, run `~>opts admincustom true`", false).build();
        }
    });
}
Also used : CustomCommandStatsManager(net.kodehawa.mantarobot.commands.info.stats.manager.CustomCommandStatsManager) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) DefaultCommandProcessor(net.kodehawa.mantarobot.core.processor.DefaultCommandProcessor) PostLoadEvent(net.kodehawa.mantarobot.core.listeners.events.PostLoadEvent) StringUtils(net.kodehawa.mantarobot.utils.StringUtils) Async(br.com.brjdevs.java.utils.async.Async) URL(java.net.URL) Utils(net.kodehawa.mantarobot.utils.Utils) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) CategoryStatsManager(net.kodehawa.mantarobot.commands.info.stats.manager.CategoryStatsManager) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Pair(org.apache.commons.lang3.tuple.Pair) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) Subscribe(com.google.common.eventbus.Subscribe) CommandStatsManager(net.kodehawa.mantarobot.commands.info.stats.manager.CommandStatsManager) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) MantaroCore(net.kodehawa.mantarobot.core.MantaroCore) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) CustomCommand(net.kodehawa.mantarobot.db.entities.CustomCommand) MantaroData.db(net.kodehawa.mantarobot.data.MantaroData.db) ConditionalCustoms(net.kodehawa.mantarobot.commands.custom.ConditionalCustoms) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) AbstractCommand(net.kodehawa.mantarobot.core.modules.commands.base.AbstractCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Mapifier.map(net.kodehawa.mantarobot.commands.custom.Mapifier.map) GsonDataManager(net.kodehawa.mantarobot.utils.data.GsonDataManager) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Guild(net.dv8tion.jda.core.entities.Guild) Slf4j(lombok.extern.slf4j.Slf4j) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) Mapifier.dynamicResolve(net.kodehawa.mantarobot.commands.custom.Mapifier.dynamicResolve) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) EmbedJSON(net.kodehawa.mantarobot.commands.custom.EmbedJSON) MantaroData(net.kodehawa.mantarobot.data.MantaroData) HelpUtils.forType(net.kodehawa.mantarobot.commands.info.HelpUtils.forType) Pattern(java.util.regex.Pattern) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Guild(net.dv8tion.jda.core.entities.Guild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) CustomCommand(net.kodehawa.mantarobot.db.entities.CustomCommand) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Pair(org.apache.commons.lang3.tuple.Pair) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) Subscribe(com.google.common.eventbus.Subscribe)

Example 2 with ISnowflake

use of net.dv8tion.jda.core.entities.ISnowflake 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 3 with ISnowflake

use of net.dv8tion.jda.core.entities.ISnowflake 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 4 with ISnowflake

use of net.dv8tion.jda.core.entities.ISnowflake 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)

Example 5 with ISnowflake

use of net.dv8tion.jda.core.entities.ISnowflake in project pokeraidbot by magnusmickelsson.

the class InstallEmotesCommand method createEmote.

// Code taken from JDA's GuildController since they have a limitation that bot accounts can't upload emotes.
private void createEmote(String iconName, CommandEvent commandEvent, Icon icon, Role... roles) {
    JSONObject body = new JSONObject();
    body.put("name", iconName);
    body.put("image", icon.getEncoding());
    if (// making sure none of the provided roles are null before mapping them to the snowflake id
    roles.length > 0) {
        body.put("roles", Stream.of(roles).filter(Objects::nonNull).map(ISnowflake::getId).collect(Collectors.toSet()));
    }
    GuildImpl guild = (GuildImpl) commandEvent.getGuild();
    JDA jda = commandEvent.getJDA();
    Route.CompiledRoute route = Route.Emotes.CREATE_EMOTE.compile(guild.getId());
    AuditableRestAction<Emote> action = new AuditableRestAction<Emote>(jda, route, body) {

        @Override
        protected void handleResponse(Response response, Request<Emote> request) {
            if (response.isOk()) {
                JSONObject obj = response.getObject();
                final long id = obj.getLong("id");
                String name = obj.getString("name");
                EmoteImpl emote = new EmoteImpl(id, guild).setName(name);
                // managed is false by default, should always be false for emotes created by client accounts.
                JSONArray rolesArr = obj.getJSONArray("roles");
                Set<Role> roleSet = emote.getRoleSet();
                for (int i = 0; i < rolesArr.length(); i++) {
                    roleSet.add(guild.getRoleById(rolesArr.getString(i)));
                }
                // put emote into cache
                guild.getEmoteMap().put(id, emote);
                request.onSuccess(emote);
            } else {
                request.onFailure(response);
                throw new RuntimeException("Couldn't install emojis. " + "Make sure that pokeraidbot has access to manage emojis.");
            }
        }
    };
    action.queue();
}
Also used : AuditableRestAction(net.dv8tion.jda.core.requests.restaction.AuditableRestAction) JDA(net.dv8tion.jda.core.JDA) Emote(net.dv8tion.jda.core.entities.Emote) Request(net.dv8tion.jda.core.requests.Request) JSONArray(org.json.JSONArray) Response(net.dv8tion.jda.core.requests.Response) Role(net.dv8tion.jda.core.entities.Role) GuildImpl(net.dv8tion.jda.core.entities.impl.GuildImpl) EmoteImpl(net.dv8tion.jda.core.entities.impl.EmoteImpl) JSONObject(org.json.JSONObject) Route(net.dv8tion.jda.core.requests.Route) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake)

Aggregations

ISnowflake (net.dv8tion.jda.core.entities.ISnowflake)5 Subscribe (com.google.common.eventbus.Subscribe)4 Collectors (java.util.stream.Collectors)4 MantaroData (net.kodehawa.mantarobot.data.MantaroData)4 Utils (net.kodehawa.mantarobot.utils.Utils)4 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)4 List (java.util.List)3 Consumer (java.util.function.Consumer)3 TextChannel (net.dv8tion.jda.core.entities.TextChannel)3 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)3 GuildData (net.kodehawa.mantarobot.db.entities.helpers.GuildData)3 Option (net.kodehawa.mantarobot.options.annotations.Option)3 OptionHandler (net.kodehawa.mantarobot.options.core.OptionHandler)3 OptionRegistryEvent (net.kodehawa.mantarobot.options.event.OptionRegistryEvent)3 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)2 Slf4j (lombok.extern.slf4j.Slf4j)2 Guild (net.dv8tion.jda.core.entities.Guild)2 Role (net.dv8tion.jda.core.entities.Role)2 User (net.dv8tion.jda.core.entities.User)2 InteractiveOperations (net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations)2