Search in sources :

Example 1 with Cooldown

use of com.jockie.bot.core.command.Command.Cooldown in project Sx4 by sx4-discord-bot.

the class MarriageCommand method add.

@Command(value = "add", description = "Propose to a user and marry them if they accept")
@CommandId(268)
@Redirects({ "marry" })
@Cooldown(60)
@CooldownMessage("You already have a pending marriage :no_entry:")
@Examples({ "marriage add @Shea#6653", "marriage add Shea", "marriage add 402557516728369153" })
public void add(Sx4CommandEvent event, @Argument(value = "user", endless = true) Member member) {
    User author = event.getAuthor();
    if (member.getUser().isBot()) {
        event.replyFailure("You cannot marry bots").queue();
        return;
    }
    Bson checkFilter = Filters.or(Filters.eq("proposerId", author.getIdLong()), Filters.eq("partnerId", author.getIdLong()), Filters.eq("proposerId", member.getIdLong()), Filters.eq("partnerId", member.getIdLong()));
    List<Document> marriages = event.getMongo().getMarriages(checkFilter, Projections.include("partnerId", "proposerId")).into(new ArrayList<>());
    long userCount = marriages.stream().filter(d -> d.getLong("proposerId") == author.getIdLong() || d.getLong("partnerId") == author.getIdLong()).count();
    if (userCount >= 5) {
        event.removeCooldown();
        event.replyFailure("You cannot marry more than 5 users").queue();
        return;
    }
    long memberCount = marriages.stream().filter(d -> d.getLong("proposerId") == member.getIdLong() || d.getLong("partnerId") == member.getIdLong()).count();
    if (memberCount >= 5) {
        event.removeCooldown();
        event.replyFailure("That user is already married to 5 users").queue();
        return;
    }
    List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
    event.reply(member.getAsMention() + ", **" + author.getName() + "** would like to marry you! Do you accept?").allowedMentions(EnumSet.of(Message.MentionType.USER)).setActionRow(buttons).submit().thenCompose(message -> {
        return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, member.getUser())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, member.getUser())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
    }).whenComplete((e, exception) -> {
        event.removeCooldown();
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof CancelException) {
            GenericEvent cancelEvent = ((CancelException) cause).getEvent();
            if (cancelEvent != null) {
                ((ButtonClickEvent) cancelEvent).reply("Better luck next time " + author.getName() + " :broken_heart:").queue();
            }
            return;
        } else if (cause instanceof TimeoutException) {
            event.reply("Timed out :stopwatch:").queue();
            return;
        } else if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        Bson filter = Filters.or(Filters.and(Filters.eq("proposerId", member.getIdLong()), Filters.eq("partnerId", author.getIdLong())), Filters.and(Filters.eq("proposerId", author.getIdLong()), Filters.eq("partnerId", member.getIdLong())));
        event.getMongo().updateMarriage(filter, Updates.combine(Updates.setOnInsert("proposerId", author.getIdLong()), Updates.setOnInsert("partnerId", member.getIdLong()))).whenComplete((result, databaseException) -> {
            if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                return;
            }
            if (result.getMatchedCount() != 0) {
                e.reply("You're already married to that user " + event.getConfig().getFailureEmote()).queue();
                return;
            }
            e.reply("You're now married to " + member.getAsMention() + " :tada: :heart:").queue();
        });
    });
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) Projections(com.mongodb.client.model.Projections) Cooldown(com.jockie.bot.core.command.Command.Cooldown) CommandId(com.sx4.bot.annotations.command.CommandId) Member(net.dv8tion.jda.api.entities.Member) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) Redirects(com.sx4.bot.annotations.command.Redirects) Alternative(com.sx4.bot.entities.argument.Alternative) ButtonUtility(com.sx4.bot.utility.ButtonUtility) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) ZoneOffset(java.time.ZoneOffset) EnumSet(java.util.EnumSet) Argument(com.jockie.bot.core.argument.Argument) Message(net.dv8tion.jda.api.entities.Message) Sx4Command(com.sx4.bot.core.Sx4Command) Updates(com.mongodb.client.model.Updates) CooldownMessage(com.sx4.bot.annotations.command.CooldownMessage) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) Sorts(com.mongodb.client.model.Sorts) DateTimeFormatter(java.time.format.DateTimeFormatter) StringJoiner(java.util.StringJoiner) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) Bson(org.bson.conversions.Bson) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Redirects(com.sx4.bot.annotations.command.Redirects) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Cooldown(com.jockie.bot.core.command.Command.Cooldown) CooldownMessage(com.sx4.bot.annotations.command.CooldownMessage) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 2 with Cooldown

use of com.jockie.bot.core.command.Command.Cooldown in project Sx4 by sx4-discord-bot.

the class SteamCommand method game.

@Command(value = "game", description = "View information about a game on steam")
@CommandId(34)
@Examples({ "steam game Grand Theft Auto", "steam game 1293830", "steam game https://store.steampowered.com/app/1293830/Forza_Horizon_4/" })
@Cooldown(5)
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void game(Sx4CommandEvent event, @Argument(value = "query", endless = true, nullDefault = true) String query, @Option(value = "random", description = "Gets a random game") boolean random) {
    if (query == null && !random) {
        event.replyHelp().queue();
        return;
    }
    SteamGameCache cache = event.getBot().getSteamGameCache();
    if (cache.getGames().isEmpty()) {
        event.replyFailure("The steam cache is currently empty, try again").queue();
        return;
    }
    Matcher urlMatcher;
    List<Document> games;
    if (query == null) {
        List<Document> cacheGames = cache.getGames();
        games = List.of(cacheGames.get(event.getRandom().nextInt(cacheGames.size())));
    } else if (NumberUtility.isNumberUnsigned(query)) {
        games = List.of(new Document("appid", Integer.parseInt(query)));
    } else if ((urlMatcher = this.gamePattern.matcher(query)).matches()) {
        games = List.of(new Document("appid", Integer.parseInt(urlMatcher.group(1))));
    } else {
        games = cache.getGames(query);
        if (games.isEmpty()) {
            event.replyFailure("I could not find any games with that query").queue();
            return;
        }
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), games).setAuthor("Steam Search", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setIncreasedIndex(true).setAutoSelect(true).setTimeout(60).setDisplayFunction(game -> game.getString("name"));
    paged.onSelect(select -> {
        Document game = select.getSelected();
        int appId = game.getInteger("appid");
        Request request = new Request.Builder().url("https://store.steampowered.com/api/appdetails?cc=gb&appids=" + appId).build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            Document json = Document.parse(response.body().string()).get(String.valueOf(appId), Document.class);
            if (!json.getBoolean("success")) {
                event.replyFailure("Steam failed to get data for that game").queue();
                return;
            }
            List<MessageEmbed> embeds = new ArrayList<>();
            Document gameInfo = json.get("data", Document.class);
            String description = Jsoup.parse(gameInfo.getString("short_description")).text();
            String price;
            if (gameInfo.containsKey("price_overview")) {
                Document priceOverview = gameInfo.get("price_overview", Document.class);
                double initialPrice = priceOverview.getInteger("initial") / 100D, finalPrice = priceOverview.getInteger("final") / 100D;
                price = initialPrice == finalPrice ? String.format("£%,.2f", finalPrice) : String.format("~~£%,.2f~~ £%,.2f (-%d%%)", initialPrice, finalPrice, priceOverview.getInteger("discount_percent"));
            } else {
                price = gameInfo.getBoolean("is_free") ? "Free" : "Unknown";
            }
            EmbedBuilder embed = new EmbedBuilder();
            embed.setDescription(description);
            embed.setTitle(gameInfo.getString("name"), "https://store.steampowered.com/app/" + appId);
            embed.setAuthor("Steam", "https://steamcommunity.com", "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png");
            embed.setImage(gameInfo.getString("header_image"));
            embed.addField("Price", price, true);
            embed.setFooter("Developed by " + (gameInfo.containsKey("developers") ? String.join(", ", gameInfo.getList("developers", String.class)) : "Unknown"), null);
            Document releaseDate = gameInfo.get("release_date", Document.class);
            String date = releaseDate.getString("date");
            embed.addField("Release Date", String.format("%s%s", date.isBlank() ? "Unknown" : date, releaseDate.getBoolean("coming_soon") ? " (Coming Soon)" : ""), true);
            Object age = gameInfo.get("required_age");
            embed.addField("Required Age", age instanceof Integer ? ((int) age) == 0 ? "No Age Restriction" : String.valueOf((int) age) : (String) age, true);
            embed.addField("Recommendations", String.format("%,d", gameInfo.getEmbedded(List.of("recommendations", "total"), 0)), true);
            embed.addField("Supported Languages", gameInfo.containsKey("supported_languages") ? Jsoup.parse(gameInfo.getString("supported_languages")).text() : "Unknown", true);
            List<Document> genres = gameInfo.getList("genres", Document.class);
            embed.addField("Genres", genres == null ? "None" : genres.stream().map(genre -> genre.getString("description")).collect(Collectors.joining("\n")), true);
            embeds.add(embed.build());
            gameInfo.getList("screenshots", Document.class).stream().map(d -> d.getString("path_thumbnail")).limit(3).forEach(thumbnail -> {
                embeds.add(new MessageEmbed("https://store.steampowered.com/app/" + appId, null, null, EmbedType.RICH, null, Role.DEFAULT_COLOR_RAW, null, null, null, null, null, new MessageEmbed.ImageInfo(thumbnail, null, 0, 0), List.of()));
            });
            event.getChannel().sendMessageEmbeds(embeds).queue();
        });
    });
    paged.onTimeout(() -> event.reply("Response timed out :stopwatch:").queue());
    paged.execute(event);
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) CommandId(com.sx4.bot.annotations.command.CommandId) Cooldown(com.jockie.bot.core.command.Command.Cooldown) PagedResult(com.sx4.bot.paged.PagedResult) EmbedType(net.dv8tion.jda.api.entities.EmbedType) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) Role(net.dv8tion.jda.api.entities.Role) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Request(okhttp3.Request) HmacUtility(com.sx4.bot.utility.HmacUtility) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) Examples(com.sx4.bot.annotations.command.Examples) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) InvalidKeyException(java.security.InvalidKeyException) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Jsoup(org.jsoup.Jsoup) Pattern(java.util.regex.Pattern) StringUtility(com.sx4.bot.utility.StringUtility) JSONArray(org.json.JSONArray) SteamGameCache(com.sx4.bot.cache.SteamGameCache) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Matcher(java.util.regex.Matcher) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) SteamGameCache(com.sx4.bot.cache.SteamGameCache) JSONObject(org.json.JSONObject) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Cooldown(com.jockie.bot.core.command.Command.Cooldown) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Aggregations

Argument (com.jockie.bot.core.argument.Argument)2 Command (com.jockie.bot.core.command.Command)2 Cooldown (com.jockie.bot.core.command.Command.Cooldown)2 Projections (com.mongodb.client.model.Projections)2 CommandId (com.sx4.bot.annotations.command.CommandId)2 Examples (com.sx4.bot.annotations.command.Examples)2 ModuleCategory (com.sx4.bot.category.ModuleCategory)2 Sx4Command (com.sx4.bot.core.Sx4Command)2 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)2 PagedResult (com.sx4.bot.paged.PagedResult)2 Instant (java.time.Instant)2 DateTimeFormatter (java.time.format.DateTimeFormatter)2 Collectors (java.util.stream.Collectors)2 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)2 Document (org.bson.Document)2 Option (com.jockie.bot.core.option.Option)1 Filters (com.mongodb.client.model.Filters)1 Sorts (com.mongodb.client.model.Sorts)1 Updates (com.mongodb.client.model.Updates)1 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)1