Search in sources :

Example 1 with Sx4Command

use of com.sx4.bot.core.Sx4Command in project Sx4 by sx4-discord-bot.

the class HelpCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "command | module", endless = true, nullDefault = true) String commandName) {
    boolean embed = !event.isFromGuild() || event.getGuild().getSelfMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_EMBED_LINKS);
    if (commandName == null) {
        List<Sx4Category> categories = Arrays.stream(ModuleCategory.ALL_ARRAY).filter(category -> !category.getCommands(event.isAuthorDeveloper()).isEmpty()).collect(Collectors.toList());
        PagedResult<Sx4Category> paged = new PagedResult<>(event.getBot(), categories).setPerPage(categories.size()).setSelect(SelectType.OBJECT).setSelectablePredicate((content, category) -> category.getName().equalsIgnoreCase(content) || Arrays.stream(category.getAliases()).anyMatch(content::equalsIgnoreCase)).setCustomFunction(page -> {
            MessageBuilder builder = new MessageBuilder();
            EmbedBuilder embedBuilder = new EmbedBuilder();
            embedBuilder.setAuthor("Help", null, event.getSelfUser().getEffectiveAvatarUrl());
            embedBuilder.setFooter(event.getPrefix() + "help <module> or respond below with a name of a module", event.getAuthor().getEffectiveAvatarUrl());
            embedBuilder.setDescription("All commands are put in a set category also known as a module, use `" + event.getPrefix() + "help <module>` on the module of your choice, The bot will then " + "list all the commands in that module. If you need further help feel free to join the [support server](https://discord.gg/PqJNcfB).");
            embedBuilder.addField("Modules", "`" + categories.stream().map(Sx4Category::getName).collect(Collectors.joining("`, `")) + "`", false);
            return builder.setEmbeds(embedBuilder.build());
        });
        paged.onSelect(select -> {
            Sx4Category category = select.getSelected();
            List<Sx4Command> categoryCommands = category.getCommands(event.isAuthorDeveloper()).stream().map(Sx4Command.class::cast).sorted(Comparator.comparing(Sx4Command::getCommandTrigger)).collect(Collectors.toList());
            PagedResult<Sx4Command> categoryPaged = HelpUtility.getCommandsPaged(event.getBot(), categoryCommands).setAuthor(category.getName(), null, event.getAuthor().getEffectiveAvatarUrl());
            categoryPaged.onSelect(categorySelect -> event.reply(HelpUtility.getHelpMessage(categorySelect.getSelected(), embed)).queue());
            categoryPaged.execute(event);
        });
        paged.execute(event);
    } else {
        Sx4Category category = SearchUtility.getModule(commandName);
        List<Sx4Command> commands = SearchUtility.getCommands(event.getCommandListener(), commandName, event.isAuthorDeveloper());
        if (category != null) {
            List<Sx4Command> categoryCommands = category.getCommands(event.isAuthorDeveloper()).stream().map(Sx4Command.class::cast).sorted(Comparator.comparing(Sx4Command::getCommandTrigger)).collect(Collectors.toList());
            PagedResult<Sx4Command> paged = HelpUtility.getCommandsPaged(event.getBot(), categoryCommands).setAuthor(category.getName(), null, event.getAuthor().getEffectiveAvatarUrl());
            paged.onSelect(select -> event.reply(HelpUtility.getHelpMessage(select.getSelected(), embed)).queue());
            paged.execute(event);
        } else if (!commands.isEmpty()) {
            PagedResult<Sx4Command> paged = new PagedResult<>(event.getBot(), commands).setAuthor(commandName, null, event.getAuthor().getEffectiveAvatarUrl()).setAutoSelect(true).setPerPage(15).setSelectablePredicate((content, command) -> command.getCommandTrigger().equals(content)).setDisplayFunction(Sx4Command::getUsage);
            paged.onSelect(select -> event.reply(HelpUtility.getHelpMessage(select.getSelected(), embed)).queue());
            paged.execute(event);
        } else {
            event.replyFailure("I could not find that command/module").queue();
        }
    }
}
Also used : Arrays(java.util.Arrays) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) SearchUtility(com.sx4.bot.utility.SearchUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) HelpUtility(com.sx4.bot.utility.HelpUtility) Sx4Category(com.sx4.bot.core.Sx4Category) List(java.util.List) SelectType(com.sx4.bot.paged.PagedResult.SelectType) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Comparator(java.util.Comparator) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Sx4Command(com.sx4.bot.core.Sx4Command) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4Category(com.sx4.bot.core.Sx4Category) PagedResult(com.sx4.bot.paged.PagedResult)

Example 2 with Sx4Command

use of com.sx4.bot.core.Sx4Command in project Sx4 by sx4-discord-bot.

the class CommandStatsCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Option(value = "group", description = "What to group the data by, default is command") GroupType group, @Option(value = "command", description = "Provide a command filter") Sx4Command command, @Option(value = "server", aliases = { "guild" }, description = "Provide a server filter") Guild guild, @Option(value = "channel", description = "Provide a channel filter") TextChannel channel, @Option(value = "user", description = "Provide a user id argument") long userId, @Option(value = "from", description = "When the data should start in epoch seconds") long from, @Option(value = "to", description = "When the data should end in epoch seconds") long to) {
    List<Bson> filters = new ArrayList<>();
    if (command != null) {
        filters.add(Filters.eq("command.id", command.getId()));
    }
    if (group == GroupType.CHANNEL) {
        filters.add(Filters.eq("guildId", event.getGuild().getIdLong()));
    } else if (guild != null) {
        filters.add(Filters.eq("guildId", guild.getIdLong()));
    }
    if (userId != 0L) {
        filters.add(Filters.eq("authorId", userId));
    }
    if (channel != null) {
        filters.add(Filters.eq("channelId", channel.getIdLong()));
    }
    if (from != 0L) {
        filters.add(Filters.gte("_id", new ObjectId(Date.from(Instant.ofEpochSecond(from)))));
    }
    if (to != 0L) {
        filters.add(Filters.lte("_id", new ObjectId(Date.from(Instant.ofEpochSecond(to)))));
    }
    List<Bson> pipeline = List.of(Aggregates.match(filters.isEmpty() ? Filters.empty() : Filters.and(filters)), Aggregates.group("$" + (group == null ? GroupType.COMMAND : group).getField(), Accumulators.sum("count", 1L)), Aggregates.sort(Sorts.descending("count")));
    event.getMongo().aggregateCommands(pipeline).whenComplete((commands, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (commands.isEmpty()) {
            event.replyFailure("No data was found with those filters").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), commands).setIndexed(false).setSelect().setAuthor("Command Stats", null, event.getSelfUser().getEffectiveAvatarUrl()).setDisplayFunction(data -> {
            String prefix = null;
            if (group == null || group == GroupType.COMMAND) {
                prefix = "`" + data.getString("_id") + "`";
            } else if (group == GroupType.CHANNEL) {
                long id = data.getLong("_id");
                TextChannel textChannel = event.getGuild().getTextChannelById(id);
                prefix = textChannel == null ? "#deleted-channel (" + id + ")" : textChannel.getAsMention();
            } else if (group == GroupType.USER) {
                long id = data.getLong("_id");
                User user = event.getShardManager().getUserById(id);
                prefix = "`" + (user == null ? "Anonymous#0000 (" + id + ")" : MarkdownSanitizer.escape(user.getAsTag())) + "`";
            } else if (group == GroupType.SERVER) {
                Long id = data.getLong("_id");
                if (id == null) {
                    prefix = "`Private Messages`";
                } else {
                    Guild guildGroup = event.getShardManager().getGuildById(id);
                    prefix = "`" + (guildGroup == null ? "Unknown Server (" + id + ")" : MarkdownSanitizer.escape(guildGroup.getName())) + "`";
                }
            }
            long count = data.getLong("count");
            return (prefix == null ? "Unknown" : prefix) + " - " + String.format("%,d", count) + " use" + (count == 1 ? "" : "s");
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) ObjectId(org.bson.types.ObjectId) ArrayList(java.util.ArrayList) Document(org.bson.Document) Guild(net.dv8tion.jda.api.entities.Guild) Bson(org.bson.conversions.Bson) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult)

Example 3 with Sx4Command

use of com.sx4.bot.core.Sx4Command 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)

Example 4 with Sx4Command

use of com.sx4.bot.core.Sx4Command in project Sx4 by sx4-discord-bot.

the class SearchUtility method getCommandOrModule.

public static List<Sx4Command> getCommandOrModule(CommandListener commandListener, String query) {
    Sx4Command command = SearchUtility.getCommand(commandListener, query, false);
    Sx4Category category = SearchUtility.getModule(query);
    if (category != null) {
        return category.getCommands().stream().map(Sx4Command.class::cast).collect(Collectors.toList());
    } else if (command != null) {
        return List.of(command);
    } else {
        return null;
    }
}
Also used : Sx4Command(com.sx4.bot.core.Sx4Command) Sx4Category(com.sx4.bot.core.Sx4Category)

Example 5 with Sx4Command

use of com.sx4.bot.core.Sx4Command in project Sx4 by sx4-discord-bot.

the class BlacklistCommand method remove.

@Command(value = "remove", description = "Remove a role/user from being blacklisted from a specified command/module in a channel")
@CommandId(180)
@Examples({ "blacklist remove #general @Shea#6653 fish", "blacklist remove #bots @Members ban" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void remove(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "user | role") IPermissionHolder holder, @Argument(value = "command | module", endless = true) List<Sx4Command> commands) {
    List<TextChannel> channels = channel == null ? event.getGuild().getTextChannels() : List.of(channel);
    boolean role = holder instanceof Role;
    BitSet bitSet = new BitSet();
    commands.stream().map(Sx4Command::getId).forEach(bitSet::set);
    List<Long> longArray = Arrays.stream(bitSet.toLongArray()).boxed().collect(Collectors.toList());
    List<Bson> update = List.of(Operators.set("holders", Operators.let(new Document("holder", Operators.filter("$holders", Operators.eq("$$this.id", holder.getIdLong()))), Operators.cond(Operators.or(Operators.extinct("$holders"), Operators.isEmpty("$$holder")), "$holders", Operators.concatArrays(Operators.filter("$holders", Operators.ne("$$this.id", holder.getIdLong())), Operators.let(new Document("result", Operators.bitSetAndNot(Operators.ifNull(Operators.first(Operators.map("$$holder", "$$this.blacklisted")), Collections.EMPTY_LIST), longArray)), Operators.cond(Operators.and(Operators.isEmpty(Operators.ifNull(Operators.first(Operators.map("$$holder", "$$this.whitelisted")), Collections.EMPTY_LIST)), Operators.bitSetIsEmpty("$$result")), Collections.EMPTY_LIST, List.of(Operators.cond(Operators.bitSetIsEmpty("$$result"), Operators.removeObject(Operators.first("$$holder"), "blacklisted"), Operators.mergeObjects(Operators.first("$$holder"), new Document("blacklisted", "$$result")))))))))));
    List<WriteModel<Document>> bulkData = channels.stream().map(textChannel -> new UpdateOneModel<Document>(Filters.eq("channelId", textChannel.getIdLong()), update, new UpdateOptions())).collect(Collectors.toList());
    event.getMongo().bulkWriteBlacklists(bulkData).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure((commands.size() == 1 ? "That command is" : "Those commands are") + " not blacklisted for that " + (role ? "role" : "user") + " in those channels").queue();
            return;
        }
        event.replySuccess((commands.size() == 1 ? "That command is" : "Those commands are") + " no longer blacklisted for that " + (role ? "role" : "user") + " in **" + result.getModifiedCount() + "** channel" + (result.getModifiedCount() == 1 ? "" : "s")).queue();
    });
}
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) Document(org.bson.Document) Bson(org.bson.conversions.Bson) Role(net.dv8tion.jda.api.entities.Role) TextChannel(net.dv8tion.jda.api.entities.TextChannel) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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)10 Argument (com.jockie.bot.core.argument.Argument)8 ModuleCategory (com.sx4.bot.category.ModuleCategory)8 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)8 PagedResult (com.sx4.bot.paged.PagedResult)8 Permission (net.dv8tion.jda.api.Permission)8 Collectors (java.util.stream.Collectors)7 TextChannel (net.dv8tion.jda.api.entities.TextChannel)7 User (net.dv8tion.jda.api.entities.User)7 Document (org.bson.Document)7 Bson (org.bson.conversions.Bson)7 Command (com.jockie.bot.core.command.Command)6 com.mongodb.client.model (com.mongodb.client.model)6 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)6 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)6 CommandId (com.sx4.bot.annotations.command.CommandId)6 Examples (com.sx4.bot.annotations.command.Examples)6 Operators (com.sx4.bot.database.mongo.model.Operators)6 Alternative (com.sx4.bot.entities.argument.Alternative)6 HolderType (com.sx4.bot.entities.settings.HolderType)6