Search in sources :

Example 36 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class ItemsCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    Member effectiveMember = member == null ? event.getMember() : member;
    List<Bson> usersPipeline = List.of(Aggregates.match(Filters.eq("_id", effectiveMember.getIdLong())), Aggregates.project(Projections.computed("balance", Operators.ifNull("$economy.balance", 0L))), Aggregates.addFields(new Field<>("name", "balance")));
    List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("userId", effectiveMember.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")), Aggregates.unionWith("users", usersPipeline));
    event.getMongo().aggregateItems(pipeline).whenComplete((items, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        EmbedBuilder embed = new EmbedBuilder().setAuthor("Items", null, effectiveMember.getUser().getEffectiveAvatarUrl()).setColor(effectiveMember.getColorRaw());
        if (items.isEmpty()) {
            event.replyFailure("That user does not have any items").queue();
            return;
        }
        String footerText = "If a category isn't shown it means you have no items in that category | Balance: $";
        StringBuilder footer = new StringBuilder(footerText);
        Map<ItemType, StringJoiner> types = new HashMap<>();
        for (Document item : items) {
            String name = item.getString("name");
            if (name.equals("balance")) {
                if (items.size() == 1) {
                    event.replyFailure("That user does not have any items").queue();
                    return;
                }
                footer.append(String.format("%,d", item.get("balance", 0L)));
                continue;
            }
            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()));
        }
        if (footer.length() == footerText.length()) {
            footer.append("0");
        }
        types.forEach((type, joiner) -> embed.addField(type.getName(), joiner.toString(), true));
        embed.setFooter(footer.toString());
        event.reply(embed.build()).queue();
    });
}
Also used : ItemType(com.sx4.bot.entities.economy.item.ItemType) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ItemStack(com.sx4.bot.entities.economy.item.ItemStack) Member(net.dv8tion.jda.api.entities.Member)

Example 37 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class AxeCommand method info.

@Command(value = "info", aliases = { "information" }, description = "View information on a users axe")
@CommandId(391)
@Examples({ "axe info", "axe info @Shea#6653", "axe info Shea" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void info(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    Member effectiveMember = member == null ? event.getMember() : member;
    User user = member == null ? event.getAuthor() : effectiveMember.getUser();
    Bson filter = Filters.and(Filters.eq("userId", effectiveMember.getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()));
    Document data = event.getMongo().getItem(filter, Projections.include("item"));
    if (data == null) {
        event.replyFailure("That user does not have an axe").queue();
        return;
    }
    Axe axe = Axe.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
    EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getName() + "'s " + axe.getName(), null, user.getEffectiveAvatarUrl()).setColor(effectiveMember.getColorRaw()).setThumbnail("https://www.shareicon.net/data/2016/09/02/823994_ax_512x512.png").addField("Durability", axe.getDurability() + "/" + axe.getMaxDurability(), false).addField("Current Price", String.format("$%,d", axe.getCurrentPrice()), false).addField("Price", String.format("$%,d", axe.getPrice()), false).addField("Max Materials", String.valueOf(axe.getMaxMaterials()), false).addField("Multiplier", NumberUtility.DEFAULT_DECIMAL_FORMAT.format(axe.getMultiplier()), false);
    event.reply(embed.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) Member(net.dv8tion.jda.api.entities.Member) Bson(org.bson.conversions.Bson) Axe(com.sx4.bot.entities.economy.item.Axe) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 38 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class AxeCommand method repair.

@Command(value = "repair", description = "Repair your current axe with the material it is made from")
@CommandId(392)
@Examples({ "axe repair 10", "axe repair all" })
public void repair(Sx4CommandEvent event, @Argument(value = "durability") @AlternativeOptions("all") Alternative<Integer> option) {
    Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()));
    Document data = event.getMongo().getItem(filter, Projections.include("item"));
    if (data == null) {
        event.replyFailure("You do not have a axe").queue();
        return;
    }
    Axe axe = Axe.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
    CraftItem item = axe.getRepairItem();
    if (item == null) {
        event.replyFailure("That axe is not repairable").queue();
        return;
    }
    int maxDurability = axe.getMaxDurability() - axe.getDurability();
    if (maxDurability <= 0) {
        event.replyFailure("Your axe is already at full durability").queue();
        return;
    }
    int durability;
    if (option.isAlternative()) {
        durability = maxDurability;
    } else {
        int amount = option.getValue();
        if (amount > maxDurability) {
            event.reply("You can only repair your axe by **" + maxDurability + "** durability :no_entry:").queue();
            return;
        }
        durability = amount;
    }
    String acceptId = new CustomButtonId.Builder().setType(ButtonType.AXE_REPAIR_CONFIRM).setTimeout(60).setOwners(event.getAuthor().getIdLong()).setArguments(item.getId(), axe.getId(), axe.getDurability(), durability).getId();
    String rejectId = new CustomButtonId.Builder().setType(ButtonType.GENERIC_REJECT).setTimeout(60).setOwners(event.getAuthor().getIdLong()).getId();
    List<Button> buttons = List.of(Button.success(acceptId, "Yes"), Button.danger(rejectId, "No"));
    int itemCount = (int) Math.ceil((((double) axe.getPrice() / item.getPrice()) / axe.getMaxDurability()) * durability);
    event.reply("It will cost you `" + itemCount + " " + item.getName() + "` to repair your axe by **" + durability + "** durability, are you sure you want to repair it?").setActionRow(buttons).queue();
}
Also used : Button(net.dv8tion.jda.api.interactions.components.buttons.Button) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) CraftItem(com.sx4.bot.entities.economy.item.CraftItem) Bson(org.bson.conversions.Bson) 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 39 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class DailyCommand method onCommand.

public void onCommand(Sx4CommandEvent event) {
    List<Bson> update = List.of(Operators.set("economy.balance", Operators.let(new Document("reset", Operators.ifNull("$economy.resets.daily", 0L)).append("balance", Operators.ifNull("$economy.balance", 0L)), Operators.let(new Document("streak", Operators.cond(Operators.and(Operators.gte(Operators.nowEpochSecond(), "$$reset"), Operators.lt(Operators.nowEpochSecond(), Operators.add("$$reset", DailyCommand.COOLDOWN))), Operators.add(Operators.ifNull("$economy.streak", 0), 1), 0)), Operators.cond(Operators.lt(Operators.nowEpochSecond(), "$$reset"), "$$balance", Operators.add("$$balance", Operators.add(100L, Operators.multiply(Operators.min(10L, "$$streak"), Operators.add(20L, Operators.multiply(Operators.min(10L, "$$streak"), 5L))))))))), Operators.set("economy.streak", Operators.let(new Document("reset", Operators.ifNull("$economy.resets.daily", 0L)).append("streak", Operators.ifNull("$economy.streak", 0)), Operators.cond(Operators.and(Operators.gte(Operators.nowEpochSecond(), "$$reset"), Operators.lt(Operators.nowEpochSecond(), Operators.add("$$reset", DailyCommand.COOLDOWN))), Operators.add("$$streak", 1), Operators.cond(Operators.lt(Operators.nowEpochSecond(), "$$reset"), "$$streak", 0)))), Operators.set("economy.resets.daily", Operators.let(new Document("reset", Operators.ifNull("$economy.resets.daily", 0L)), Operators.cond(Operators.lt(Operators.nowEpochSecond(), "$$reset"), "$$reset", Operators.add(Operators.nowEpochSecond(), DailyCommand.COOLDOWN)))));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("economy.resets.daily", "economy.streak")).upsert(true);
    EmbedBuilder embed = new EmbedBuilder().setAuthor(event.getAuthor().getName(), null, event.getAuthor().getEffectiveAvatarUrl()).setColor(event.getMember().getColor());
    event.getMongo().findAndUpdateUserById(event.getAuthor().getIdLong(), update, options).thenCompose(data -> {
        Document economy = (data == null ? MongoDatabase.EMPTY_DOCUMENT : data).get("economy", MongoDatabase.EMPTY_DOCUMENT);
        long reset = economy.getEmbedded(List.of("resets", "daily"), 0L), timestamp = Clock.systemUTC().instant().getEpochSecond();
        if (timestamp < reset) {
            event.reply("Slow down! You can collect your daily in " + TimeUtility.LONG_TIME_FORMATTER.parse(reset - timestamp) + " :stopwatch:").queue();
            return CompletableFuture.completedFuture(null);
        }
        int previousStreak = economy.get("streak", 0);
        int streak = timestamp < reset + DailyCommand.COOLDOWN ? previousStreak + 1 : 0;
        long money = 100 + Math.min(10, streak) * (20 + Math.min(10, streak) * 5L);
        embed.setDescription("You have collected your daily money (**$" + money + "**)" + (streak == 0 && previousStreak != streak ? "\n\nIt has been over 2 days since you last collected your daily, your streak has been reset" : streak == 0 ? "" : "\nYou had a bonus of $" + (money - 100) + String.format(" for having a %,d day streak", streak)));
        List<Crate> crates = new ArrayList<>();
        if (streak != 0) {
            for (Crate crate : event.getBot().getEconomyManager().getItems(Crate.class)) {
                if (crate.isHidden()) {
                    continue;
                }
                double randomDouble = event.getBot().getEconomyManager().getRandom().nextDouble();
                if (randomDouble <= Math.min(1D / Math.ceil((crate.getPrice() / 10D / streak) * 4), 1)) {
                    crates.add(crate);
                }
            }
        }
        crates.sort(Comparator.comparingLong(Crate::getPrice).reversed());
        if (!crates.isEmpty()) {
            Crate crate = crates.get(0);
            embed.appendDescription(String.format("\n\nYou also received a `%s` (**$%,d**), it has been added to your items.", crate.getName(), crate.getPrice()));
            List<Bson> crateUpdate = List.of(Operators.set("item", crate.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), 1L)));
            return event.getMongo().updateItem(Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", crate.getId())), crateUpdate, new UpdateOptions().upsert(true));
        }
        return CompletableFuture.completedFuture(UpdateResult.acknowledged(0L, 0L, null));
    }).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception) || result == null) {
            return;
        }
        event.reply(embed.build()).queue();
    });
}
Also used : Document(org.bson.Document) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) CompletableFuture(java.util.concurrent.CompletableFuture) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) UpdateResult(com.mongodb.client.result.UpdateResult) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) com.mongodb.client.model(com.mongodb.client.model) Crate(com.sx4.bot.entities.economy.item.Crate) Comparator(java.util.Comparator) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Crate(com.sx4.bot.entities.economy.item.Crate) ArrayList(java.util.ArrayList) List(java.util.List) Document(org.bson.Document) Bson(org.bson.conversions.Bson)

Example 40 with UserId

use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.

the class SlotCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "bet") AmountArgument amount) {
    Slot[] slots = Slot.getSlots(event.getBot().getEconomyManager().getRandom());
    Slot firstSlot = slots[0], secondSlot = slots[1], thirdSlot = slots[2];
    boolean won = firstSlot == secondSlot && firstSlot == thirdSlot;
    Document betData = new Document("bet", amount.hasDecimal() ? Operators.toLong(Operators.ceil(Operators.multiply(amount.getDecimal(), "$$balance"))) : amount.getAmount());
    List<Bson> update = List.of(Operators.set("economy.winnings", Operators.let(new Document("winnings", Operators.ifNull("$economy.winnings", 0L)).append("balance", Operators.ifNull("$economy.balance", 0L)), Operators.let(betData, Operators.cond(Operators.lt("$$balance", "$$bet"), "$$winnings", Operators.cond(won, Operators.add("$$winnings", Operators.subtract(Operators.toLong(Operators.round(Operators.multiply("$$bet", firstSlot.getMultiplier()))), "$$bet")), Operators.subtract("$$winnings", "$$bet")))))), Operators.set("economy.balance", Operators.let(new Document("balance", Operators.ifNull("$economy.balance", 0L)), Operators.let(betData, Operators.cond(Operators.lt("$$balance", "$$bet"), "$$balance", Operators.cond(won, Operators.add("$$balance", Operators.subtract(Operators.toLong(Operators.round(Operators.multiply("$$bet", firstSlot.getMultiplier()))), "$$bet")), Operators.subtract("$$balance", "$$bet")))))));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("economy.balance")).upsert(true);
    event.getMongo().findAndUpdateUserById(event.getAuthor().getIdLong(), update, options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (data == null) {
            event.replyFailure("You do not have any money").queue();
            return;
        }
        long balance = data.getEmbedded(List.of("economy", "balance"), 0L);
        if (balance == 0L) {
            event.replyFailure("You do not have any money").queue();
            return;
        }
        long bet = amount.getEffectiveAmount(balance);
        if (balance < bet) {
            event.replyFormat("You do not have **$%,d** %s", bet, event.getConfig().getFailureEmote()).queue();
            return;
        }
        long winnings = Math.round(bet * firstSlot.getMultiplier());
        EmbedBuilder embed = new EmbedBuilder().setAuthor("🎰 Slot Machine 🎰").setFooter(event.getAuthor().getAsTag(), event.getAuthor().getEffectiveAvatarUrl()).setThumbnail("https://images.emojiterra.com/twitter/512px/1f3b0.png").setDescription(firstSlot.getAbove().getEmote() + secondSlot.getAbove().getEmote() + thirdSlot.getAbove().getEmote() + "\n" + firstSlot.getEmote() + secondSlot.getEmote() + thirdSlot.getEmote() + "\n" + firstSlot.getBelow().getEmote() + secondSlot.getBelow().getEmote() + thirdSlot.getBelow().getEmote());
        embed.appendDescription(String.format("\n\nYou " + (won ? "won" : "lost") + " **$%,d**!", won ? winnings : bet));
        event.reply(embed.build()).queue();
        Document gameData = new Document("userId", event.getAuthor().getIdLong()).append("slots", List.of(firstSlot.name(), secondSlot.name(), thirdSlot.name())).append("bet", bet).append("winnings", won ? winnings - bet : -bet).append("state", won ? GameState.WIN.getId() : GameState.LOSS.getId()).append("gameId", ObjectId.get()).append("type", GameType.SLOT.getId());
        event.getMongo().insertGame(gameData).whenComplete(MongoDatabase.exceptionally(event));
    });
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Slot(com.sx4.bot.entities.economy.Slot) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) Bson(org.bson.conversions.Bson)

Aggregations

Document (org.bson.Document)46 Bson (org.bson.conversions.Bson)44 Sx4Command (com.sx4.bot.core.Sx4Command)36 Command (com.jockie.bot.core.command.Command)28 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)26 User (net.dv8tion.jda.api.entities.User)26 CommandId (com.sx4.bot.annotations.command.CommandId)25 Examples (com.sx4.bot.annotations.command.Examples)23 Operators (com.sx4.bot.database.mongo.model.Operators)23 List (java.util.List)21 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)20 Permission (net.dv8tion.jda.api.Permission)20 Member (net.dv8tion.jda.api.entities.Member)20 ModuleCategory (com.sx4.bot.category.ModuleCategory)18 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)18 PagedResult (com.sx4.bot.paged.PagedResult)14 Argument (com.jockie.bot.core.argument.Argument)13 com.mongodb.client.model (com.mongodb.client.model)13 ArrayList (java.util.ArrayList)13 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)12