Search in sources :

Example 1 with ItemStack

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

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

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

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

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

the class ShopCommand method list.

@Command(value = "list", description = "View what items the bot has")
@CommandId(455)
@Examples({ "shop list" })
public void list(Sx4CommandEvent event) {
    List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("userId", event.getSelfUser().getIdLong()), Filters.ne("amount", 0))), Aggregates.project(Projections.fields(Projections.computed("name", "$item.name"), Projections.computed("type", "$item.type"), Projections.include("item", "amount"))), Aggregates.sort(Sorts.descending("amount")));
    event.getMongo().aggregateItems(pipeline).whenComplete((items, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        EmbedBuilder embed = new EmbedBuilder().setAuthor("Shop List", null, event.getSelfUser().getEffectiveAvatarUrl()).setColor(event.getSelfMember().getColorRaw());
        if (items.isEmpty()) {
            event.replyFailure("That user does not have any items").queue();
            return;
        }
        Map<ItemType, StringJoiner> types = new HashMap<>();
        for (Document item : items) {
            ItemType type = ItemType.fromId(item.getInteger("type"));
            ItemStack<?> stack = new ItemStack<>(event.getBot().getEconomyManager(), item);
            types.compute(type, (key, value) -> (value == null ? new StringJoiner("\n") : value).add(stack.toString()));
        }
        types.forEach((type, joiner) -> embed.addField(type.getName(), joiner.toString(), true));
        event.reply(embed.build()).queue();
    });
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Document(org.bson.Document) 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)

Aggregations

EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)11 Sx4Command (com.sx4.bot.core.Sx4Command)10 Command (com.jockie.bot.core.command.Command)7 CommandId (com.sx4.bot.annotations.command.CommandId)7 Examples (com.sx4.bot.annotations.command.Examples)7 Document (org.bson.Document)7 Bson (org.bson.conversions.Bson)7 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)6 ItemStack (com.sx4.bot.entities.economy.item.ItemStack)6 PagedResult (com.sx4.bot.paged.PagedResult)6 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)6 ModuleCategory (com.sx4.bot.category.ModuleCategory)5 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)5 Operators (com.sx4.bot.database.mongo.model.Operators)5 EconomyUtility (com.sx4.bot.utility.EconomyUtility)5 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)5 Permission (net.dv8tion.jda.api.Permission)5 Filters (com.mongodb.client.model.Filters)4 UpdateOptions (com.mongodb.client.model.UpdateOptions)4 List (java.util.List)4