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();
});
}
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());
});
});
}
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);
});
}
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();
});
}
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());
}
Aggregations