use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class GoogleImageCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
boolean nsfw = event.getTextChannel().isNSFW();
event.getBot().getGoogleCache().retrieveResultsByQuery(query, true, nsfw).whenComplete((results, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof ForbiddenException) {
event.replyFailure(cause.getMessage()).queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
String googleUrl = "https://google.com/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&tbm=isch" + (nsfw ? "" : "&safe=active");
PagedResult<GoogleSearchResult> paged = new PagedResult<>(event.getBot(), results).setIndexed(false).setPerPage(4).setCustomFunction(page -> {
List<MessageEmbed> embeds = new ArrayList<>();
page.forEach((result, index) -> {
EmbedBuilder embed = new EmbedBuilder().setTitle("Page " + page.getPage() + "/" + page.getMaxPage(), googleUrl).setAuthor("Google", googleUrl, "http://i.imgur.com/G46fm8J.png").setFooter(PagedResult.DEFAULT_FOOTER_TEXT).setImage(result.getLink());
embeds.add(embed.build());
});
return new MessageBuilder().setEmbeds(embeds);
});
paged.execute(event);
});
}
use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class ReputationCommand method leaderboard.
@Command(value = "leaderboard", aliases = { "lb" }, description = "View the leaderboard for reputation across the bot")
@CommandId(421)
@Redirects({ "leaderboard reputation", "lb rep", "lb reputation", "leaderboard rep" })
@Examples({ "reputation leaderboard", "reputation leaderboard --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void leaderboard(Sx4CommandEvent event, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
List<Bson> pipeline = List.of(Aggregates.project(Projections.computed("reputation", "$reputation.amount")), Aggregates.match(Filters.exists("reputation")), Aggregates.sort(Sorts.descending("reputation")));
event.getMongo().aggregateUsers(pipeline).whenComplete((documents, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
List<Map.Entry<User, Integer>> users = new ArrayList<>();
AtomicInteger userIndex = new AtomicInteger(-1);
int i = 0;
for (Document data : documents) {
User user = event.getShardManager().getUserById(data.getLong("_id"));
if (user == null) {
continue;
}
if (!event.getGuild().isMember(user) && guild) {
continue;
}
i++;
users.add(Map.entry(user, data.getInteger("reputation")));
if (user.getIdLong() == event.getAuthor().getIdLong()) {
userIndex.set(i);
}
}
if (users.isEmpty()) {
event.replyFailure("There are no users which fit into this leaderboard").queue();
return;
}
PagedResult<Map.Entry<User, Integer>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
int rank = userIndex.get();
EmbedBuilder embed = new EmbedBuilder().setTitle("Reputation Leaderboard").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 reputation\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue())));
return new MessageBuilder().setEmbeds(embed.build());
});
paged.execute(event);
});
}
use of com.sx4.bot.paged.PagedResult 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.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class GameCommand method list.
@Command(value = "list", aliases = { "game list", "game list @Shea#6653", "game list Shea" }, description = "Lists basic info on all games a user has played on Sx4")
@CommandId(297)
@Redirects({ "games" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
User user = member == null ? event.getAuthor() : member.getUser();
List<Document> games = event.getMongo().getGames(Filters.eq("userId", user.getIdLong()), Projections.include("type", "state")).into(new ArrayList<>());
if (games.isEmpty()) {
event.replyFailure("That user has not played any games yet").queue();
return;
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), games).setAuthor("Game List", null, user.getEffectiveAvatarUrl()).setIndexed(false).setPerPage(15).setSelect().setDisplayFunction(game -> "`" + GameType.fromId(game.getInteger("type")).getName() + "` - " + StringUtility.title(GameState.fromId(game.getInteger("state")).name()));
paged.execute(event);
}
use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class YouTubeNotificationCommand method list.
@Command(value = "list", description = "View all the notifications you have setup throughout your server")
@CommandId(165)
@Examples({ "youtube notification list" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event) {
List<Document> notifications = event.getMongo().getYouTubeNotifications(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("uploaderId", "channelId", "message")).into(new ArrayList<>());
if (notifications.isEmpty()) {
event.replyFailure("You have no notifications setup in this server").queue();
return;
}
int size = notifications.size();
List<CompletableFuture<Map<String, String>>> futures = new ArrayList<>();
for (int i = 0; i < Math.ceil(size / 50D); i++) {
List<Document> splitNotifications = notifications.subList(i * 50, Math.min((i + 1) * 50, size));
String ids = splitNotifications.stream().map(d -> d.getString("uploaderId")).collect(Collectors.joining(","));
Request request = new Request.Builder().url("https://www.googleapis.com/youtube/v3/channels?key=" + event.getConfig().getYouTube() + "&id=" + ids + "&part=snippet&maxResults=50").build();
CompletableFuture<Map<String, String>> future = new CompletableFuture<>();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
List<Document> items = data.getList("items", Document.class);
Map<String, String> names = new HashMap<>();
for (Document item : items) {
names.put(item.getString("id"), item.getEmbedded(List.of("snippet", "title"), String.class));
}
future.complete(names);
});
futures.add(future);
}
FutureUtility.allOf(futures).whenComplete((maps, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
Map<String, String> names = new HashMap<>();
for (Map<String, String> map : maps) {
names.putAll(map);
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), notifications).setIncreasedIndex(true).setAutoSelect(false).setAuthor("YouTube Notifications", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
String uploaderId = data.getString("uploaderId");
return String.format("%s - [%s](https://youtube.com/channel/%s)", data.getObjectId("_id").toHexString(), names.getOrDefault(uploaderId, "Unknown"), uploaderId);
}).setSelect(SelectType.INDEX);
paged.onSelect(selected -> this.sendStats(event, selected.getSelected()));
paged.execute(event);
});
}
Aggregations