Search in sources :

Example 21 with Item

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

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

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

the class CrateCommand method shop.

@Command(value = "shop", description = "View all the crates you can buy")
@CommandId(411)
@Examples({ "crate shop" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void shop(Sx4CommandEvent event) {
    List<Crate> crates = event.getBot().getEconomyManager().getItems(Crate.class).stream().filter(Predicate.not(Crate::isHidden)).collect(Collectors.toList());
    PagedResult<Crate> paged = new PagedResult<>(event.getBot(), crates).setPerPage(12).setCustomFunction(page -> {
        EmbedBuilder embed = new EmbedBuilder().setDescription("Crates give you a random item, the better the crate the better the chance of a better item").setAuthor("Crate Shop", null, event.getSelfUser().getEffectiveAvatarUrl()).setTitle("Page " + page.getPage() + "/" + page.getMaxPage()).setFooter(PagedResult.DEFAULT_FOOTER_TEXT);
        page.forEach((crate, index) -> embed.addField(crate.getName(), String.format("Price: $%,d\nContents: %s", crate.getPrice(), crate.getContentString()), true));
        return new MessageBuilder().setEmbeds(embed.build());
    });
    paged.execute(event);
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Crate(com.sx4.bot.entities.economy.item.Crate) PagedResult(com.sx4.bot.paged.PagedResult) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 24 with Item

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

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

the class YouTubeNotificationCommand method add.

@Command(value = "add", description = "Add a youtube notification to be posted to a specific channel when the user uploads")
@CommandId(158)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "youtube notification add videos mrbeast", "youtube notification add mrbeast", "youtube notification add #videos pewdiepie" })
public void add(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "youtube channel", endless = true) String channelQuery) {
    if (!event.getBot().getConnectionHandler().isReady()) {
        event.replyFailure("The bot has to be fully started to use this command, try again later").queue();
        return;
    }
    MessageChannel messageChannel = event.getChannel();
    if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
        event.replyFailure("You cannot use this channel type").queue();
        return;
    }
    BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
    boolean id = this.id.matcher(channelQuery).matches();
    boolean search;
    String queryName, query;
    Matcher matcher = this.url.matcher(channelQuery);
    if (!id && matcher.matches()) {
        String path = matcher.group(1);
        search = false;
        queryName = path == null || path.equals("user") ? "forUsername" : "id";
        query = matcher.group(2);
    } else {
        search = !id;
        queryName = id ? "id" : "q";
        query = channelQuery;
    }
    Request channelRequest = new Request.Builder().url("https://www.googleapis.com/youtube/v3/" + (search ? "search" : "channels") + "?key=" + event.getConfig().getYouTube() + "&" + queryName + "=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&part=snippet&type=channel&maxResults=1").build();
    event.getHttpClient().newCall(channelRequest).enqueue((HttpCallback) channelResponse -> {
        Document json = Document.parse(channelResponse.body().string());
        List<Document> items = json.getList("items", Document.class, Collections.emptyList());
        if (items.isEmpty()) {
            event.replyFailure("I could not find that youtube channel").queue();
            return;
        }
        Document item = items.get(0);
        String channelId = search ? item.getEmbedded(List.of("id", "channelId"), String.class) : item.getString("id");
        Document notificationData = new Document("uploaderId", channelId).append("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
        if (!event.getBot().getYouTubeManager().hasExecutor(channelId)) {
            RequestBody body = new MultipartBody.Builder().addFormDataPart("hub.mode", "subscribe").addFormDataPart("hub.topic", "https://www.youtube.com/xml/feeds/videos.xml?channel_id=" + channelId).addFormDataPart("hub.callback", event.getConfig().getBaseUrl() + "/api/youtube").addFormDataPart("hub.verify", "sync").addFormDataPart("hub.verify_token", event.getConfig().getYouTube()).setType(MultipartBody.FORM).build();
            Request request = new Request.Builder().url("https://pubsubhubbub.appspot.com/subscribe").post(body).build();
            event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
                if (response.isSuccessful()) {
                    this.addNotification(event, effectiveChannel.getIdLong(), notificationData).whenComplete((result, exception) -> {
                        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
                        if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                            event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
                            return;
                        }
                        if (ExceptionUtility.sendExceptionally(event, exception)) {
                            return;
                        }
                        event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
                    });
                } else {
                    event.replyFailure("Oops something went wrong there, try again. If this repeats report this to my developer (Message: " + response.body().string() + ")").queue();
                }
            });
        } else {
            this.addNotification(event, effectiveChannel.getIdLong(), notificationData).whenComplete((result, exception) -> {
                Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
                if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                    event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
                    return;
                }
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
            });
        }
    });
}
Also used : Document(org.bson.Document) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) PagedResult(com.sx4.bot.paged.PagedResult) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) ZoneOffset(java.time.ZoneOffset) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Request(okhttp3.Request) InsertOneResult(com.mongodb.client.result.InsertOneResult) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) FormatterManager(com.sx4.bot.formatter.FormatterManager) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) YouTubeChannel(com.sx4.bot.entities.youtube.YouTubeChannel) MultipartBody(okhttp3.MultipartBody) Pattern(java.util.regex.Pattern) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) java.util(java.util) Command(com.jockie.bot.core.command.Command) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) RequestBody(okhttp3.RequestBody) Bson(org.bson.conversions.Bson) AdvancedMessage(com.sx4.bot.annotations.argument.AdvancedMessage) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.mongodb.client.model(com.mongodb.client.model) YouTubeManager(com.sx4.bot.managers.YouTubeManager) FutureUtility(com.sx4.bot.utility.FutureUtility) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) MessageUtility(com.sx4.bot.utility.MessageUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) SelectType(com.sx4.bot.paged.PagedResult.SelectType) YouTubeVideo(com.sx4.bot.entities.youtube.YouTubeVideo) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) JSONArray(org.json.JSONArray) ErrorCategory(com.mongodb.ErrorCategory) Matcher(java.util.regex.Matcher) MongoWriteException(com.mongodb.MongoWriteException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Document(org.bson.Document) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) CompletionException(java.util.concurrent.CompletionException) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) RequestBody(okhttp3.RequestBody) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Sx4Command(com.sx4.bot.core.Sx4Command) Command(com.jockie.bot.core.command.Command) 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