use of com.jockie.bot.core.option.Option in project Sx4 by sx4-discord-bot.
the class AvatarCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member, @Option(value = "global", description = "Forced to show their global avatar") boolean global) {
Member effectiveMember = member == null ? event.getMember() : member;
User user = effectiveMember.getUser();
String avatar = global ? user.getEffectiveAvatarUrl() : effectiveMember.getEffectiveAvatarUrl();
Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("median-colour")).addQuery("image", avatar).build(event.getConfig().getImageWebserver());
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
if (!response.isSuccessful()) {
ImageUtility.getErrorMessage(event.getTextChannel(), response.code(), response.body().string()).queue();
return;
}
Document data = Document.parse(response.body().string());
String sizedAvatar = avatar + "?size=1024";
EmbedBuilder embed = new EmbedBuilder().setImage(sizedAvatar).setColor(data.getInteger("colour")).setAuthor(user.getAsTag(), sizedAvatar, user.getEffectiveAvatarUrl());
event.reply(embed.build()).queue();
});
}
use of com.jockie.bot.core.option.Option 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);
});
}
use of com.jockie.bot.core.option.Option in project Sx4 by sx4-discord-bot.
the class DiscordCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user", nullDefault = true) Member member, @Argument(value = "text | message id", endless = true) @Limit(max = 250) Or<MessageArgument, String> option, @Option(value = "light", description = "Sets the discord theme to light") boolean light) {
if (member == null && option.hasSecond()) {
event.replyFailure("You need to provide a user when not giving a message").queue();
return;
}
this.getContext(option, member).thenAccept(pair -> {
Member effectiveMember = pair.getLeft();
User user = effectiveMember.getUser();
String text = pair.getRight();
Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("discord")).addField("name", effectiveMember.getEffectiveName()).addField("avatar", user.getEffectiveAvatarUrl()).addField("bot", user.isBot()).addField("dark_theme", !light).addField("colour", effectiveMember.getColorRaw()).addField("text", text).addAllFields(this.getMentions(event.getShardManager(), event.getGuild(), text)).build(event.getConfig().getImageWebserver());
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
});
}
use of com.jockie.bot.core.option.Option in project Sx4 by sx4-discord-bot.
the class LeaderboardCommand method votes.
@Command(value = "votes", description = "View the leaderboard for the votes of users")
@CommandId(374)
@Examples({ "leaderboard votes", "leaderboard votes December", "leaderboard votes July --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void votes(Sx4CommandEvent event, @Argument(value = "month", nullDefault = true) Month month, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
StringBuilder url = new StringBuilder(event.getConfig().getVoteWebserverUrl("votesCount"));
int year;
if (month != null) {
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
year = month.getValue() > now.getMonthValue() ? now.getYear() - 1 : now.getYear();
OffsetDateTime monthStart = OffsetDateTime.of(year, month.getValue(), 1, 0, 0, 0, 0, ZoneOffset.UTC);
url.append("?after=").append(monthStart.toInstant().getEpochSecond()).append("&before=").append(monthStart.plusMonths(1).toInstant().getEpochSecond());
} else {
year = 0;
}
Request request = new Request.Builder().url(url.toString()).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
List<Document> votes = data.getList("votes", Document.class);
List<Map.Entry<User, Integer>> users = new ArrayList<>();
AtomicInteger userIndex = new AtomicInteger(-1);
int i = 0;
for (Document vote : votes) {
User user = event.getShardManager().getUserById(vote.getString("id"));
if (user == null) {
continue;
}
if (!event.getGuild().isMember(user) && guild) {
continue;
}
i++;
users.add(Map.entry(user, vote.getInteger("count")));
if (user.getIdLong() == event.getAuthor().getIdLong()) {
userIndex.set(i);
}
}
PagedResult<Map.Entry<User, Integer>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
int rank = userIndex.get();
EmbedBuilder embed = new EmbedBuilder().setTitle("Votes Leaderboard" + (month == null ? "" : " for " + month.getDisplayName(TextStyle.FULL, Locale.UK) + " " + year)).setFooter(event.getAuthor().getName() + "'s Rank: " + (rank == -1 ? "N/A" : NumberUtility.getSuffixed(rank)) + " | Page " + page.getPage() + "/" + page.getMaxPage(), event.getAuthor().getEffectiveAvatarUrl());
page.forEach((entry, index) -> embed.appendDescription(String.format("%d. `%s` - %,d vote%s\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue(), entry.getValue() == 1 ? "" : "s")));
return new MessageBuilder().setEmbeds(embed.build());
});
paged.execute(event);
});
}
use of com.jockie.bot.core.option.Option 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);
}
Aggregations