Search in sources :

Example 1 with BotPermissions

use of com.sx4.bot.annotations.command.BotPermissions in project Sx4 by sx4-discord-bot.

the class LeaderboardCommand method networth.

@Command(value = "networth", description = "View the leaderboard for the networth of users")
@CommandId(370)
@Examples({ "leaderboard networth", "leaderboard networth --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void networth(Sx4CommandEvent event, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
    List<Bson> userPipeline = List.of(Aggregates.project(Projections.computed("total", "$economy.balance")), Aggregates.match(Filters.and(Filters.exists("total"), Filters.ne("total", 0))));
    List<Bson> pipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("_id", "$userId"), Projections.computed("total", Operators.cond(Operators.exists("$item.durability"), Operators.toLong(Operators.multiply(Operators.divide("$item.price", "$item.maxDurability"), "$item.durability")), Operators.multiply("$item.price", "$amount"))))), Aggregates.match(Filters.and(Filters.ne("_id", event.getJDA().getSelfUser().getIdLong()), Filters.ne("amount", 0))), Aggregates.unionWith("users", userPipeline), Aggregates.group("$_id", Accumulators.sum("total", "$total")), Aggregates.sort(Sorts.descending("total")));
    event.getMongo().aggregateItems(pipeline).whenCompleteAsync((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        List<Map.Entry<User, Long>> users = new ArrayList<>();
        AtomicInteger userIndex = new AtomicInteger(-1);
        int i = 0;
        for (Document data : documents) {
            User user = event.getShardManager().getUserById(data.getLong("_id"));
            if (user == null) {
                continue;
            }
            if (!event.getGuild().isMember(user) && guild) {
                continue;
            }
            i++;
            users.add(Map.entry(user, data.getLong("total")));
            if (user.getIdLong() == event.getAuthor().getIdLong()) {
                userIndex.set(i);
            }
        }
        if (users.isEmpty()) {
            event.replyFailure("There are no users which fit into this leaderboard").queue();
            return;
        }
        PagedResult<Map.Entry<User, Long>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
            int rank = userIndex.get();
            EmbedBuilder embed = new EmbedBuilder().setTitle("Networth Leaderboard").setFooter(event.getAuthor().getName() + "'s Rank: " + (rank == -1 ? "N/A" : NumberUtility.getSuffixed(rank)) + " | Page " + page.getPage() + "/" + page.getMaxPage(), event.getAuthor().getEffectiveAvatarUrl());
            page.forEach((entry, index) -> embed.appendDescription(String.format("%d. `%s` - $%,d\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue())));
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PagedResult(com.sx4.bot.paged.PagedResult) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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 2 with BotPermissions

use of com.sx4.bot.annotations.command.BotPermissions in project Sx4 by sx4-discord-bot.

the class LeaderboardCommand method items.

@Command(value = "items", description = "View the leaderboard for a specific items count of users")
@CommandId(372)
@Examples({ "leaderboard items", "leaderboard items Shoe", "leaderboard items Diamond --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void items(Sx4CommandEvent event, @Argument(value = "item", endless = true, nullDefault = true) Item item, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
    Bson filter = Filters.and(Filters.ne("_id", event.getJDA().getSelfUser().getIdLong()), Filters.ne("amount", 0));
    if (item != null) {
        filter = Filters.and(filter, Filters.eq("item.id", item.getId()));
    }
    List<Bson> pipeline = List.of(Aggregates.project(Projections.include("amount", "userId", "item.id")), Aggregates.match(filter), Aggregates.group("$userId", Accumulators.sum("amount", "$amount")), Aggregates.sort(Sorts.descending("amount")));
    event.getMongo().aggregateItems(pipeline).whenCompleteAsync((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        List<Map.Entry<User, Long>> users = new ArrayList<>();
        AtomicInteger userIndex = new AtomicInteger(-1);
        int i = 0;
        for (Document data : documents) {
            User user = event.getShardManager().getUserById(data.getLong("_id"));
            if (user == null) {
                continue;
            }
            if (!event.getGuild().isMember(user) && guild) {
                continue;
            }
            i++;
            users.add(Map.entry(user, data.getLong("amount")));
            if (user.getIdLong() == event.getAuthor().getIdLong()) {
                userIndex.set(i);
            }
        }
        if (users.isEmpty()) {
            event.replyFailure("There are no users which fit into this leaderboard").queue();
            return;
        }
        PagedResult<Map.Entry<User, Long>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
            int rank = userIndex.get();
            EmbedBuilder embed = new EmbedBuilder().setTitle((item == null ? "All Items" : item.getName()) + " Leaderboard").setFooter(event.getAuthor().getName() + "'s Rank: " + (rank == -1 ? "N/A" : NumberUtility.getSuffixed(rank)) + " | Page " + page.getPage() + "/" + page.getMaxPage(), event.getAuthor().getEffectiveAvatarUrl());
            page.forEach((entry, index) -> embed.appendDescription(String.format("%d. `%s` - %,d %s\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue(), item == null ? "Item" + (entry.getValue() == 1 ? "" : "s") : item.getName())));
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PagedResult(com.sx4.bot.paged.PagedResult) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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 3 with BotPermissions

use of com.sx4.bot.annotations.command.BotPermissions in project Sx4 by sx4-discord-bot.

the class FishingRodCommand method info.

@Command(value = "info", aliases = { "information" }, description = "View information on a users fishing rod")
@CommandId(382)
@Examples({ "fishing rod info", "fishing rod info @Shea#6653", "fishing rod info Shea" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void info(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    Member effectiveMember = member == null ? event.getMember() : member;
    User user = member == null ? event.getAuthor() : effectiveMember.getUser();
    Bson filter = Filters.and(Filters.eq("userId", effectiveMember.getIdLong()), Filters.eq("item.type", ItemType.ROD.getId()));
    Document data = event.getMongo().getItem(filter, Projections.include("item"));
    if (data == null) {
        event.replyFailure("That user does not have a fishing rod").queue();
        return;
    }
    Rod rod = Rod.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
    EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getName() + "'s " + rod.getName(), null, user.getEffectiveAvatarUrl()).setColor(effectiveMember.getColorRaw()).setThumbnail("https://emojipedia-us.s3.amazonaws.com/thumbs/120/twitter/147/fishing-pole-and-fish_1f3a3.png").addField("Durability", rod.getDurability() + "/" + rod.getMaxDurability(), false).addField("Current Price", String.format("$%,d", rod.getCurrentPrice()), false).addField("Price", String.format("$%,d", rod.getPrice()), false).addField("Yield", String.format("$%,d to $%,d", rod.getMinYield(), rod.getMaxYield()), false);
    event.reply(embed.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) Rod(com.sx4.bot.entities.economy.item.Rod) Document(org.bson.Document) Member(net.dv8tion.jda.api.entities.Member) Bson(org.bson.conversions.Bson) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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 BotPermissions

use of com.sx4.bot.annotations.command.BotPermissions in project Sx4 by sx4-discord-bot.

the class WelcomerCommand method formatters.

@Command(value = "formatters", aliases = { "format", "formatting" }, description = "Get all the formatters for welcomer you can use")
@CommandId(441)
@Examples({ "welcomer formatters" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void formatters(Sx4CommandEvent event) {
    EmbedBuilder embed = new EmbedBuilder().setAuthor("Welcomer Formatters", null, event.getSelfUser().getEffectiveAvatarUrl());
    FormatterManager manager = FormatterManager.getDefaultManager();
    StringJoiner content = new StringJoiner("\n");
    for (FormatterVariable<?> variable : manager.getVariables(User.class)) {
        content.add("`{user." + variable.getName() + "}` - " + variable.getDescription());
    }
    for (FormatterVariable<?> variable : manager.getVariables(Member.class)) {
        content.add("`{member." + variable.getName() + "}` - " + variable.getDescription());
    }
    for (FormatterVariable<?> variable : manager.getVariables(Guild.class)) {
        content.add("`{server." + variable.getName() + "}` - " + variable.getDescription());
    }
    for (FormatterVariable<?> variable : manager.getVariables(OffsetDateTime.class)) {
        content.add("`{now." + variable.getName() + "}` - " + variable.getDescription());
    }
    content.add("`{user.age}` - Gets the age of a user as a string");
    embed.setDescription(content.toString());
    event.reply(embed.build()).queue();
}
Also used : FormatterManager(com.sx4.bot.formatter.FormatterManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) StringJoiner(java.util.StringJoiner) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 5 with BotPermissions

use of com.sx4.bot.annotations.command.BotPermissions in project Sx4 by sx4-discord-bot.

the class AutoRoleCommand method fix.

@Command(value = "fix", description = "Will give missing members the auto role if needed")
@CommandId(458)
@Examples({ "auto role fix @Role", "auto role fix Role", "auto role fix 406240455622262784" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@BotPermissions(permissions = { Permission.MANAGE_ROLES })
public void fix(Sx4CommandEvent event, @Argument(value = "role", endless = true) Role role) {
    Document data = event.getMongo().getAutoRole(Filters.eq("roleId", role.getIdLong()), Projections.include("filters"));
    if (data == null) {
        event.replyFailure("That role is not an auto role").queue();
        return;
    }
    if (!event.getSelfMember().canInteract(role)) {
        event.replyFailure("That auto role is above my top role").queue();
        return;
    }
    List<Document> filters = data.getList("filters", Document.class, Collections.emptyList());
    List<Member> members = event.getGuild().getMemberCache().applyStream(stream -> stream.filter(member -> AutoRoleUtility.filtersMatch(member, filters) && !member.getRoles().contains(role) && !member.isPending()).collect(Collectors.toList()));
    if (members.size() == 0) {
        event.replyFailure("No users currently need that auto role").queue();
        return;
    }
    if (!this.pending.add(event.getGuild().getIdLong())) {
        event.replyFailure("You already have an auto role fix in progress").queue();
        return;
    }
    event.replyFormat("Adding %s to **%,d** user%s, another message will be sent once this is done %s", role.getAsMention(), members.size(), members.size() == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
    List<CompletableFuture<Integer>> futures = new ArrayList<>();
    for (Member member : members) {
        futures.add(event.getGuild().addRoleToMember(member, role).submit().handle((result, exception) -> exception == null ? 1 : 0));
    }
    FutureUtility.allOf(futures).whenComplete((completed, exception) -> {
        this.pending.remove(event.getGuild().getIdLong());
        int count = completed.stream().reduce(0, Integer::sum);
        event.replyFormat("Successfully added the role %s to **%,d/%,d** user%s %s", role.getAsMention(), count, members.size(), count == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
    });
}
Also used : Document(org.bson.Document) java.util(java.util) CancelException(com.sx4.bot.waiter.exception.CancelException) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) TimedArgument(com.sx4.bot.entities.argument.TimedArgument) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) AutoRoleFilter(com.sx4.bot.entities.management.AutoRoleFilter) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.sx4.bot.utility(com.sx4.bot.utility) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) Examples(com.sx4.bot.annotations.command.Examples) ErrorCategory(com.mongodb.ErrorCategory) CompletableFuture(java.util.concurrent.CompletableFuture) Document(org.bson.Document) Member(net.dv8tion.jda.api.entities.Member) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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

Command (com.jockie.bot.core.command.Command)38 Sx4Command (com.sx4.bot.core.Sx4Command)38 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)31 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)28 CommandId (com.sx4.bot.annotations.command.CommandId)28 Examples (com.sx4.bot.annotations.command.Examples)26 Document (org.bson.Document)24 PagedResult (com.sx4.bot.paged.PagedResult)21 Bson (org.bson.conversions.Bson)17 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)16 User (net.dv8tion.jda.api.entities.User)15 Argument (com.jockie.bot.core.argument.Argument)10 ModuleCategory (com.sx4.bot.category.ModuleCategory)10 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)10 ArrayList (java.util.ArrayList)10 Permission (net.dv8tion.jda.api.Permission)10 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)9 Collectors (java.util.stream.Collectors)8 Option (com.jockie.bot.core.option.Option)6 java.util (java.util)6