Search in sources :

Example 11 with Item

use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.

the class AxeCommand method upgrade.

@Command(value = "upgrade", description = "Upgrade your axe by a certain attribute")
@CommandId(429)
@Examples({ "axe upgrade multiplier", "axe upgrade durability 5" })
public void upgrade(Sx4CommandEvent event, @Argument(value = "upgrade") Upgrade upgrade, @Argument(value = "upgrades") @DefaultNumber(1) @Limit(min = 1, max = 100) int upgrades) {
    if (!upgrade.containsType(ItemType.AXE)) {
        event.replyFailure("You can not use that upgrade on a axe").queue();
        return;
    }
    event.getMongo().withTransaction(session -> {
        Document data = event.getMongo().getItems().find(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()))).first();
        if (data == null) {
            event.replyFailure("You do not have a axe").queue();
            session.abortTransaction();
            return null;
        }
        Document item = data.get("item", Document.class);
        Axe defaultAxe = event.getBot().getEconomyManager().getItemById(item.getInteger("id"), Axe.class);
        Axe axe = new Axe(item, defaultAxe);
        int currentUpgrades = axe.getUpgrades();
        long price = 0;
        for (int i = 0; i < upgrades; i++) {
            price += Math.round(0.015D * defaultAxe.getPrice() * currentUpgrades++ + 0.025D * defaultAxe.getPrice());
        }
        UpdateResult result = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(price)));
        if (result.getModifiedCount() == 0) {
            event.replyFormat("You do not have **$%,d** %s", price, event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return null;
        }
        List<Bson> update = new ArrayList<>();
        update.add(Operators.set("item.upgrades", Operators.add(Operators.ifNull("$item.upgrades", 0), upgrades)));
        update.add(Operators.set("item.price", Operators.add("$item.price", Math.round(defaultAxe.getPrice() * 0.015D) * upgrades)));
        if (upgrade == Upgrade.DURABILITY) {
            int increase = (int) upgrade.getValue() * upgrades;
            update.add(Operators.set("item.durability", Operators.add("$item.durability", increase)));
            update.add(Operators.set("item.maxDurability", Operators.add("$item.maxDurability", increase)));
        } else if (upgrade == Upgrade.MULTIPLIER) {
            double increase = defaultAxe.getMultiplier() * upgrade.getValue() * upgrades;
            update.add(Operators.set("item.multiplier", Operators.add("$item.multiplier", increase)));
        }
        event.getMongo().getItems().updateOne(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", axe.getId())), update);
        return String.format("You just upgraded %s %d time%s for your `%s` for **$%,d**", upgrade.getName().toLowerCase(), upgrades, (upgrades == 1 ? "" : "s"), axe.getName(), price);
    }).whenComplete((message, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception) || message == null) {
            return;
        }
        event.replySuccess(message).queue();
    });
}
Also used : Document(org.bson.Document) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Arrays(java.util.Arrays) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) CraftItem(com.sx4.bot.entities.economy.item.CraftItem) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CommandId(com.sx4.bot.annotations.command.CommandId) Member(net.dv8tion.jda.api.entities.Member) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) UpdateResult(com.mongodb.client.result.UpdateResult) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) EnumSet(java.util.EnumSet) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) Upgrade(com.sx4.bot.entities.economy.upgrade.Upgrade) Operators(com.sx4.bot.database.mongo.model.Operators) ItemType(com.sx4.bot.entities.economy.item.ItemType) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) ReturnDocument(com.mongodb.client.model.ReturnDocument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Examples(com.sx4.bot.annotations.command.Examples) Axe(com.sx4.bot.entities.economy.item.Axe) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ButtonType(com.sx4.bot.entities.interaction.ButtonType) ArrayList(java.util.ArrayList) List(java.util.List) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) UpdateResult(com.mongodb.client.result.UpdateResult) Axe(com.sx4.bot.entities.economy.item.Axe) 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 12 with Item

use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.

the class ChopCommand method onCommand.

public void onCommand(Sx4CommandEvent event) {
    EmbedBuilder embed = new EmbedBuilder();
    event.getMongo().withTransaction(session -> {
        Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()));
        Document data = event.getMongo().getItems().find(session, filter).first();
        if (data == null) {
            event.replyFailure("You do not have a axe").queue();
            session.abortTransaction();
            return;
        }
        CooldownItemStack<Axe> axeStack = new CooldownItemStack<>(event.getBot().getEconomyManager(), data);
        long usableAmount = axeStack.getUsableAmount();
        if (usableAmount == 0) {
            event.reply("Slow down! You can chop some trees down again in " + TimeUtility.LONG_TIME_FORMATTER.parse(axeStack.getTimeRemaining()) + " :stopwatch:").queue();
            session.abortTransaction();
            return;
        }
        Axe axe = axeStack.getItem();
        List<ItemStack<Wood>> materialStacks = axe.getWoodYield();
        String materials = materialStacks.stream().map(ItemStack::toString).collect(Collectors.joining(", "));
        embed.setAuthor(event.getAuthor().getName(), null, event.getAuthor().getEffectiveAvatarUrl()).setColor(event.getMember().getColorRaw()).setDescription(String.format("You chopped down some trees :axe:\nWood found: %s", materialStacks.isEmpty() ? "Nothing" : materials));
        if (axe.getDurability() == 2) {
            embed.appendDescription("\n\nYour axe will break the next time you use it :warning:");
        } else if (axe.getDurability() == 1) {
            embed.appendDescription("\n\nYour axe broke in the process");
        }
        Bson itemFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", axe.getId()));
        if (axe.getDurability() == 1) {
            event.getMongo().getItems().deleteOne(session, itemFilter);
        } else {
            List<Bson> update = List.of(EconomyUtility.getResetsUpdate(usableAmount, ChopCommand.COOLDOWN), Operators.set("item.durability", Operators.subtract("$item.durability", 1)));
            event.getMongo().getItems().updateOne(session, itemFilter, update);
        }
        for (ItemStack<?> stack : materialStacks) {
            Item item = stack.getItem();
            List<Bson> update = List.of(Operators.set("item", item.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), stack.getAmount())));
            Bson materialFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", item.getId()));
            event.getMongo().getItems().updateOne(session, materialFilter, update, new UpdateOptions().upsert(true));
        }
    }).whenComplete((updated, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (updated) {
            event.reply(embed.build()).queue();
        }
    });
}
Also used : Document(org.bson.Document) Operators(com.sx4.bot.database.mongo.model.Operators) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) com.sx4.bot.entities.economy.item(com.sx4.bot.entities.economy.item) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) UpdateOptions(com.mongodb.client.model.UpdateOptions) Document(org.bson.Document) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) List(java.util.List)

Example 13 with Item

use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.

the class CrateCommand method buy.

@Command(value = "buy", description = "Buy a crate from the `crate shop`")
@CommandId(412)
@Examples({ "crate buy 2 Shoe Crate", "crate buy Shoe Crate", "crate buy 5 Shoe" })
public void buy(Sx4CommandEvent event, @Argument(value = "crates", endless = true) ItemStack<Crate> stack) {
    long amount = stack.getAmount();
    if (amount < 1) {
        event.replyFailure("You need to buy at least 1 crate").queue();
        return;
    }
    long price = stack.getTotalPrice();
    Crate crate = stack.getItem();
    event.getMongo().withTransaction(session -> {
        UpdateResult result = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(price)));
        if (result.getModifiedCount() == 0) {
            event.replyFormat("You do not have **$%,d** %s", price, event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return;
        }
        Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", crate.getId()));
        List<Bson> update = List.of(Operators.set("item", crate.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), amount)));
        event.getMongo().getItems().updateOne(session, filter, update, new UpdateOptions().upsert(true));
    }).whenComplete((updated, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception) || !updated) {
            return;
        }
        event.replyFormat("You just bought `%,d %s` for **$%,d** %s", amount, crate.getName(), price, event.getConfig().getSuccessEmote()).queue();
    });
}
Also used : Document(org.bson.Document) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) PagedResult(com.sx4.bot.paged.PagedResult) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) UpdateResult(com.mongodb.client.result.UpdateResult) Item(com.sx4.bot.entities.economy.item.Item) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) UpdateOptions(com.mongodb.client.model.UpdateOptions) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) Predicate(java.util.function.Predicate) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) StringJoiner(java.util.StringJoiner) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Crate(com.sx4.bot.entities.economy.item.Crate) Comparator(java.util.Comparator) Collections(java.util.Collections) Crate(com.sx4.bot.entities.economy.item.Crate) List(java.util.List) UpdateResult(com.mongodb.client.result.UpdateResult) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson) 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 14 with Item

use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.

the class GiveawayCommand method setup.

@Command(value = "setup", description = "Setup giveaways for users to react to")
@CommandId(47)
@Examples({ "giveaway setup", "giveaway setup #giveaways 1 7d $10 Nitro" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void setup(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "winners") @DefaultNumber(0) @Limit(min = 1) int winners, @Argument(value = "duration", nullDefault = true) Duration duration, @Argument(value = "item", nullDefault = true, endless = true) String item) {
    if (channel != null && winners != 0 && duration != null && item != null) {
        long seconds = duration.toSeconds();
        if (seconds < 1) {
            event.replyFailure("The duration of a giveaway cannot be less than 1 second").queue();
            return;
        }
        channel.sendMessageEmbeds(this.getEmbed(winners, seconds, item)).queue(message -> {
            message.addReaction("🎉").queue();
            Document data = new Document("messageId", message.getIdLong()).append("channelId", channel.getIdLong()).append("guildId", event.getGuild().getIdLong()).append("winnersAmount", winners).append("endAt", Clock.systemUTC().instant().getEpochSecond() + seconds).append("duration", seconds).append("item", item);
            event.getMongo().insertGiveaway(data).whenComplete((result, exception) -> {
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.getBot().getGiveawayManager().putGiveaway(data, seconds);
                event.reply("Your giveaway has been created in " + channel.getAsMention() + " :tada:").queue();
            });
        });
        return;
    }
    AtomicReference<BaseGuildMessageChannel> atomicChannel = new AtomicReference<>();
    AtomicInteger atomicWinners = new AtomicInteger();
    AtomicReference<Duration> atomicDuration = new AtomicReference<>();
    AtomicReference<String> atomicItem = new AtomicReference<>();
    CompletableFuture.completedFuture(true).thenCompose($ -> {
        if (channel != null) {
            atomicChannel.set(channel);
            return CompletableFuture.completedFuture(true);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        event.reply("What channel would you like to start the giveaway in? Type `cancel` at anytime to cancel the creation.").queue(message -> {
            Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setPredicate(e -> {
                BaseGuildMessageChannel messageChannel = SearchUtility.getBaseMessageChannel(event.getGuild(), e.getMessage().getContentRaw());
                if (messageChannel != null) {
                    atomicChannel.set(messageChannel);
                    return true;
                }
                event.replyFailure("I could not find that channel").queue();
                return false;
            });
            waiter.onCancelled((type) -> {
                event.replySuccess("Cancelled").queue();
                future.complete(false);
            });
            waiter.onTimeout(() -> {
                event.reply("Response timed out :stopwatch:").queue();
                future.complete(false);
            });
            waiter.onSuccess(e -> future.complete(true));
            waiter.start();
        });
        return future;
    }).thenCompose(success -> {
        if (!success) {
            return CompletableFuture.completedFuture(false);
        }
        if (winners != 0) {
            atomicWinners.set(winners);
            return CompletableFuture.completedFuture(true);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        event.reply("How many winners would you like the giveaway to have?").queue(message -> {
            Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
                String content = e.getMessage().getContentRaw();
                if (NumberUtility.isNumberUnsigned(content)) {
                    int number = Integer.parseInt(content);
                    if (number < 1) {
                        event.replyFailure("You have to have at least 1 winner").queue();
                        return false;
                    }
                    atomicWinners.set(number);
                    return true;
                }
                event.replyFailure("That is not a number").queue();
                return false;
            });
            waiter.onCancelled((type) -> {
                event.replySuccess("Cancelled").queue();
                future.complete(false);
            });
            waiter.onTimeout(() -> {
                event.reply("Response timed out :stopwatch:").queue();
                future.complete(false);
            });
            waiter.onSuccess(e -> future.complete(true));
            waiter.start();
        });
        return future;
    }).thenCompose(success -> {
        if (!success) {
            return CompletableFuture.completedFuture(false);
        }
        if (duration != null) {
            atomicDuration.set(duration);
            return CompletableFuture.completedFuture(true);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        event.reply("How long would you like the giveaway to last?").queue(message -> {
            Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
                Duration durationReply = TimeUtility.getDurationFromString(e.getMessage().getContentRaw());
                if (durationReply.toSeconds() < 1) {
                    event.replyFailure("The duration of a giveaway cannot be less than 1 second").queue();
                    return false;
                }
                atomicDuration.set(durationReply);
                return true;
            });
            waiter.onCancelled((type) -> {
                event.replySuccess("Cancelled").queue();
                future.complete(false);
            });
            waiter.onTimeout(() -> {
                event.reply("Response timed out :stopwatch:").queue();
                future.complete(false);
            });
            waiter.onSuccess(e -> future.complete(true));
            waiter.start();
        });
        return future;
    }).thenCompose(success -> {
        if (!success) {
            return CompletableFuture.completedFuture(false);
        }
        if (item != null) {
            atomicItem.set(item);
            return CompletableFuture.completedFuture(true);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        event.reply("What would you like to giveaway?").queue(message -> {
            Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
                String content = e.getMessage().getContentRaw();
                if (content.equalsIgnoreCase("cancel")) {
                    return false;
                }
                atomicItem.set(content);
                return true;
            });
            waiter.onCancelled((type) -> {
                event.replySuccess("Cancelled").queue();
                future.complete(false);
            });
            waiter.onTimeout(() -> {
                event.reply("Response timed out :stopwatch:").queue();
                future.complete(false);
            });
            waiter.onSuccess(e -> future.complete(true));
            waiter.start();
        });
        return future;
    }).thenAccept(success -> {
        if (!success) {
            return;
        }
        BaseGuildMessageChannel channelFuture = atomicChannel.get();
        int winnersFuture = atomicWinners.get();
        long durationFuture = atomicDuration.get().toSeconds();
        String itemFuture = atomicItem.get();
        channelFuture.sendMessageEmbeds(this.getEmbed(winnersFuture, durationFuture, itemFuture)).queue(message -> {
            message.addReaction("🎉").queue();
            Document data = new Document("messageId", message.getIdLong()).append("channelId", channelFuture.getIdLong()).append("guildId", event.getGuild().getIdLong()).append("winnersAmount", winnersFuture).append("endAt", Clock.systemUTC().instant().getEpochSecond() + durationFuture).append("duration", durationFuture).append("item", itemFuture);
            event.getMongo().insertGiveaway(data).whenComplete((result, exception) -> {
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.getBot().getGiveawayManager().putGiveaway(data, durationFuture);
                event.reply("Your giveaway has been created in " + channelFuture.getAsMention() + " :tada:").queue();
            });
        });
    });
}
Also used : Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) PagedResult(com.sx4.bot.paged.PagedResult) AtomicReference(java.util.concurrent.atomic.AtomicReference) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Waiter(com.sx4.bot.waiter.Waiter) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) SearchUtility(com.sx4.bot.utility.SearchUtility) ReturnDocument(com.mongodb.client.model.ReturnDocument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Examples(com.sx4.bot.annotations.command.Examples) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) Collections(java.util.Collections) ButtonType(com.sx4.bot.entities.interaction.ButtonType) AtomicReference(java.util.concurrent.atomic.AtomicReference) Duration(java.time.Duration) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Waiter(com.sx4.bot.waiter.Waiter) 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)

Example 15 with Item

use of com.sx4.bot.entities.economy.item.Item in project Sx4 by sx4-discord-bot.

the class SteamCommand method inventory.

@Command(value = "inventory", description = "Look at your steam inventory for a game")
@CommandId(505)
@Examples({ "steam inventory Intruder", "steam inventory Counter-Strike" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void inventory(Sx4CommandEvent event, @Argument(value = "game", endless = true) String query) {
    SteamGameCache cache = event.getBot().getSteamGameCache();
    if (cache.getGames().isEmpty()) {
        event.replyFailure("The steam cache is currently empty, try again").queue();
        return;
    }
    Matcher urlMatcher;
    List<Document> games;
    if (NumberUtility.isNumberUnsigned(query)) {
        games = List.of(new Document("appid", Integer.parseInt(query)));
    } else if ((urlMatcher = this.gamePattern.matcher(query)).matches()) {
        games = List.of(new Document("appid", Integer.parseInt(urlMatcher.group(1))));
    } else {
        games = cache.getGames(query);
        if (games.isEmpty()) {
            event.replyFailure("I could not find any games with that query").queue();
            return;
        }
    }
    PagedResult<Document> gamePaged = new PagedResult<>(event.getBot(), games).setAuthor("Steam Search", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setIncreasedIndex(true).setAutoSelect(true).setTimeout(60).setDisplayFunction(game -> game.getString("name"));
    gamePaged.onSelect(gameSelect -> {
        int game = gameSelect.getSelected().getInteger("appid");
        List<Document> connections = event.getMongo().getUserById(event.getAuthor().getIdLong(), Projections.include("connections.steam")).getEmbedded(List.of("connections", "steam"), Collections.emptyList());
        if (connections.isEmpty()) {
            event.replyFailure("You do not have a steam account linked, use `steam connect` to link an account or provide an argument to search").queue();
            return;
        }
        List<Document> profiles = connections.stream().map(data -> data.append("url", "https://steamcommunity.com/profiles/" + data.getLong("id") + "/")).collect(Collectors.toList());
        PagedResult<Document> profilePaged = new PagedResult<>(event.getBot(), profiles).setAutoSelect(true).setAuthor("Steam Profiles", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setDisplayFunction(data -> "[" + data.getString("name") + "](" + data.getString("url") + ")");
        profilePaged.onSelect(profileSelect -> {
            long id = profileSelect.getSelected().getLong("id");
            Request request = new Request.Builder().url("https://steamcommunity.com/inventory/" + id + "/" + game + "/2?l=english&count=5000").build();
            event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
                String body = response.body().string();
                if (body.equals("null")) {
                    event.replyFailure("Your inventory is set to private").queue();
                    return;
                }
                Document json = Document.parse(body);
                if (json.containsKey("error")) {
                    event.replyFailure("That game does not have inventory items").queue();
                    return;
                }
                int totalCount = json.getInteger("total_inventory_count");
                if (totalCount == 0) {
                    event.replyFailure("You do not have any inventory items for this game").queue();
                    return;
                }
                List<Document> items = json.getList("descriptions", Document.class);
                List<Document> assets = json.getList("assets", Document.class);
                PagedResult<Document> itemPaged = new PagedResult<>(event.getBot(), items).setSelect().setPerPage(1).cachePages(true).setAsyncFunction((page, message) -> {
                    EmbedBuilder embed = new EmbedBuilder();
                    embed.setFooter("Item " + page.getPage() + "/" + page.getMaxPage());
                    page.forEach((item, index) -> {
                        Document asset = assets.stream().filter(d -> d.getString("classid").equals(item.getString("classid"))).findFirst().orElse(null);
                        List<Document> descriptions = item.getList("descriptions", Document.class);
                        StringJoiner joiner = new StringJoiner("\n");
                        for (Document description : descriptions) {
                            String value = description.getString("value");
                            if (value.isBlank()) {
                                continue;
                            }
                            Element element = Jsoup.parse(value.replace("*", "\\*"));
                            for (Element italicElement : element.getElementsByTag("i")) {
                                italicElement.replaceWith(new TextNode("*" + italicElement.text() + "*"));
                            }
                            for (Element boldElement : element.getElementsByTag("b")) {
                                boldElement.replaceWith(new TextNode("**" + boldElement.text() + "**"));
                            }
                            joiner.add(element.text());
                        }
                        String inspect = item.getList("actions", Document.class, Collections.emptyList()).stream().filter(d -> d.getString("name").equals("Inspect in Game...")).map(d -> d.getString("link")).findFirst().orElse(null);
                        embed.setDescription(joiner.toString());
                        embed.setTitle(item.getString("market_name"), "https://steamcommunity.com/profiles/" + id + "/inventory/#" + game + (asset == null ? "" : "_2_" + asset.getString("assetid")));
                        embed.setImage("https://community.cloudflare.steamstatic.com/economy/image/" + item.getString("icon_url"));
                        if (inspect != null) {
                            embed.addField("Inspect In Game", "<" + inspect + ">", false);
                        }
                        Request itemRequest = new Request.Builder().url("https://steamcommunity.com/market/priceoverview/?appid=" + game + "&currency=2&market_hash_name=" + URLEncoder.encode(item.getString("market_hash_name"), StandardCharsets.UTF_8)).build();
                        event.getHttpClient().newCall(itemRequest).enqueue((HttpCallback) itemResponse -> {
                            String itemBody = itemResponse.body().string();
                            if (itemBody.equals("null")) {
                                message.accept(new MessageBuilder().setEmbeds(embed.build()));
                                return;
                            }
                            Document priceData = Document.parse(itemBody);
                            if (priceData.getBoolean("success") && priceData.containsKey("lowest_price")) {
                                embed.addField("Lowest Price", priceData.getString("lowest_price"), false);
                            }
                            message.accept(new MessageBuilder().setEmbeds(embed.build()));
                        });
                    });
                });
                itemPaged.execute(event);
            });
        });
        profilePaged.execute(event);
    });
    gamePaged.execute(event);
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) TextNode(org.jsoup.nodes.TextNode) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) CommandId(com.sx4.bot.annotations.command.CommandId) Cooldown(com.jockie.bot.core.command.Command.Cooldown) PagedResult(com.sx4.bot.paged.PagedResult) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Element(org.jsoup.nodes.Element) Option(com.jockie.bot.core.option.Option) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Request(okhttp3.Request) HmacUtility(com.sx4.bot.utility.HmacUtility) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) Examples(com.sx4.bot.annotations.command.Examples) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) InvalidKeyException(java.security.InvalidKeyException) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Jsoup(org.jsoup.Jsoup) Pattern(java.util.regex.Pattern) StringUtility(com.sx4.bot.utility.StringUtility) JSONArray(org.json.JSONArray) SteamGameCache(com.sx4.bot.cache.SteamGameCache) Matcher(java.util.regex.Matcher) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Element(org.jsoup.nodes.Element) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) TextNode(org.jsoup.nodes.TextNode) Document(org.bson.Document) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) SteamGameCache(com.sx4.bot.cache.SteamGameCache) 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)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)29 Document (org.bson.Document)29 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)28 Bson (org.bson.conversions.Bson)27 Command (com.jockie.bot.core.command.Command)22 CommandId (com.sx4.bot.annotations.command.CommandId)22 Examples (com.sx4.bot.annotations.command.Examples)22 ModuleCategory (com.sx4.bot.category.ModuleCategory)18 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)18 Permission (net.dv8tion.jda.api.Permission)17 Operators (com.sx4.bot.database.mongo.model.Operators)16 PagedResult (com.sx4.bot.paged.PagedResult)15 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)15 Argument (com.jockie.bot.core.argument.Argument)14 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)14 Collectors (java.util.stream.Collectors)13 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)13 ReturnDocument (com.mongodb.client.model.ReturnDocument)12 User (net.dv8tion.jda.api.entities.User)12 Filters (com.mongodb.client.model.Filters)11