use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.
the class FishingRodCommand method upgrade.
@Command(value = "upgrade", description = "Upgrade your fishing rod by a certain attribute")
@CommandId(431)
@Examples({ "fishing rod upgrade money", "fishing rod upgrade durability 5" })
public void upgrade(Sx4CommandEvent event, @Argument(value = "upgrade") Upgrade upgrade, @Argument(value = "upgrades") @DefaultNumber(1) @Limit(min = 1, max = 100) int upgrades) {
if (!upgrade.containsType(ItemType.ROD)) {
event.replyFailure("You can not use that upgrade on a fishing rod").queue();
return;
}
event.getMongo().withTransaction(session -> {
Document data = event.getMongo().getItems().find(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.ROD.getId()))).first();
if (data == null) {
event.replyFailure("You do not have a fishing rod").queue();
session.abortTransaction();
return null;
}
Document item = data.get("item", Document.class);
Rod defaultRod = event.getBot().getEconomyManager().getItemById(item.getInteger("id"), Rod.class);
Rod rod = new Rod(item, defaultRod);
int currentUpgrades = rod.getUpgrades();
long price = 0;
for (int i = 0; i < upgrades; i++) {
price += Math.round(0.015D * defaultRod.getPrice() * currentUpgrades++ + 0.025D * defaultRod.getPrice());
}
UpdateResult result = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(price)));
if (result.getModifiedCount() == 0) {
event.replyFormat("You do not have **$%,d** %s", price, event.getConfig().getFailureEmote()).queue();
session.abortTransaction();
return null;
}
List<Bson> update = new ArrayList<>();
update.add(Operators.set("item.upgrades", Operators.add(Operators.ifNull("$item.upgrades", 0), upgrades)));
update.add(Operators.set("item.price", Operators.add("$item.price", Math.round(defaultRod.getPrice() * 0.015D) * upgrades)));
if (upgrade == Upgrade.MONEY) {
int increase = (int) Math.round(defaultRod.getMinYield() * upgrade.getValue()) * upgrades;
update.add(Operators.set("item.minYield", Operators.add("$item.minYield", increase)));
update.add(Operators.set("item.maxYield", Operators.add("$item.maxYield", increase)));
} else if (upgrade == Upgrade.DURABILITY) {
int increase = (int) upgrade.getValue() * upgrades;
update.add(Operators.set("item.durability", Operators.add("$item.durability", increase)));
update.add(Operators.set("item.maxDurability", Operators.add("$item.maxDurability", increase)));
}
event.getMongo().getItems().updateOne(session, Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", rod.getId())), update);
return String.format("You just upgraded %s %d time%s for your `%s` for **$%,d**", upgrade.getName().toLowerCase(), upgrades, (upgrades == 1 ? "" : "s"), rod.getName(), price);
}).whenComplete((message, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception) || message == null) {
return;
}
event.replySuccess(message).queue();
});
}
use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.
the class GiveawayCommand method setup.
@Command(value = "setup", description = "Setup giveaways for users to react to")
@CommandId(47)
@Examples({ "giveaway setup", "giveaway setup #giveaways 1 7d $10 Nitro" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void setup(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "winners") @DefaultNumber(0) @Limit(min = 1) int winners, @Argument(value = "duration", nullDefault = true) Duration duration, @Argument(value = "item", nullDefault = true, endless = true) String item) {
if (channel != null && winners != 0 && duration != null && item != null) {
long seconds = duration.toSeconds();
if (seconds < 1) {
event.replyFailure("The duration of a giveaway cannot be less than 1 second").queue();
return;
}
channel.sendMessageEmbeds(this.getEmbed(winners, seconds, item)).queue(message -> {
message.addReaction("🎉").queue();
Document data = new Document("messageId", message.getIdLong()).append("channelId", channel.getIdLong()).append("guildId", event.getGuild().getIdLong()).append("winnersAmount", winners).append("endAt", Clock.systemUTC().instant().getEpochSecond() + seconds).append("duration", seconds).append("item", item);
event.getMongo().insertGiveaway(data).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getBot().getGiveawayManager().putGiveaway(data, seconds);
event.reply("Your giveaway has been created in " + channel.getAsMention() + " :tada:").queue();
});
});
return;
}
AtomicReference<TextChannel> atomicChannel = new AtomicReference<>();
AtomicInteger atomicWinners = new AtomicInteger();
AtomicReference<Duration> atomicDuration = new AtomicReference<>();
AtomicReference<String> atomicItem = new AtomicReference<>();
CompletableFuture.completedFuture(true).thenCompose($ -> {
if (channel != null) {
atomicChannel.set(channel);
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
event.reply("What channel would you like to start the giveaway in? Type `cancel` at anytime to cancel the creation.").queue(message -> {
Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setPredicate(e -> {
TextChannel textChannel = SearchUtility.getTextChannel(event.getGuild(), e.getMessage().getContentRaw());
if (textChannel != null) {
atomicChannel.set(textChannel);
return true;
}
event.replyFailure("I could not find that channel").queue();
return false;
});
waiter.onCancelled((type) -> {
event.replySuccess("Cancelled").queue();
future.complete(false);
});
waiter.onTimeout(() -> {
event.reply("Response timed out :stopwatch:").queue();
future.complete(false);
});
waiter.onSuccess(e -> future.complete(true));
waiter.start();
});
return future;
}).thenCompose(success -> {
if (!success) {
return CompletableFuture.completedFuture(false);
}
if (winners != 0) {
atomicWinners.set(winners);
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
event.reply("How many winners would you like the giveaway to have?").queue(message -> {
Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
String content = e.getMessage().getContentRaw();
if (NumberUtility.isNumberUnsigned(content)) {
int number = Integer.parseInt(content);
if (number < 1) {
event.replyFailure("You have to have at least 1 winner").queue();
return false;
}
atomicWinners.set(number);
return true;
}
event.replyFailure("That is not a number").queue();
return false;
});
waiter.onCancelled((type) -> {
event.replySuccess("Cancelled").queue();
future.complete(false);
});
waiter.onTimeout(() -> {
event.reply("Response timed out :stopwatch:").queue();
future.complete(false);
});
waiter.onSuccess(e -> future.complete(true));
waiter.start();
});
return future;
}).thenCompose(success -> {
if (!success) {
return CompletableFuture.completedFuture(false);
}
if (duration != null) {
atomicDuration.set(duration);
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
event.reply("How long would you like the giveaway to last?").queue(message -> {
Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
Duration durationReply = TimeUtility.getDurationFromString(e.getMessage().getContentRaw());
if (durationReply.toSeconds() < 1) {
event.replyFailure("The duration of a giveaway cannot be less than 1 second").queue();
return false;
}
atomicDuration.set(durationReply);
return true;
});
waiter.onCancelled((type) -> {
event.replySuccess("Cancelled").queue();
future.complete(false);
});
waiter.onTimeout(() -> {
event.reply("Response timed out :stopwatch:").queue();
future.complete(false);
});
waiter.onSuccess(e -> future.complete(true));
waiter.start();
});
return future;
}).thenCompose(success -> {
if (!success) {
return CompletableFuture.completedFuture(false);
}
if (item != null) {
atomicItem.set(item);
return CompletableFuture.completedFuture(true);
}
CompletableFuture<Boolean> future = new CompletableFuture<>();
event.reply("What would you like to giveaway?").queue(message -> {
Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
String content = e.getMessage().getContentRaw();
if (content.equalsIgnoreCase("cancel")) {
return false;
}
atomicItem.set(content);
return true;
});
waiter.onCancelled((type) -> {
event.replySuccess("Cancelled").queue();
future.complete(false);
});
waiter.onTimeout(() -> {
event.reply("Response timed out :stopwatch:").queue();
future.complete(false);
});
waiter.onSuccess(e -> future.complete(true));
waiter.start();
});
return future;
}).thenAccept(success -> {
if (!success) {
return;
}
TextChannel channelFuture = atomicChannel.get();
int winnersFuture = atomicWinners.get();
long durationFuture = atomicDuration.get().toSeconds();
String itemFuture = atomicItem.get();
channelFuture.sendMessageEmbeds(this.getEmbed(winnersFuture, durationFuture, itemFuture)).queue(message -> {
message.addReaction("🎉").queue();
Document data = new Document("messageId", message.getIdLong()).append("channelId", channelFuture.getIdLong()).append("guildId", event.getGuild().getIdLong()).append("winnersAmount", winnersFuture).append("endAt", Clock.systemUTC().instant().getEpochSecond() + durationFuture).append("duration", durationFuture).append("item", itemFuture);
event.getMongo().insertGiveaway(data).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getBot().getGiveawayManager().putGiveaway(data, durationFuture);
event.reply("Your giveaway has been created in " + channelFuture.getAsMention() + " :tada:").queue();
});
});
});
}
use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.
the class AntiInviteCommand method attempts.
/*@Command(value="set", description="Sets the amount of attempts a user has")
@CommandId(459)
@Examples({"antiinvite set @Shea#6653 0", "antiinvite set Shea 3", "antiinvite set 402557516728369153 2"})
@AuthorPermissions(permissions={Permission.MANAGE_SERVER})
public void set(Sx4CommandEvent event, @Argument(value="user") Member member, @Argument(value="attempts") int attempts) {
Bson filter = Filters.and(Filters.eq("regexId", AntiInviteCommand.REGEX_ID), Filters.eq("userId", member.getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()));
CompletableFuture<Document> future;
if (attempts == 0) {
future = event.getMongo().findAndDeleteRegexAttempt(filter);
} else {
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(Projections.include("attempts")).returnDocument(ReturnDocument.BEFORE).upsert(true);
future = event.getMongo().findAndUpdateRegexAttempt(filter, Updates.set("attempts", attempts), options);
}
future.whenComplete((data, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (data == null) {
event.replyFailure("You do not have anti-invite setup").queue();
return;
}
if (data.getInteger("attempts") == attempts) {
event.replyFailure("That users attempts were already set to that").queue();
return;
}
if (attempts == 0) {
event.getBot().getAntiRegexManager().clearAttempts(AntiInviteCommand.REGEX_ID, member.getIdLong());
} else {
event.getBot().getAntiRegexManager().setAttempts(AntiInviteCommand.REGEX_ID, member.getIdLong(), attempts);
}
event.replySuccess("**" + member.getUser().getAsTag() + "** has had their attempts set to **" + attempts + "**").queue();
});
}*/
@Command(value = "attempts", description = "Sets the amount of attempts needed for the mod action to execute")
@CommandId(307)
@Examples({ "antiinvite attempts 3", "antiinvite attempts 1" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void attempts(Sx4CommandEvent event, @Argument(value = "attempts") @Limit(min = 1) int attempts) {
Bson filter = Filters.and(Filters.eq("regexId", AntiInviteCommand.REGEX_ID), Filters.eq("guildId", event.getGuild().getIdLong()));
event.getMongo().updateRegex(filter, Updates.set("attempts.amount", attempts)).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (result.getMatchedCount() == 0) {
event.replyFailure("You do not have anti-invite setup").queue();
return;
}
if (result.getModifiedCount() == 0) {
event.replyFailure("Your attempts where already set to that").queue();
return;
}
event.replySuccess("Attempts to a mod action have been set to **" + attempts + "**").queue();
});
}
use of com.sx4.bot.annotations.argument.Limit 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);
}
use of com.sx4.bot.annotations.argument.Limit in project Sx4 by sx4-discord-bot.
the class TemplateCommand method add.
@Command(value = "add", description = "Add a template in the current server")
@CommandId(255)
@Examples({ "template add tos Broke ToS", "template add spam Spamming excessively" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void add(Sx4CommandEvent event, @Argument(value = "template") @Limit(max = 100) String template, @Argument(value = "reason", endless = true) String reason) {
Document data = new Document("template", template).append("reason", reason).append("guildId", event.getGuild().getIdLong());
event.getMongo().insertTemplate(data).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 template with that name").queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.replySuccess("That template has been added with id `" + result.getInsertedId().asObjectId().getValue().toHexString() + "`").queue();
});
}
Aggregations