Search in sources :

Example 1 with CooldownItemStack

use of com.sx4.bot.entities.economy.item.CooldownItemStack 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 2 with CooldownItemStack

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

the class GiveItemCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user") Member member, @Argument(value = "item", endless = true) ItemStack<Item> stack) {
    User user = member.getUser();
    if (user.isBot()) {
        event.replyFailure("You can not give items to bots").queue();
        return;
    }
    if (user.getIdLong() == event.getAuthor().getIdLong()) {
        event.replyFailure("You can not give items to yourself").queue();
        return;
    }
    long amount = stack.getAmount();
    if (amount < 1) {
        event.replyFailure("You need to give at least 1 item").queue();
        return;
    }
    Item item = stack.getItem();
    if (item instanceof Tool) {
        event.replyFailure("You cannot give tools").queue();
        return;
    }
    long price = stack.getTotalPrice();
    long tax = (long) Math.ceil(price * 0.05D);
    event.getMongo().withTransaction(session -> {
        UpdateResult balanceResult = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(tax)));
        if (balanceResult.getModifiedCount() == 0) {
            event.replyFormat("You do not have enough to pay the tax for this item (**$%,d**) %s", tax, event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return null;
        }
        FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("amount", "resets"));
        Bson authorFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", item.getId()));
        List<Bson> authorUpdate = List.of(Operators.set("amount", Operators.let(new Document("amount", Operators.ifNull("$amount", 0L)), Operators.cond(Operators.lt(Operators.subtract("$$amount", Operators.sum(Operators.map(Operators.filter(Operators.ifNull("$resets", Collections.EMPTY_LIST), Operators.gt("$$this.time", Operators.nowEpochSecond())), "$$this.amount"))), amount), "$$amount", Operators.subtract("$$amount", amount)))));
        Document authorData = event.getMongo().getItems().findOneAndUpdate(session, authorFilter, authorUpdate, options);
        long authorAmount = authorData == null ? 0L : authorData.get("amount", 0L);
        if (authorAmount < amount) {
            event.replyFailure("You do not have `" + amount + " " + item.getName() + "`").queue();
            session.abortTransaction();
            return null;
        }
        CooldownItemStack<Item> cooldownStack = new CooldownItemStack<>(item, authorData);
        long cooldownAmount = cooldownStack.getCooldownAmount();
        if (authorAmount - cooldownAmount < amount) {
            event.replyFormat("You have `%,d %s` but **%,d** %s on cooldown %s", authorAmount, item.getName(), cooldownAmount, cooldownAmount == 1 ? "is" : "are", event.getConfig().getFailureEmote()).queue();
            session.abortTransaction();
            return null;
        }
        Bson userFilter = Filters.and(Filters.eq("userId", member.getIdLong()), Filters.eq("item.id", item.getId()));
        List<Bson> userUpdate = List.of(Operators.set("item", item.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), stack.getAmount())));
        Document userData = event.getMongo().getItems().findOneAndUpdate(session, userFilter, userUpdate, options.upsert(true));
        event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getSelfUser().getIdLong()), Updates.inc("economy.balance", tax));
        EmbedBuilder embed = new EmbedBuilder().setColor(event.getMember().getColor()).setAuthor(event.getAuthor().getName() + " → " + member.getUser().getName(), null, "https://cdn0.iconfinder.com/data/icons/social-messaging-ui-color-shapes/128/money-circle-green-3-512.png").setDescription(String.format("You have gifted **%,d %s** to **%s**\n\n%s's new %s amount: **%,d %s**\n%s's new %s amount: **%,d %s**", amount, item.getName(), user.getName(), event.getAuthor().getName(), item.getName(), authorAmount - amount, item.getName(), user.getName(), item.getName(), (userData == null ? 0L : userData.getLong("amount")) + amount, item.getName())).setFooter(String.format("$%,d (%d%%) tax was taken", tax, Math.round((double) tax / price * 100)), null);
        return embed.build();
    }).whenComplete((embed, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception) || embed == null) {
            return;
        }
        event.reply(embed).queue();
    });
}
Also used : CooldownItemStack(com.sx4.bot.entities.economy.item.CooldownItemStack) 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) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) List(java.util.List) UpdateResult(com.mongodb.client.result.UpdateResult) Item(com.sx4.bot.entities.economy.item.Item) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) com.mongodb.client.model(com.mongodb.client.model) Collections(java.util.Collections) Argument(com.jockie.bot.core.argument.Argument) Tool(com.sx4.bot.entities.economy.item.Tool) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) CooldownItemStack(com.sx4.bot.entities.economy.item.CooldownItemStack) Bson(org.bson.conversions.Bson) Item(com.sx4.bot.entities.economy.item.Item) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) List(java.util.List) UpdateResult(com.mongodb.client.result.UpdateResult) Tool(com.sx4.bot.entities.economy.item.Tool)

Example 3 with CooldownItemStack

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

the class MineCommand 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.PICKAXE.getId()));
        Document data = event.getMongo().getItems().find(session, filter).first();
        if (data == null) {
            event.replyFailure("You do not have a pickaxe").queue();
            session.abortTransaction();
            return;
        }
        CooldownItemStack<Pickaxe> pickaxeStack = new CooldownItemStack<>(event.getBot().getEconomyManager(), data);
        long usableAmount = pickaxeStack.getUsableAmount();
        if (usableAmount == 0) {
            event.reply("Slow down! You can go mining again in " + TimeUtility.LONG_TIME_FORMATTER.parse(pickaxeStack.getTimeRemaining()) + " :stopwatch:").queue();
            session.abortTransaction();
            return;
        }
        Pickaxe pickaxe = pickaxeStack.getItem();
        long yield = pickaxe.getYield();
        List<ItemStack<Material>> materialStacks = pickaxe.getMaterialYield();
        String materials = materialStacks.stream().map(ItemStack::getItem).map(item -> item.getName() + item.getEmote()).collect(Collectors.joining(", "));
        embed.setAuthor(event.getAuthor().getName(), null, event.getAuthor().getEffectiveAvatarUrl()).setColor(event.getMember().getColorRaw()).setDescription(String.format("You mined resources and made **$%,d** :pick:\nMaterials found: %s", yield, materialStacks.isEmpty() ? "Nothing" : materials));
        if (pickaxe.getDurability() == 2) {
            embed.appendDescription("\n\nYour pickaxe will break the next time you use it :warning:");
        } else if (pickaxe.getDurability() == 1) {
            embed.appendDescription("\n\nYour pickaxe broke in the process");
        }
        Bson itemFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", pickaxe.getId()));
        if (pickaxe.getDurability() == 1) {
            event.getMongo().getItems().deleteOne(session, itemFilter);
        } else {
            List<Bson> update = List.of(EconomyUtility.getResetsUpdate(usableAmount, MineCommand.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));
        }
        event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), Updates.inc("economy.balance", yield), 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) Updates(com.mongodb.client.model.Updates) 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 4 with CooldownItemStack

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

the class FishCommand 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.ROD.getId()));
        Document data = event.getMongo().getItems().find(session, filter).first();
        if (data == null) {
            event.replyFailure("You do not have a fishing rod").queue();
            session.abortTransaction();
            return;
        }
        CooldownItemStack<Rod> rodStack = new CooldownItemStack<>(event.getBot().getEconomyManager(), data);
        long usableAmount = rodStack.getUsableAmount();
        if (usableAmount == 0) {
            event.reply("Slow down! You can go fishing again in " + TimeUtility.LONG_TIME_FORMATTER.parse(rodStack.getTimeRemaining()) + " :stopwatch:").queue();
            session.abortTransaction();
            return;
        }
        Rod rod = rodStack.getItem();
        long yield = rod.getYield(event.getBot().getEconomyManager());
        embed.setAuthor(event.getAuthor().getName(), null, event.getAuthor().getEffectiveAvatarUrl()).setColor(event.getMember().getColorRaw()).setDescription(String.format("You fish for 5 minutes and sell your fish! (**$%,d**) :fish:", yield));
        if (rod.getDurability() == 2) {
            embed.appendDescription("\n\nYour fishing rod will break the next time you use it :warning:");
        } else if (rod.getDurability() == 1) {
            embed.appendDescription("\n\nYour fishing rod broke in the process");
        }
        Bson itemFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", rod.getId()));
        if (rod.getDurability() == 1) {
            event.getMongo().getItems().deleteOne(session, itemFilter);
        } else {
            List<Bson> update = List.of(EconomyUtility.getResetsUpdate(usableAmount, FishCommand.COOLDOWN), Operators.set("item.durability", Operators.subtract("$item.durability", 1)));
            event.getMongo().getItems().updateOne(session, itemFilter, update);
        }
        event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), Updates.inc("economy.balance", yield), new UpdateOptions().upsert(true));
    }).whenComplete((updated, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (updated) {
            event.reply(embed.build()).queue();
        }
    });
}
Also used : CooldownItemStack(com.sx4.bot.entities.economy.item.CooldownItemStack) Document(org.bson.Document) Operators(com.sx4.bot.database.mongo.model.Operators) ItemType(com.sx4.bot.entities.economy.item.ItemType) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) Updates(com.mongodb.client.model.Updates) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Rod(com.sx4.bot.entities.economy.item.Rod) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) UpdateOptions(com.mongodb.client.model.UpdateOptions) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Rod(com.sx4.bot.entities.economy.item.Rod) List(java.util.List) Document(org.bson.Document) CooldownItemStack(com.sx4.bot.entities.economy.item.CooldownItemStack) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson)

Example 5 with CooldownItemStack

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

the class TradeCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true) Member member) {
    User user = member.getUser();
    if (user.isBot()) {
        event.replyFailure("You can not trade with bots").queue();
        return;
    }
    if (user.getIdLong() == event.getAuthor().getIdLong()) {
        event.replyFailure("You can not trade with yourself").queue();
        return;
    }
    String prompt = "What %s the user? Make sure you put a space between every thing you want to offer, for example: `2 gold, 200, 5 titanium, 1 coal factory` would offer $200, 5 Titanium, 2 Gold and 1 Coal Factory (Respond Below)";
    AtomicLong userMoneyAtomic = new AtomicLong(0), authorMoneyAtomic = new AtomicLong(0);
    Map<Item, Long> userItems = new HashMap<>(), authorItems = new HashMap<>();
    event.reply(String.format(prompt, "are you offering to")).submit().thenCompose(message -> {
        return new Waiter<>(event.getBot(), MessageReceivedEvent.class).setPredicate(e -> !e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setTimeout(60).start();
    }).thenCompose(e -> {
        Map.Entry<Long, Map<Item, Long>> trade = this.getTrade(event.getBot().getEconomyManager(), e.getMessage().getContentRaw());
        Map<Item, Long> items = trade.getValue();
        long money = trade.getKey();
        if (items.isEmpty() && money == 0) {
            throw new IllegalArgumentException("No valid or tradeable items or money were supplied");
        }
        userItems.putAll(trade.getValue());
        userMoneyAtomic.set(trade.getKey());
        StringJoiner content = new StringJoiner("\n");
        items.forEach((key, value) -> content.add(value + " " + key.getName()));
        EmbedBuilder embed = new EmbedBuilder().setTitle("What you are offering to " + user.getAsTag()).setDescription((money == 0 ? "" : String.format("$%,d", money)) + (items.isEmpty() ? "" : "\n") + content);
        MessageBuilder message = new MessageBuilder().setEmbeds(embed.build()).setContent(String.format(prompt, "would you like from"));
        return event.reply(message.build()).submit();
    }).thenCompose(message -> {
        return new Waiter<>(event.getBot(), MessageReceivedEvent.class).setPredicate(e -> !e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setTimeout(60).start();
    }).thenCompose(e -> {
        Map.Entry<Long, Map<Item, Long>> trade = this.getTrade(event.getBot().getEconomyManager(), e.getMessage().getContentRaw());
        authorItems.putAll(trade.getValue());
        long authorMoney = trade.getKey();
        if (authorItems.isEmpty() && authorMoney == 0) {
            throw new IllegalArgumentException("No valid or tradeable items or money were supplied");
        }
        authorMoneyAtomic.set(authorMoney);
        long userMoney = userMoneyAtomic.get();
        StringJoiner authorContent = new StringJoiner("\n");
        authorItems.forEach((key, value) -> authorContent.add(value + " " + key.getName()));
        StringJoiner userContent = new StringJoiner("\n");
        userItems.forEach((key, value) -> userContent.add(value + " " + key.getName()));
        EmbedBuilder embed = new EmbedBuilder().setTitle("Final Trade").addField(user.getAsTag() + " Gets", (userMoney == 0 ? "" : String.format("$%,d", userMoney)) + (userItems.isEmpty() ? "" : "\n") + userContent, false).addField(event.getAuthor().getAsTag() + " Gets", (authorMoney == 0 ? "" : String.format("$%,d", authorMoney)) + (authorItems.isEmpty() ? "" : "\n") + authorContent, false);
        MessageBuilder message = new MessageBuilder().setEmbeds(embed.build()).setActionRows(ActionRow.of(List.of(Button.success("yes", "Yes"), Button.danger("no", "No")))).setAllowedMentions(EnumSet.of(Message.MentionType.USER)).setContent(user.getAsMention() + ", do you accept this trade?");
        return event.reply(message.build()).submit();
    }).thenCompose(message -> {
        return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, user)).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, user)).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
    }).whenCompleteAsync((e, exception) -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof CancelException) {
            GenericEvent cancelEvent = ((CancelException) cause).getEvent();
            if (cancelEvent != null) {
                ((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
            }
            return;
        } else if (cause instanceof TimeoutException) {
            event.reply("Timed out :stopwatch:").queue();
            return;
        } else if (cause instanceof IllegalArgumentException) {
            event.replyFailure(cause.getMessage()).queue();
            return;
        }
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        event.getMongo().withTransaction(session -> {
            Map<String, Long> types = new HashMap<>();
            Map<Item, Long> combined = new HashMap<>();
            long authorMoney = authorMoneyAtomic.get(), userMoney = userMoneyAtomic.get();
            long totalAuthorWorth = authorMoney;
            for (Item item : authorItems.keySet()) {
                if (item instanceof Envelope) {
                    e.reply("You can not trade envelopes " + event.getConfig().getFailureEmote()).queue();
                    session.abortTransaction();
                    return;
                } else if (item instanceof Tool) {
                    e.reply("You can not trade tools " + event.getConfig().getFailureEmote()).queue();
                    session.abortTransaction();
                    return;
                }
                long amount = authorItems.get(item);
                totalAuthorWorth += item.getPrice() * amount;
                types.compute(item.getName(), (key, value) -> value == null ? amount : value + amount);
                combined.compute(item, (key, value) -> value == null ? -amount : value - amount);
            }
            long totalUserWorth = userMoney;
            for (Item item : userItems.keySet()) {
                if (item instanceof Envelope) {
                    e.reply("You can not trade envelopes " + event.getConfig().getFailureEmote()).queue();
                    session.abortTransaction();
                    return;
                } else if (item instanceof Tool) {
                    e.reply("You can not trade tools " + event.getConfig().getFailureEmote()).queue();
                    session.abortTransaction();
                    return;
                }
                long amount = userItems.get(item);
                totalUserWorth += item.getPrice() * amount;
                types.compute(item.getName(), (key, value) -> value == null ? amount : value + amount);
                combined.compute(item, (key, value) -> value == null ? amount : value + amount);
            }
            types.put("Money", authorMoney + userMoney);
            Map.Entry<String, Long> max = types.entrySet().stream().max(Map.Entry.comparingByValue()).get();
            if ((double) max.getValue() / (totalUserWorth + totalAuthorWorth) >= 0.7D) {
                e.reply(max.getKey() + " cannot make up more than 70% of the trades value " + event.getConfig().getFailureEmote()).queue();
                session.abortTransaction();
                return;
            }
            if (totalUserWorth / totalAuthorWorth > 5 || totalAuthorWorth / totalUserWorth > 5) {
                e.reply("You have to trade at least 20% the worth of the other persons trade " + event.getConfig().getFailureEmote()).queue();
                session.abortTransaction();
                return;
            }
            if (userMoney - authorMoney != 0) {
                List<Bson> authorUpdate = List.of(Operators.set("economy.balance", Operators.let(new Document("balance", Operators.ifNull("$economy.balance", 0L)), Operators.let(new Document("newBalance", Operators.add("$$balance", authorMoney - userMoney)), Operators.cond(Operators.lt("$$newBalance", 0L), "$$balance", "$$newBalance")))));
                UpdateResult authorResult = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), authorUpdate);
                if (authorResult.getModifiedCount() == 0) {
                    e.replyFormat("%s does not have **$%,d** %s", event.getAuthor().getAsTag(), userMoney - authorMoney, event.getConfig().getFailureEmote()).queue();
                    session.abortTransaction();
                    return;
                }
                List<Bson> userUpdate = List.of(Operators.set("economy.balance", Operators.let(new Document("balance", Operators.ifNull("$economy.balance", 0L)), Operators.let(new Document("newBalance", Operators.add("$$balance", userMoney - authorMoney)), Operators.cond(Operators.lt("$$newBalance", 0L), "$$balance", "$$newBalance")))));
                UpdateResult userResult = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", user.getIdLong()), userUpdate);
                if (userResult.getModifiedCount() == 0) {
                    e.replyFormat("%s does not have **$%,d** %s", event.getAuthor().getAsTag(), authorMoney - userMoney, event.getConfig().getFailureEmote()).queue();
                    session.abortTransaction();
                    return;
                }
            }
            for (Item item : combined.keySet()) {
                long signedAmount = combined.get(item);
                if (signedAmount == 0) {
                    continue;
                }
                boolean author = signedAmount < 0;
                long amount = Math.abs(signedAmount);
                List<Bson> addUpdate = List.of(Operators.set("item", item.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), amount)));
                event.getMongo().getItems().updateOne(session, Filters.and(Filters.eq("userId", author ? event.getAuthor().getIdLong() : user.getIdLong()), Filters.eq("item.id", item.getId())), addUpdate, new UpdateOptions().upsert(true));
                List<Bson> removeUpdate = List.of(Operators.set("amount", Operators.let(new Document("amount", Operators.ifNull("$amount", 0L)), Operators.cond(Operators.lt(Operators.subtract("$$amount", Operators.sum(Operators.map(Operators.filter(Operators.ifNull("$resets", Collections.EMPTY_LIST), Operators.gt("$$this.time", Operators.nowEpochSecond())), "$$this.amount"))), amount), "$$amount", Operators.subtract("$$amount", amount)))));
                FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(Projections.include("amount", "resets")).returnDocument(ReturnDocument.BEFORE);
                Document data = event.getMongo().getItems().findOneAndUpdate(session, Filters.and(Filters.eq("userId", author ? user.getIdLong() : event.getAuthor().getIdLong()), Filters.eq("item.id", item.getId())), removeUpdate, options);
                long userAmount = data == null ? 0L : data.get("amount", 0L);
                if (userAmount < amount) {
                    e.reply((author ? user.getAsTag() : event.getAuthor().getAsTag()) + " does not have `" + amount + " " + item.getName() + "` " + event.getConfig().getFailureEmote()).queue();
                    session.abortTransaction();
                    return;
                }
                CooldownItemStack<Item> cooldownStack = new CooldownItemStack<>(item, data);
                long cooldownAmount = cooldownStack.getCooldownAmount();
                if (userAmount - cooldownAmount < amount) {
                    e.replyFormat("%s has `%,d %s` but **%,d** %s on cooldown %s", author ? user.getAsTag() : event.getAuthor().getAsTag(), userAmount, item.getName(), cooldownAmount, cooldownAmount == 1 ? "is" : "are", event.getConfig().getFailureEmote()).queue();
                    session.abortTransaction();
                    return;
                }
            }
        }).whenComplete((updated, databaseException) -> {
            if (ExceptionUtility.sendExceptionally(event, databaseException) || !updated) {
                return;
            }
            e.reply("All money and items have been traded " + event.getConfig().getSuccessEmote()).queue();
        });
    });
}
Also used : Document(org.bson.Document) java.util(java.util) CancelException(com.sx4.bot.waiter.exception.CancelException) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) Permission(net.dv8tion.jda.api.Permission) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) ButtonUtility(com.sx4.bot.utility.ButtonUtility) UpdateResult(com.mongodb.client.result.UpdateResult) com.sx4.bot.entities.economy.item(com.sx4.bot.entities.economy.item) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) com.mongodb.client.model(com.mongodb.client.model) Argument(com.jockie.bot.core.argument.Argument) Message(net.dv8tion.jda.api.entities.Message) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) EconomyManager(com.sx4.bot.managers.EconomyManager) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) AtomicLong(java.util.concurrent.atomic.AtomicLong) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) UpdateResult(com.mongodb.client.result.UpdateResult) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) AtomicLong(java.util.concurrent.atomic.AtomicLong) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) CompletionException(java.util.concurrent.CompletionException) AtomicLong(java.util.concurrent.atomic.AtomicLong) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter)

Aggregations

ModuleCategory (com.sx4.bot.category.ModuleCategory)5 Sx4Command (com.sx4.bot.core.Sx4Command)5 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)5 Operators (com.sx4.bot.database.mongo.model.Operators)5 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)5 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)5 Permission (net.dv8tion.jda.api.Permission)5 Document (org.bson.Document)5 Bson (org.bson.conversions.Bson)5 EconomyUtility (com.sx4.bot.utility.EconomyUtility)4 List (java.util.List)4 Filters (com.mongodb.client.model.Filters)3 UpdateOptions (com.mongodb.client.model.UpdateOptions)3 com.sx4.bot.entities.economy.item (com.sx4.bot.entities.economy.item)3 TimeUtility (com.sx4.bot.utility.TimeUtility)3 Argument (com.jockie.bot.core.argument.Argument)2 com.mongodb.client.model (com.mongodb.client.model)2 Updates (com.mongodb.client.model.Updates)2 UpdateResult (com.mongodb.client.result.UpdateResult)2 CooldownItemStack (com.sx4.bot.entities.economy.item.CooldownItemStack)2