Search in sources :

Example 6 with Suggestion

use of com.sx4.bot.entities.management.Suggestion in project Sx4 by sx4-discord-bot.

the class SuggestionCommand method set.

@Command(value = "set", description = "Sets a suggestion to a specified state")
@CommandId(86)
@Examples({ "suggestion set 5e45ce6d3688b30ee75201ae pending Need some time to think about this", "suggestion set 5e45ce6d3688b30ee75201ae accepted I think this is a great idea", "suggestion 5e45ce6d3688b30ee75201ae set denied Not possible" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void set(Sx4CommandEvent event, @Argument(value = "id | message", acceptEmpty = true) Or<ObjectId, MessageArgument> argument, @Argument(value = "state") String stateName, @Argument(value = "reason", endless = true, nullDefault = true) String reason) {
    Document data = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("suggestion.states", "suggestion.webhook")).get("suggestion", MongoDatabase.EMPTY_DOCUMENT);
    List<Document> states = data.getList("states", Document.class, SuggestionState.DEFAULT_STATES);
    Document state = states.stream().filter(stateData -> stateData.getString("dataName").equalsIgnoreCase(stateName)).findFirst().orElse(null);
    if (state == null) {
        event.replyFailure("You do not have a suggestion state with that name").queue();
        return;
    }
    String stateData = state.getString("dataName");
    Bson update = Updates.combine(reason == null ? Updates.unset("reason") : Updates.set("reason", reason), Updates.set("state", stateData), Updates.set("moderatorId", event.getAuthor().getIdLong()));
    Bson filter = Filters.and(argument.hasFirst() ? Filters.eq("_id", argument.getFirst()) : Filters.eq("messageId", argument.getSecond().getMessageId()), Filters.eq("guildId", event.getGuild().getIdLong()));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("channelId", "authorId", "reason", "state", "suggestion", "messageId", "image"));
    event.getMongo().findAndUpdateSuggestion(filter, update, options).whenComplete((suggestionData, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (suggestionData == null) {
            event.replyFailure("There is no suggestion with that id").queue();
            return;
        }
        String reasonData = suggestionData.getString("reason");
        boolean reasonMatch = reasonData == null && reason == null || (reasonData != null && reasonData.equals(reason));
        if (suggestionData.getString("state").equals(stateData) && reasonMatch) {
            event.replyFailure("That suggestion is already in that state and has the same reason").queue();
            return;
        }
        BaseGuildMessageChannel channel = event.getGuild().getChannelById(BaseGuildMessageChannel.class, suggestionData.getLong("channelId"));
        if (channel == null) {
            event.replyFailure("The channel for that suggestion no longer exists").queue();
            return;
        }
        User author = event.getShardManager().getUserById(suggestionData.getLong("authorId"));
        long messageId = suggestionData.getLong("messageId");
        if (author != null) {
            author.openPrivateChannel().flatMap(privateChannel -> privateChannel.sendMessage("Your suggestion has been updated by a moderator, click the message link to view it\nhttps://discord.com/channels/" + event.getGuild().getIdLong() + "/" + channel.getIdLong() + "/" + messageId)).queue(null, ErrorResponseException.ignore(ErrorResponse.CANNOT_SEND_TO_USER));
        }
        WebhookEmbed embed = Suggestion.getWebhookEmbed(suggestionData.getObjectId("_id"), event.getAuthor(), author, suggestionData.getString("suggestion"), suggestionData.getString("image"), reason, new SuggestionState(state));
        event.getBot().getSuggestionManager().editSuggestion(messageId, channel.getIdLong(), data.get("webhook", MongoDatabase.EMPTY_DOCUMENT), embed);
        event.replySuccess("That suggestion has been set to the `" + stateData + "` state").queue();
    });
}
Also used : Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Suggestion(com.sx4.bot.entities.management.Suggestion) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) ColourUtility(com.sx4.bot.utility.ColourUtility) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.mongodb.client.model(com.mongodb.client.model) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Or(com.sx4.bot.entities.argument.Or) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) Colour(com.sx4.bot.annotations.argument.Colour) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) ObjectId(org.bson.types.ObjectId) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) SuggestionState(com.sx4.bot.entities.management.SuggestionState) Collections(java.util.Collections) ButtonType(com.sx4.bot.entities.interaction.ButtonType) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) SuggestionState(com.sx4.bot.entities.management.SuggestionState) Document(org.bson.Document) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 7 with Suggestion

use of com.sx4.bot.entities.management.Suggestion in project Sx4 by sx4-discord-bot.

the class CSGOSkinCommand method skinBaron.

public void skinBaron(Sx4CommandEvent event, @Argument(value = "skin name", endless = true, nullDefault = true) String query, @Option(value = "sort", description = "You can sort by `expensive`, `cheapest`, `best_deal`, `newest`, `rarest`, `best_float` or `popularity`") Sort sort, @Option(value = "wear", description = "What wear you would like to filter by, options are `fn`, `mw`, `ft`, `ww` and `bs`") Wear wear) {
    Request suggestionRequest = new Request.Builder().url("https://skinbaron.de/api/v2/Browsing/QuickSearch?variantName=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&appId=730&language=en").build();
    event.getHttpClient().newCall(suggestionRequest).enqueue((HttpCallback) suggestionResponse -> {
        Document data = Document.parse(suggestionResponse.body().string());
        List<Document> variants = data.getList("variants", Document.class);
        if (variants.isEmpty()) {
            event.replyFailure("I could not find any skins from that query").queue();
            return;
        }
        PagedResult<Document> suggestions = new PagedResult<>(event.getBot(), variants).setAuthor("SkinBaron", null, "https://skinbaron.de/favicon.png").setDisplayFunction(suggestion -> suggestion.getString("variantName")).setIndexed(true).setAutoSelect(true);
        suggestions.onSelect(select -> {
            Document selected = select.getSelected();
            StringBuilder url = new StringBuilder("https://skinbaron.de/api/v2/Browsing/FilterOffers?appId=730&language=en&otherCurrency=GBP&variantId=" + selected.getInteger("id") + "&sort=" + (sort == null ? Sort.DEAL : sort).getIdentifier());
            if (wear != null) {
                url.append("&wf=").append(wear.getId());
            }
            Request request = new Request.Builder().url(url.toString()).build();
            event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
                Document skinData = Document.parse(response.body().string());
                List<Document> offers = skinData.getList("aggregatedMetaOffers", Document.class);
                if (offers.isEmpty()) {
                    event.replyFailure("There are no skins listed with those filters").queue();
                    return;
                }
                PagedResult<Document> skins = new PagedResult<>(event.getBot(), offers).setPerPage(1).setSelect().setCustomFunction(page -> {
                    EmbedBuilder embed = new EmbedBuilder();
                    embed.setFooter("Skin " + page.getPage() + "/" + page.getMaxPage());
                    page.forEach((d, index) -> {
                        Document skin = d.containsKey("singleOffer") ? d.get("singleOffer", Document.class) : d.get("variant", Document.class);
                        Number steamPrice = d.get("steamMarketPrice", Number.class);
                        String priceString;
                        if (skin.containsKey("itemPrice")) {
                            double price = skin.get("itemPrice", Number.class).doubleValue();
                            if (steamPrice == null) {
                                priceString = String.format("£%,.2f", price);
                            } else {
                                double increase = price - steamPrice.doubleValue();
                                priceString = String.format("~~£%,.2f~~ £%,.2f (%.2f%%)", steamPrice.doubleValue(), price, (increase / (increase > 0 ? steamPrice.doubleValue() : price)) * 100D);
                            }
                        } else {
                            priceString = String.format("£%,.2f", steamPrice.doubleValue());
                        }
                        int tradeLockHours = skin.getInteger("tradeLockHoursLeft", 0);
                        embed.setTitle(skin.getString("localizedName") + (skin.containsKey("statTrakString") ? " (StatTrak)" : ""), "https://skinbaron.de" + d.getString("offerLink"));
                        embed.setImage(skin.getString("imageUrl"));
                        embed.addField("Price", priceString, true);
                        String wearName = skin.getString("localizedExteriorName");
                        if (wearName != null) {
                            embed.addField("Wear", wearName, true);
                            embed.addField("Float", String.format("%.4f", skin.get("wearPercent", Number.class).doubleValue() / 100D), true);
                        }
                        embed.addField("Trade Locked", tradeLockHours == 0 ? "No" : "Yes (" + this.formatter.parse(Duration.ofHours(tradeLockHours)) + ")", true);
                    });
                    return new MessageBuilder().setEmbeds(embed.build());
                });
                skins.execute(event);
            });
        });
        suggestions.execute(event);
    });
}
Also used : Document(org.bson.Document) Uppercase(com.sx4.bot.annotations.argument.Uppercase) HashMap(java.util.HashMap) SkinPortManager(com.sx4.bot.managers.SkinPortManager) PagedResult(com.sx4.bot.paged.PagedResult) ArrayList(java.util.ArrayList) FormBody(okhttp3.FormBody) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) Map(java.util.Map) Option(com.jockie.bot.core.option.Option) TimeFormatter(com.sx4.bot.entities.utility.TimeFormatter) ZoneOffset(java.time.ZoneOffset) Argument(com.jockie.bot.core.argument.Argument) Lowercase(com.sx4.bot.annotations.argument.Lowercase) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) DefaultString(com.sx4.bot.annotations.argument.DefaultString) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) DefaultString(com.sx4.bot.annotations.argument.DefaultString) Document(org.bson.Document) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ArrayList(java.util.ArrayList) List(java.util.List) PagedResult(com.sx4.bot.paged.PagedResult)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)7 Command (com.jockie.bot.core.command.Command)5 PagedResult (com.sx4.bot.paged.PagedResult)5 Document (org.bson.Document)5 Bson (org.bson.conversions.Bson)5 Argument (com.jockie.bot.core.argument.Argument)4 ModuleCategory (com.sx4.bot.category.ModuleCategory)4 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)4 List (java.util.List)4 WebhookClient (club.minnced.discord.webhook.WebhookClient)3 MessageArgument (com.sx4.bot.entities.argument.MessageArgument)3 Suggestion (com.sx4.bot.entities.management.Suggestion)3 Button (net.dv8tion.jda.api.interactions.components.buttons.Button)3 ObjectId (org.bson.types.ObjectId)3 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)2 Option (com.jockie.bot.core.option.Option)2 com.mongodb.client.model (com.mongodb.client.model)2 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)2 Colour (com.sx4.bot.annotations.argument.Colour)2 DefaultString (com.sx4.bot.annotations.argument.DefaultString)2