Search in sources :

Example 6 with Limit

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

the class TTSCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) @Limit(max = 200) String query) {
    Request request = new Request.Builder().url("https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en-gb&q=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        event.replyFile(response.body().bytes(), query + ".mp3").queue();
    });
}
Also used : ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) URLEncoder(java.net.URLEncoder) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Permission(net.dv8tion.jda.api.Permission) StandardCharsets(java.nio.charset.StandardCharsets) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) Request(okhttp3.Request)

Example 7 with Limit

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

the class GuessTheNumberCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true) Member member, @Option(value = "min", description = "Choose the minimum number of the range") @Limit(min = 1) @DefaultNumber(1) int min, @Option(value = "max", description = "Choose the maximum number of the range") @Limit(min = 2) @DefaultNumber(50) int max) {
    User opponent = member.getUser();
    if (opponent.isBot()) {
        event.replyFailure("You cannot play against bots").queue();
        return;
    }
    if (opponent.getIdLong() == event.getAuthor().getIdLong()) {
        event.replyFailure("You cannot play against yourself").queue();
        return;
    }
    List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
    event.reply(opponent.getAsMention() + ", do you want to play guess the number with **" + event.getAuthor().getName() + "**?").allowedMentions(EnumSet.of(Message.MentionType.USER)).setActionRow(buttons).submit().thenCompose(message -> {
        return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, opponent)).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, opponent)).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
    }).whenComplete((confirmEvent, confirmException) -> {
        Throwable confirmCause = confirmException instanceof CompletionException ? confirmException.getCause() : confirmException;
        if (confirmCause instanceof CancelException) {
            GenericEvent cancelEvent = ((CancelException) confirmCause).getEvent();
            if (cancelEvent != null) {
                ((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
            }
            return;
        } else if (confirmCause instanceof TimeoutException) {
            event.reply("Timed out :stopwatch:").queue();
            return;
        }
        confirmEvent.deferEdit().queue();
        CompletableFuture<MessageReceivedEvent> authorFuture = event.getAuthor().openPrivateChannel().submit().thenCompose(channel -> channel.sendMessage("Send a number between **" + min + "** and **" + max + "** or `cancel` to cancel").submit()).thenCompose(message -> {
            return new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(event.getAuthor().getIdLong(), message.getChannel().getIdLong()).setTimeout(30).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setPredicate(e -> {
                int number;
                try {
                    number = Integer.parseInt(e.getMessage().getContentRaw());
                } catch (NumberFormatException exception) {
                    return false;
                }
                return number >= min && number <= max;
            }).start();
        });
        CompletableFuture<MessageReceivedEvent> opponentFuture = opponent.openPrivateChannel().submit().thenCompose(channel -> channel.sendMessage("Send a number between **" + min + "** and **" + max + "** or `cancel` to cancel").submit()).thenCompose(message -> {
            return new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(opponent.getIdLong(), message.getChannel().getIdLong()).setTimeout(30).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setPredicate(e -> {
                int number;
                try {
                    number = Integer.parseInt(e.getMessage().getContentRaw());
                } catch (NumberFormatException exception) {
                    return false;
                }
                return number >= min && number <= max;
            }).start();
        });
        authorFuture.whenComplete((messageEvent, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof CancelException) {
                opponentFuture.cancel(true);
                if (((CancelException) cause).getType() == CancelType.USER) {
                    event.getAuthor().openPrivateChannel().flatMap(channel -> channel.sendMessage("Cancelled " + event.getConfig().getSuccessEmote())).queue();
                }
                event.replyFailure("**" + event.getAuthor().getAsTag() + "** cancelled their response").queue();
                return;
            } else if (cause instanceof TimeoutException) {
                opponentFuture.cancel(true);
                event.replyFailure("**" + event.getAuthor().getAsTag() + "** took too long to respond").queue();
                return;
            } else if (cause instanceof ErrorResponseException) {
                opponentFuture.cancel(true);
                event.replyFailure("I could not send a message to **" + event.getAuthor().getAsTag() + "**").queue();
                return;
            }
            messageEvent.getChannel().sendMessage("Your number has been received, results will be sent in " + event.getTextChannel().getAsMention()).queue();
        });
        opponentFuture.whenComplete((messageEvent, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof CancelException) {
                authorFuture.cancel(true);
                if (((CancelException) cause).getType() == CancelType.USER) {
                    opponent.openPrivateChannel().flatMap(channel -> channel.sendMessage("Cancelled " + event.getConfig().getSuccessEmote())).queue();
                }
                event.replyFailure("**" + opponent.getAsTag() + "** cancelled their response").queue();
                return;
            } else if (cause instanceof TimeoutException) {
                authorFuture.cancel(true);
                event.replyFailure("**" + opponent.getAsTag() + "** took too long to respond").queue();
                return;
            } else if (cause instanceof ErrorResponseException) {
                authorFuture.cancel(true);
                event.replyFailure("I could not send a message to **" + opponent.getAsTag() + "**").queue();
                return;
            }
            messageEvent.getChannel().sendMessage("Your number has been received, results will be sent in " + event.getTextChannel().getAsMention()).queue();
        });
        CompletableFuture.allOf(authorFuture, opponentFuture).whenComplete((result, exception) -> {
            if (exception != null) {
                return;
            }
            MessageReceivedEvent authorEvent = authorFuture.join(), opponentEvent = opponentFuture.join();
            ObjectId gameId = ObjectId.get();
            int authorNumber = Integer.parseInt(authorEvent.getMessage().getContentRaw());
            int opponentNumber = Integer.parseInt(opponentEvent.getMessage().getContentRaw());
            int randomNumber = event.getRandom().nextInt(max) + 1;
            Document authorData = new Document("userId", event.getAuthor().getIdLong()).append("gameId", gameId).append("type", GameType.GUESS_THE_NUMBER.getId()).append("choice", authorNumber).append("answer", randomNumber);
            Document opponentData = new Document("userId", opponent.getIdLong()).append("gameId", gameId).append("type", GameType.GUESS_THE_NUMBER.getId()).append("choice", authorNumber).append("answer", randomNumber);
            int authorDifference = Math.abs(authorNumber - randomNumber), opponentDifference = Math.abs(opponentNumber - randomNumber);
            StringBuilder content = new StringBuilder("The random number was **" + randomNumber + "**\n" + opponent.getName() + "'s number was **" + opponentNumber + "**\n" + event.getAuthor().getName() + "'s number was **" + authorNumber + "**\n\n");
            if (authorDifference == opponentDifference) {
                content.append("You both guessed the same number, It was a draw!");
                authorData.append("state", GameState.DRAW.getId());
                opponentData.append("state", GameState.DRAW.getId());
            } else if (authorDifference > opponentDifference) {
                content.append(opponent.getName()).append(" won! They were the closest to ").append(randomNumber);
                authorData.append("state", GameState.LOSS.getId());
                opponentData.append("state", GameState.WIN.getId());
            } else {
                content.append(event.getAuthor().getName()).append(" won! They were the closest to ").append(randomNumber);
                authorData.append("state", GameState.WIN.getId());
                opponentData.append("state", GameState.LOSS.getId());
            }
            event.reply(content.toString()).queue();
            event.getMongo().insertManyGames(List.of(authorData, opponentData)).whenComplete(MongoDatabase.exceptionally());
        });
    });
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) ButtonUtility(com.sx4.bot.utility.ButtonUtility) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) Option(com.jockie.bot.core.option.Option) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) GameState(com.sx4.bot.entities.games.GameState) EnumSet(java.util.EnumSet) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) CancelType(com.sx4.bot.waiter.Waiter.CancelType) Message(net.dv8tion.jda.api.entities.Message) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) GameType(com.sx4.bot.entities.games.GameType) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) ObjectId(org.bson.types.ObjectId) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) User(net.dv8tion.jda.api.entities.User) ObjectId(org.bson.types.ObjectId) Document(org.bson.Document) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException)

Example 8 with Limit

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

the class BotListCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "page") @DefaultNumber(1) @Limit(min = 1, max = 50) int page) {
    Request request = new Request.Builder().url("https://top.gg/api/bots?sort=server_count&limit=500&fields=username,server_count,id").addHeader("Authorization", event.getConfig().getTopGG()).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document data = Document.parse(response.body().string());
        List<Document> results = data.getList("results", Document.class);
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), results).setPage(page).setAuthor("Bot List", null, "https://imgur.com/HlfRQ3g.png").setIncreasedIndex(true).setSelect().setDisplayFunction(bot -> String.format("[%s](https://top.gg/bot/%s) - **%,d** servers", bot.getString("username"), bot.getString("id"), bot.getInteger("server_count")));
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Permission(net.dv8tion.jda.api.Permission) PagedResult(com.sx4.bot.paged.PagedResult) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) Request(okhttp3.Request) List(java.util.List) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult)

Example 9 with Limit

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

the class CropCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "image url") @ImageUrl String imageUrl, @Argument(value = "width") @Limit(min = 0) double width, @Argument(value = "height") @Limit(min = 0) @DefaultNumber(1) double height) {
    Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("crop")).addQuery("w", width).addQuery("h", height).addQuery("image", imageUrl).build(event.getConfig().getImageWebserver());
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        ImageUtility.getImageMessage(event, response, (body, error) -> {
            if (error == ImageError.INVALID_QUERY_VALUE) {
                return event.replyFailure(body.getString("message"));
            }
            return null;
        }).queue();
    });
}
Also used : Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) ImageError(com.sx4.bot.entities.image.ImageError) Permission(net.dv8tion.jda.api.Permission) ModuleCategory(com.sx4.bot.category.ModuleCategory) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest)

Example 10 with Limit

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

the class TweetCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user") Member member, @Argument(value = "text", endless = true) @Limit(max = 280) String text) {
    User user = member.getUser();
    Guild guild = event.getGuild();
    int memberCount = guild.getMemberCount();
    int likes = event.getRandom().nextInt(memberCount);
    List<Member> members = guild.getMembers();
    List<String> urls = new ArrayList<>();
    for (int i = 0; i < Math.min(10, likes); i++) {
        urls.add(members.get(event.getRandom().nextInt(memberCount)).getUser().getEffectiveAvatarUrl() + "?size=64");
    }
    Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("tweet")).addField("display_name", member.getEffectiveName()).addField("name", user.getName()).addField("avatar", user.getEffectiveAvatarUrl() + "?size=128").addField("retweets", event.getRandom().nextInt(memberCount)).addField("likes", likes).addField("text", ImageUtility.escapeMentions(guild, text)).addField("urls", urls).build(event.getConfig().getImageWebserver());
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
}
Also used : Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Guild(net.dv8tion.jda.api.entities.Guild) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) User(net.dv8tion.jda.api.entities.User) ImageRequest(com.sx4.bot.entities.image.ImageRequest) ArrayList(java.util.ArrayList) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Guild(net.dv8tion.jda.api.entities.Guild) Member(net.dv8tion.jda.api.entities.Member)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)25 Argument (com.jockie.bot.core.argument.Argument)20 ModuleCategory (com.sx4.bot.category.ModuleCategory)20 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)20 Permission (net.dv8tion.jda.api.Permission)19 Limit (com.sx4.bot.annotations.argument.Limit)17 Document (org.bson.Document)17 HttpCallback (com.sx4.bot.http.HttpCallback)14 Request (okhttp3.Request)13 Command (com.jockie.bot.core.command.Command)11 Bson (org.bson.conversions.Bson)11 CommandId (com.sx4.bot.annotations.command.CommandId)10 Examples (com.sx4.bot.annotations.command.Examples)10 List (java.util.List)10 DefaultNumber (com.sx4.bot.annotations.argument.DefaultNumber)9 PagedResult (com.sx4.bot.paged.PagedResult)9 Member (net.dv8tion.jda.api.entities.Member)9 ImageRequest (com.sx4.bot.entities.image.ImageRequest)8 ImageUtility (com.sx4.bot.utility.ImageUtility)8 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)8