Search in sources :

Example 21 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class DictionaryCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    Request request = new Request.Builder().url(event.getConfig().getSearchWebserverUrl("dictionary") + "?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document document = Document.parse(response.body().string());
        if (!response.isSuccessful()) {
            StringBuilder builder = new StringBuilder("Command failed with status " + response.code());
            if (document.containsKey("message")) {
                builder.append(" with message `").append(document.getString("message")).append("`");
            }
            event.replyFailure(builder.toString()).queue();
            return;
        }
        List<Document> definitions = document.getList("definitions", Document.class);
        if (definitions.isEmpty()) {
            event.replyFailure("I could not find a definition for that word").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), definitions).setPerPage(1).setCustomFunction(page -> {
            EmbedBuilder embed = new EmbedBuilder();
            embed.setAuthor(StringUtility.title(query) + " (" + document.getString("type") + ")", document.getString("url"), null);
            embed.setTitle("Page " + page.getPage() + "/" + page.getMaxPage());
            embed.setFooter(PagedResult.DEFAULT_FOOTER_TEXT);
            page.forEach((data, index) -> {
                StringBuilder definition = new StringBuilder();
                for (Document node : data.getList("nodes", Document.class)) {
                    if (node.containsKey("url")) {
                        definition.append("[").append(node.getString("text")).append("](").append(node.getString("url")).append(")");
                    } else {
                        definition.append(node.getString("text"));
                    }
                }
                List<String> examples = data.getList("examples", String.class);
                embed.addField("Definition", definition + (examples.isEmpty() ? "" : "\n\n*" + String.join("*\n*", examples.subList(0, Math.min(3, examples.size()))) + "*"), false);
            });
            if (document.containsKey("pronunciation")) {
                embed.addField("Pronunciation", String.format("[Listen Here](%s)", document.getString("pronunciation")), false);
            }
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) List(java.util.List) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) StringUtility(com.sx4.bot.utility.StringUtility) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) List(java.util.List) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult)

Example 22 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class ColourCoverageCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "image url", endless = true, acceptEmpty = true) @ImageUrl String imageUrl) {
    Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("common-colour")).addQuery("image", imageUrl).build(event.getConfig().getImageWebserver());
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (!response.isSuccessful()) {
            ImageUtility.getErrorMessage(event.getTextChannel(), response.code(), response.body().string()).queue();
            return;
        }
        Document data = Document.parse(response.body().string());
        List<Document> colours = data.getList("colours", Document.class);
        long totalPixels = colours.stream().mapToInt(colour -> colour.getInteger("pixels")).sum();
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), colours).setAuthor("Colours", null, imageUrl).setIncreasedIndex(true).setSelect().setPerPage(15).setDisplayFunction(colour -> {
            int pixels = colour.getInteger("pixels");
            return "`#" + ColourUtility.toHexString(colour.getInteger("colour")) + "` - " + pixels + " pixel" + (pixels == 1 ? "" : "s") + " (" + NumberUtility.DEFAULT_DECIMAL_FORMAT.format((pixels / (double) totalPixels) * 100) + "%)";
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) Permission(net.dv8tion.jda.api.Permission) PagedResult(com.sx4.bot.paged.PagedResult) ModuleCategory(com.sx4.bot.category.ModuleCategory) ColourUtility(com.sx4.bot.utility.ColourUtility) List(java.util.List) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) Argument(com.jockie.bot.core.argument.Argument) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) List(java.util.List) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult)

Example 23 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class FormatterCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "arguments", nullDefault = true) String content) {
    FormatterManager manager = FormatterManager.getDefaultManager();
    String[] arguments = content == null ? new String[0] : content.split("\\.");
    Set<Class<?>> functionClasses = manager.getFunctions().keySet();
    Set<Class<?>> variableClasses = manager.getVariables().keySet();
    Set<Class<?>> classes = new HashSet<>();
    classes.addAll(functionClasses);
    classes.addAll(variableClasses);
    List<Class<?>> filteredClasses = classes.stream().filter(clazz -> arguments.length == 0 || arguments[0].equalsIgnoreCase(clazz.getSimpleName())).collect(Collectors.toList());
    if (filteredClasses.isEmpty()) {
        event.replyFailure("I could not find that formatter type").queue();
        return;
    }
    PagedResult<Class<?>> paged = new PagedResult<>(event.getBot(), filteredClasses).setPerPage(15).setAutoSelect(true).setDisplayFunction(Class::getSimpleName);
    paged.onSelect(select -> {
        Class<?> clazz = select.getSelected();
        for (int i = 1; i < arguments.length; i++) {
            String name = arguments[i];
            FormatterFunction<?> function = manager.getFunctions(clazz).stream().filter(f -> f.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
            FormatterVariable<?> variable = manager.getVariables(clazz).stream().filter(v -> v.getName().equalsIgnoreCase(name)).findFirst().orElse(null);
            boolean last = i == arguments.length - 1;
            MessageEmbed embed;
            if (function != null) {
                Method method = function.getMethod();
                if (!last) {
                    clazz = method.getReturnType();
                    continue;
                }
                embed = new EmbedBuilder().setDescription(function.getDescription()).setTitle(this.getFunctionString(function)).addField("Return Type", method.getReturnType().getSimpleName(), true).build();
            } else if (variable != null) {
                Class<?> returnType = variable.getReturnType();
                if (!last) {
                    clazz = returnType;
                    continue;
                }
                embed = new EmbedBuilder().setDescription(variable.getDescription()).setTitle(variable.getName()).addField("Return Type", returnType.getSimpleName(), true).build();
            } else {
                event.replyFailure("I could not find a variable or function named `" + name + "` on the type `" + clazz.getSimpleName() + "`").queue();
                return;
            }
            event.reply(embed).queue();
            return;
        }
        String variables = manager.getVariables(clazz).stream().map(FormatterVariable::getName).collect(Collectors.joining("\n"));
        String functions = manager.getFunctions(clazz).stream().map(this::getFunctionString).collect(Collectors.joining("\n"));
        EmbedBuilder embed = new EmbedBuilder().setTitle(clazz.getSimpleName()).addField("Functions", functions.isEmpty() ? "None" : functions, true).addField("Variables", variables.isEmpty() ? "None" : variables, true);
        event.reply(embed.build()).queue();
    });
    paged.execute(event);
}
Also used : Arrays(java.util.Arrays) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) Sx4Command(com.sx4.bot.core.Sx4Command) Set(java.util.Set) FormatterManager(com.sx4.bot.formatter.FormatterManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) FormatterFunction(com.sx4.bot.formatter.function.FormatterFunction) HashSet(java.util.HashSet) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Parameter(java.lang.reflect.Parameter) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Method(java.lang.reflect.Method) Argument(com.jockie.bot.core.argument.Argument) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Method(java.lang.reflect.Method) FormatterManager(com.sx4.bot.formatter.FormatterManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) HashSet(java.util.HashSet)

Example 24 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class AntiRegexCommand method list.

@Command(value = "list", description = "Lists the regexes which are active in this server")
@CommandId(110)
@Examples({ "anti regex list" })
public void list(Sx4CommandEvent event) {
    List<Document> regexes = event.getMongo().getRegexes(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("pattern")).into(new ArrayList<>());
    if (regexes.isEmpty()) {
        event.replyFailure("There are no regexes setup in this server").queue();
        return;
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), regexes).setPerPage(6).setCustomFunction(page -> {
        MessageBuilder builder = new MessageBuilder();
        EmbedBuilder embed = new EmbedBuilder();
        embed.setAuthor("Anti Regex", null, event.getGuild().getIconUrl());
        embed.setTitle("Page " + page.getPage() + "/" + page.getMaxPage());
        embed.setFooter(PagedResult.DEFAULT_FOOTER_TEXT, null);
        page.forEach((data, index) -> embed.addField(data.getObjectId("_id").toHexString(), "`" + data.getString("pattern") + "`", true));
        return builder.setEmbeds(embed.build());
    });
    paged.execute(event);
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 25 with PagedResult

use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.

the class BlacklistCommand method list.

@Command(value = "list", description = "Lists the commands roles/users blacklisted from using in a specific channel")
@CommandId(182)
@Examples({ "blacklist list", "blacklist list #channel" })
public void list(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true, endless = true) TextChannel channel) {
    List<TextChannel> channels = channel == null ? event.getGuild().getTextChannels() : List.of(channel);
    PagedResult<TextChannel> channelPaged = new PagedResult<>(event.getBot(), channels).setAutoSelect(true).setAuthor("Channels", null, event.getGuild().getIconUrl()).setDisplayFunction(TextChannel::getAsMention);
    channelPaged.onSelect(channelSelect -> {
        TextChannel selectedChannel = channelSelect.getSelected();
        Document blacklist = event.getMongo().getBlacklist(Filters.eq("channelId", selectedChannel.getIdLong()), Projections.include("holders"));
        if (blacklist == null) {
            event.replyFailure("Nothing is blacklisted in " + selectedChannel.getAsMention()).queue();
            return;
        }
        List<Document> holders = blacklist.getList("holders", Document.class).stream().filter(holder -> !holder.getList("blacklisted", Long.class, Collections.emptyList()).isEmpty()).sorted(Comparator.comparingInt(a -> a.getInteger("type"))).collect(Collectors.toList());
        if (holders.isEmpty()) {
            event.replyFailure("Nothing is blacklisted in " + selectedChannel.getAsMention()).queue();
            return;
        }
        PagedResult<Document> holderPaged = new PagedResult<>(event.getBot(), holders).setAuthor("Users/Roles", null, event.getGuild().getIconUrl()).setDisplayFunction(holder -> {
            long id = holder.getLong("id");
            int type = holder.getInteger("type");
            if (type == HolderType.ROLE.getType()) {
                Role role = event.getGuild().getRoleById(id);
                return role == null ? "Deleted Role (" + id + ")" : role.getAsMention();
            } else {
                User user = event.getShardManager().getUserById(id);
                return user == null ? "Unknown User (" + id + ")" : user.getAsTag();
            }
        });
        holderPaged.onSelect(holderSelect -> {
            Document holder = holderSelect.getSelected();
            List<Long> blacklisted = holder.getList("blacklisted", Long.class, Collections.emptyList());
            BitSet bitSet = BitSet.valueOf(blacklisted.stream().mapToLong(l -> l).toArray());
            List<Sx4Command> commands = event.getCommandListener().getAllCommands().stream().map(Sx4Command.class::cast).filter(command -> bitSet.get(command.getId())).collect(Collectors.toList());
            PagedResult<Sx4Command> commandPaged = new PagedResult<>(event.getBot(), commands).setAuthor("Blacklisted Commands", null, event.getGuild().getIconUrl()).setDisplayFunction(Sx4Command::getCommandTrigger).setSelect().setIndexed(false);
            commandPaged.execute(event);
        });
        holderPaged.execute(event);
    });
    channelPaged.execute(event);
}
Also used : HolderType(com.sx4.bot.entities.settings.HolderType) Document(org.bson.Document) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) java.util(java.util) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) Alternative(com.sx4.bot.entities.argument.Alternative) Examples(com.sx4.bot.annotations.command.Examples) IPermissionHolder(net.dv8tion.jda.api.entities.IPermissionHolder) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) com.mongodb.client.model(com.mongodb.client.model) Argument(com.jockie.bot.core.argument.Argument) User(net.dv8tion.jda.api.entities.User) Sx4Command(com.sx4.bot.core.Sx4Command) Document(org.bson.Document) Role(net.dv8tion.jda.api.entities.Role) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)54 PagedResult (com.sx4.bot.paged.PagedResult)50 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)43 Document (org.bson.Document)43 Command (com.jockie.bot.core.command.Command)41 CommandId (com.sx4.bot.annotations.command.CommandId)35 Examples (com.sx4.bot.annotations.command.Examples)33 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)32 ModuleCategory (com.sx4.bot.category.ModuleCategory)26 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)26 User (net.dv8tion.jda.api.entities.User)26 Argument (com.jockie.bot.core.argument.Argument)25 Bson (org.bson.conversions.Bson)23 Permission (net.dv8tion.jda.api.Permission)22 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)20 List (java.util.List)19 ArrayList (java.util.ArrayList)18 HttpCallback (com.sx4.bot.http.HttpCallback)15 Request (okhttp3.Request)15 Collectors (java.util.stream.Collectors)13