use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class PremiumCommand method leaderboard.
@Command(value = "leaderboard", aliases = { "lb" }, description = "Leaderboard for Sx4s biggest donors")
@CommandId(446)
@Redirects({ "lb premium", "leaderboard premium" })
@Examples({ "premium leaderboard" })
public void leaderboard(Sx4CommandEvent event, @Option(value = "server", aliases = { "guild" }, description = "Filters the results to only people in the current server") boolean guild) {
List<Bson> pipeline = List.of(Aggregates.project(Projections.computed("total", "$premium.total")), Aggregates.match(Filters.and(Filters.exists("total"), Filters.ne("total", 0))), Aggregates.sort(Sorts.descending("total")));
event.getMongoMain().aggregateUsers(pipeline).whenCompleteAsync((documents, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
List<Map.Entry<String, Integer>> users = new ArrayList<>();
AtomicInteger userIndex = new AtomicInteger(-1);
int i = 0;
for (Document data : documents) {
long id = data.getLong("_id");
User user = event.getShardManager().getUserById(data.getLong("_id"));
if ((user == null || !event.getGuild().isMember(user)) && guild) {
continue;
}
i++;
users.add(Map.entry(user == null ? "Anonymous#0000 (" + id + ")" : MarkdownSanitizer.escape(user.getAsTag()), data.getInteger("total")));
if (user != null && 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<String, Integer>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
int rank = userIndex.get();
EmbedBuilder embed = new EmbedBuilder().setTitle("Donors 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` - $%,.2f\n", index + 1, entry.getKey(), entry.getValue() / 100D)));
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 PagedHandler method handleMessage.
public void handleMessage(Message message) {
MessageChannel channel = message.getChannel();
User author = message.getAuthor();
PagedResult<?> pagedResult = this.bot.getPagedManager().getPagedResult(channel.getIdLong(), author.getIdLong());
if (pagedResult == null) {
return;
}
if (author.getIdLong() != pagedResult.getOwnerId()) {
return;
}
String content = message.getContentRaw();
String contentLower = content.toLowerCase();
EnumSet<SelectType> selectTypes = pagedResult.getSelect();
if (this.next.contains(contentLower)) {
if (pagedResult.getNextPage() != pagedResult.getPage()) {
pagedResult.nextPage().ensure(channel);
this.attemptDelete(message);
}
} else if (this.previous.contains(contentLower)) {
if (pagedResult.getPreviousPage() != pagedResult.getPage()) {
pagedResult.previousPage().ensure(channel);
this.attemptDelete(message);
}
} else if (this.cancel.contains(contentLower)) {
this.attemptDelete(message);
pagedResult.delete();
} else if (selectTypes.contains(SelectType.INDEX) && NumberUtility.isNumberUnsigned(content)) {
try {
int index = Integer.parseInt(content);
if (index > pagedResult.getLowerPageBound() && index <= pagedResult.getHigherPageBound()) {
pagedResult.select(pagedResult.isIncreasedIndex() ? index - 1 : (pagedResult.getPage() * pagedResult.getPerPage() - pagedResult.getPerPage()) + (index - 1));
this.attemptDelete(message);
}
} catch (NumberFormatException ignored) {
}
} else {
int index = contentLower.lastIndexOf(' ');
if (index != -1 && this.skip.contains(contentLower.substring(0, index))) {
try {
int page = Integer.parseInt(contentLower.substring(index + 1));
if (page > 0 && page <= pagedResult.getMaxPage() && page != pagedResult.getPage()) {
pagedResult.setPage(page).ensure(channel);
this.attemptDelete(message);
return;
}
} catch (NumberFormatException ignored) {
}
}
if (selectTypes.contains(SelectType.OBJECT)) {
for (int i = pagedResult.getPage() * pagedResult.getPerPage() - pagedResult.getPerPage(); i < (pagedResult.getPage() == pagedResult.getMaxPage() ? pagedResult.getList().size() : pagedResult.getPage() * pagedResult.getPerPage()); i++) {
if (pagedResult.runSelectablePredicate(content, i)) {
pagedResult.select(i);
this.attemptDelete(message);
}
}
}
}
}
use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class DiscordBotCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "bot", endless = true, nullDefault = true) String query) {
CompletableFuture<String> future = new CompletableFuture<>();
if (query == null) {
future.complete("440996323156819968");
} else {
Matcher mentionMatch = SearchUtility.USER_MENTION.matcher(query);
if (NumberUtility.isNumber(query)) {
future.complete(query);
} else if (mentionMatch.matches()) {
future.complete(mentionMatch.group(1));
} else if (query.length() <= 32) {
Request request = new Request.Builder().url("https://top.gg/api/search?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&type=bot").build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
PagedResult<Document> paged = new PagedResult<>(event.getBot(), data.getList("results", Document.class)).setAutoSelect(true).setDisplayFunction(d -> d.getString("name") + " (" + d.getString("id") + ")");
paged.onSelect(select -> future.complete(select.getSelected().getString("id")));
paged.execute(event);
});
} else {
event.replyFailure("I could not find that bot").queue();
return;
}
}
future.whenComplete((id, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
Request request = new Request.Builder().url("https://top.gg/api/bots/" + id).addHeader("Authorization", event.getConfig().getTopGG()).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
if (response.code() == 404) {
event.replyFailure("I could not find that bot").queue();
return;
}
Document bot = Document.parse(response.body().string());
String botAvatarUrl = "https://cdn.discordapp.com/avatars/" + bot.getString("id") + "/" + bot.getString("avatar");
String botInviteUrl = !bot.getString("invite").isEmpty() ? bot.getString("invite") : "https://discord.com/oauth2/authorize?client_id=" + bot.getString("id") + "&scope=bot";
String guildCount = bot.containsKey("server_count") ? String.format("%,d", bot.getInteger("server_count")) : "N/A";
String ownerId = bot.getList("owners", String.class).get(0);
User owner = event.getShardManager().getUserById(ownerId);
EmbedBuilder embed = new EmbedBuilder().setAuthor(bot.getString("username") + "#" + bot.getString("discriminator"), "https://top.gg/bot/" + bot.getString("id"), botAvatarUrl).setThumbnail(botAvatarUrl).setDescription((bot.getBoolean("certifiedBot") ? "<:certified:438392214545235978> | " : "") + bot.getString("shortdesc")).addField("Guilds", guildCount, true).addField("Prefix", bot.getString("prefix"), true).addField("Library", bot.getString("lib"), true).addField("Approval Date", OffsetDateTime.parse(bot.getString("date")).format(this.formatter), true).addField("Monthly Votes", String.format("%,d :thumbsup:", bot.getInteger("monthlyPoints")), true).addField("Total Votes", String.format("%,d :thumbsup:", bot.getInteger("points")), true).addField("Invite", "**[Invite " + bot.getString("username") + " to your server](" + botInviteUrl + ")**", true);
if (owner == null) {
embed.setFooter("Primary Owner ID: " + ownerId, null);
} else {
embed.setFooter("Primary Owner: " + owner.getAsTag(), owner.getEffectiveAvatarUrl());
}
event.reply(embed.build()).queue();
});
});
}
use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class FreeGamesCommand method list.
@Command(value = "list", description = "Lists the current free games")
@CommandId(473)
@Examples({ "free games list" })
public void list(Sx4CommandEvent event) {
List<Document> games = event.getMongo().getAnnouncedGames(Filters.gte("promotion.end", Instant.now().getEpochSecond()), new Document()).into(new ArrayList<>());
if (games.isEmpty()) {
event.replyFailure("There are currently no free games").queue();
return;
}
List<FreeGame<?>> freeGames = games.stream().map(FreeGameUtility::getFreeGame).collect(Collectors.toList());
PagedResult<FreeGame<?>> paged = new PagedResult<>(event.getBot(), freeGames).setSelect().setPerPage(1).setCustomFunction(page -> {
EmbedBuilder embed = new EmbedBuilder();
embed.setFooter("Game " + page.getPage() + "/" + page.getMaxPage());
page.forEach((game, index) -> this.setGameEmbed(embed, game));
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 FreeGamesCommand method upcoming.
@Command(value = "upcoming", description = "Lists the free games on Epic Games coming in the future")
@CommandId(482)
@Examples({ "free games upcoming" })
public void upcoming(Sx4CommandEvent event) {
FreeGameUtility.retrieveUpcomingFreeGames(event.getHttpClient(), freeGames -> {
if (freeGames.isEmpty()) {
event.replyFailure("There are currently no upcoming free games").queue();
return;
}
PagedResult<EpicFreeGame> paged = new PagedResult<>(event.getBot(), freeGames).setSelect().setPerPage(1).setCustomFunction(page -> {
EmbedBuilder embed = new EmbedBuilder();
embed.setFooter("Game " + page.getPage() + "/" + page.getMaxPage());
page.forEach((game, index) -> this.setGameEmbed(embed, game));
return new MessageBuilder().setEmbeds(embed.build());
});
paged.execute(event);
});
}
Aggregations