use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class YouTubeCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query, @Option(value = "channel", description = "Only return a channel") boolean channel, @Option(value = "playlist", description = "Only return a playlist") boolean playlist, @Option(value = "video", description = "Only return a video") boolean video) {
String type = channel ? "channel" : video ? "video" : playlist ? "playlist" : null;
Request request = new Request.Builder().url(String.format("https://www.googleapis.com/youtube/v3/search?key=%s&part=snippet&maxResults=50&safeSearch=none&q=%s%s", event.getConfig().getYouTube(), URLEncoder.encode(query, StandardCharsets.UTF_8), type == null ? "" : "&type=" + type)).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document json = Document.parse(response.body().string());
List<Document> items = json.getList("items", Document.class);
if (items.isEmpty()) {
event.replyFailure("I could not find any results").queue();
return;
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), items).setAuthor("YouTube Results", null, "https://media-thumbs.golden.com/4hBhjfnhOC6J3uJZglZG0quRsPU=/200x200/smart/golden-media.s3.amazonaws.com%2Ftopic_images%2F6c3fdb0966b049eba2b9c2331da224f0.png").setAutoSelect(true).setDisplayFunction(data -> {
Document id = data.get("id", Document.class);
String kind = id.getString("kind");
return "[" + data.getEmbedded(List.of("snippet", "title"), String.class) + "](" + this.getUrlFromId(id) + ")" + " (" + StringUtility.title(kind.substring(kind.indexOf('#') + 1)) + ")";
});
paged.onSelect(select -> {
Document result = select.getSelected();
Document id = result.get("id", Document.class);
Document snippet = result.get("snippet", Document.class);
Document thumbnails = snippet.get("thumbnails", Document.class);
ZonedDateTime uploadedAt = ZonedDateTime.parse(snippet.getString("publishedAt"));
EmbedBuilder embed = new EmbedBuilder();
embed.setColor(16711680);
embed.setDescription(snippet.getString("description"));
embed.setImage(thumbnails.getEmbedded(List.of("high", "url"), String.class));
embed.setTitle(snippet.getString("title"), this.getUrlFromId(id));
String kind = id.getString("kind");
if (kind.equals("youtube#channel")) {
embed.addField("Created At", uploadedAt.format(this.formatter), true);
} else if (kind.equals("youtube#video")) {
String state = snippet.getString("liveBroadcastContent");
embed.addField("Uploaded By", "[" + snippet.getString("channelTitle") + "](https://www.youtube.com/channel/" + snippet.getString("channelId") + ")", true);
embed.addField("Uploaded At", uploadedAt.format(this.formatter), true);
embed.addField("State", state.equals("live") ? "Live Now" : state.equals("upcoming") ? "Scheduled" : "Uploaded", true);
Request metaDataRequest = new Request.Builder().url("https://api.jockiemusic.com/v1/youtube/videos/" + id.getString("videoId") + "/metadata").build();
event.reply(embed.build()).queue(message -> {
event.getHttpClient().newCall(metaDataRequest).enqueue((HttpCallback) metaDataResponse -> {
if (metaDataResponse.code() == 404) {
return;
}
Document data = Document.parse(metaDataResponse.body().string()).get("data", Document.class);
Document metaData = data.get("metadata", Document.class);
Document rating = metaData.get("rating", Document.class);
long likes = rating.get("likes", Number.class).longValue(), dislikes = rating.get("dislikes", Number.class).longValue();
double ratingPercent = ((double) likes / (likes + dislikes)) * 100D;
embed.addField("Duration", TimeUtility.getMusicTimeString(metaData.get("length", Number.class).longValue(), TimeUnit.MILLISECONDS), true);
embed.addField("Views", String.format("%,d", metaData.get("views", Number.class).longValue()), true);
embed.addField("Likes/Dislikes", String.format("%,d \\\uD83D\uDC4D\n%,d \\\uD83D\uDC4E", likes, dislikes), true);
embed.addField("Rating", NumberUtility.DEFAULT_DECIMAL_FORMAT.format(ratingPercent) + "%", true);
embed.setFooter("Views and Ratings last updated");
embed.setTimestamp(Instant.ofEpochSecond(data.get("lastUpdated", Number.class).longValue()));
message.editMessageEmbeds(embed.build()).queue();
});
});
return;
} else {
embed.addField("Uploaded By", "[" + snippet.getString("channelTitle") + "](https://www.youtube.com/channel/" + snippet.getString("channelId") + ")", true);
embed.addField("Uploaded At", uploadedAt.format(this.formatter), true);
}
event.reply(embed.build()).queue();
});
paged.execute(event);
});
}
use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class MuteCommand method list.
@Command(value = "list", description = "Lists all the currently muted users in the server")
@CommandId(343)
@Redirects({ "muted list" })
@Examples({ "mute list" })
public void list(Sx4CommandEvent event) {
List<Document> mutes = event.getMongo().getMutes(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("unmuteAt", "userId")).into(new ArrayList<>());
if (mutes.isEmpty()) {
event.replyFailure("There is no one muted in this server").queue();
return;
}
mutes.sort(Comparator.comparingLong(d -> d.getLong("unmuteAt")));
PagedResult<Document> paged = new PagedResult<>(event.getBot(), mutes).setAuthor("Muted Users", null, event.getGuild().getIconUrl()).setIndexed(false).setSelect().setDisplayFunction(data -> {
User user = event.getShardManager().getUserById(data.getLong("userId"));
return (user == null ? "Anonymous#0000" : user.getAsTag()) + " - " + TimeUtility.LONG_TIME_FORMATTER.parse(data.getLong("unmuteAt") - Clock.systemUTC().instant().getEpochSecond());
});
paged.execute(event);
}
use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class OffencesCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
Bson filter = Filters.eq("guildId", event.getGuild().getIdLong());
if (member != null) {
filter = Filters.and(filter, Filters.eq("targetId", member.getIdLong()));
}
event.getMongo().getOffences(filter, Sorts.descending("_id")).whenComplete((iterable, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
try {
List<Document> data = iterable.into(new ArrayList<>());
if (data.isEmpty()) {
event.replyFailure((member == null ? "This server" : "**" + member.getUser().getAsTag() + "**") + " has no offences").queue();
return;
}
User user = member == null ? null : member.getUser();
PagedResult<Document> paged = new PagedResult<>(event.getBot(), data).setPerPage(6).setCustomFunction(page -> {
EmbedBuilder embed = new EmbedBuilder().setAuthor("Offences", null, member == null ? event.getGuild().getIconUrl() : user.getEffectiveAvatarUrl()).setTitle("Page " + page.getPage() + "/" + page.getMaxPage()).setFooter(PagedResult.DEFAULT_FOOTER_TEXT);
page.forEach((offence, index) -> {
Action action = Action.fromData(offence.get("action", Document.class));
ObjectId id = offence.getObjectId("_id");
OffsetDateTime time = OffsetDateTime.ofInstant(Instant.ofEpochSecond(id.getTimestamp()), ZoneOffset.UTC);
long targetId = offence.getLong("targetId");
User target = member == null ? event.getShardManager().getUserById(targetId) : user;
String targetContent = target == null ? "Anonymous#0000 (" + targetId + ")" : target.getAsTag();
long moderatorId = offence.getLong("moderatorId");
User moderator = event.getShardManager().getUserById(moderatorId);
String moderatorContent = moderator == null ? "Anonymous#0000 (" + moderatorId + ")" : moderator.getAsTag();
embed.addField(action.toString(), String.format("Target: %s\nModerator: %s\nReason: %s\nTime: %s", targetContent, moderatorContent, offence.get("reason", "None Given"), time.format(this.formatter)), true);
});
return new MessageBuilder().setEmbeds(embed.build());
});
paged.execute(event);
} catch (Throwable e) {
e.printStackTrace();
}
});
}
use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class IGDBCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "game", endless = true, nullDefault = true) String game, @Option(value = "sort", description = "Sort results by `name` (default), `rating` and `release`") IGDBSort sort, @Option(value = "reverse", description = "Reverses sorting order") boolean reverse) {
IGDBParser parser = new IGDBParser().setFilter("category = 0").limit(500).addFields("name", "total_rating", "total_rating_count", "first_release_date", "genres.name", "url", "summary", "cover.image_id", "platforms.name");
if (game != null && sort == null && !reverse) {
parser.search(String.format("\"%s\"", game));
} else {
parser.sort(sort == null ? "name" : sort.getName(), !reverse).appendFilter(filter -> IGDBFilter.and(filter, (sort == null ? "name" : sort.getName()) + " != n"));
if (game != null) {
parser.appendFilter(filter -> IGDBFilter.and(filter, String.format("name ~ \"%s\"*", game)));
}
}
Request request = new Request.Builder().url("https://api.igdb.com/v4/games/").post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), parser.parse())).addHeader("Client-ID", event.getConfig().getTwitchClientId()).addHeader("Authorization", "Bearer " + event.getConfig().getTwitch()).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
String body = String.format("{\"data\":%s}", response.body().string());
List<Document> results = Document.parse(body).getList("data", Document.class);
if (results.isEmpty()) {
event.replyFailure("I could not find any games with that filter").queue();
return;
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), results).setAutoSelect(true).setIncreasedIndex(true).setAuthor("IGDB Search", null, "http://bit.ly/2NXGwMz").setDisplayFunction(data -> data.getString("name"));
paged.onSelect(select -> {
Document data = select.getSelected();
EmbedBuilder embed = new EmbedBuilder();
embed.setAuthor(data.getString("name"), data.getString("url"), "http://bit.ly/2NXGwMz");
embed.setDescription(StringUtility.limit(data.get("summary", "This game has no description :("), MessageEmbed.DESCRIPTION_MAX_LENGTH, "... [Read More](" + data.getString("url") + ")"));
embed.setThumbnail(data.containsKey("cover") ? String.format("https://images.igdb.com/igdb/image/upload/t_thumb/%s.jpg", data.getEmbedded(List.of("cover", "image_id"), String.class)) : null);
int ratings = data.get("total_rating_count", 0);
embed.addField("Rating", data.containsKey("total_rating") ? String.format("%.2f out of %,d rating%s", data.getDouble("total_rating"), ratings, ratings == 1 ? "" : "s") : "Unknown", true);
embed.addField("Release Date", data.containsKey("first_release_date") ? Instant.ofEpochSecond(data.getInteger("first_release_date")).atOffset(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern("dd LLLL yyyy")) : "Unknown", true);
embed.addField("Genres", data.containsKey("genres") ? data.getList("genres", Document.class).stream().map(genre -> genre.getString("name")).collect(Collectors.joining("\n")) : "None", true);
embed.addField("Platforms", data.containsKey("platforms") ? data.getList("platforms", Document.class).stream().map(platform -> platform.getString("name")).collect(Collectors.joining("\n")) : "None", true);
event.reply(embed.build()).queue();
});
paged.execute(event);
});
}
use of com.sx4.bot.paged.PagedResult in project Sx4 by sx4-discord-bot.
the class InvitesCommand method leaderboard.
@Command(value = "leaderboard", aliases = { "lb" }, description = "View a leaderboard of all invites in the server sorted by user")
@CommandId(266)
@Redirects({ "lb invites", "leaderboard invites" })
@Examples({ "invites leaderboard" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void leaderboard(Sx4CommandEvent event) {
event.getGuild().retrieveInvites().queue(invites -> {
if (invites.isEmpty()) {
event.replyFailure("There are no invites in this server").queue();
return;
}
Map<Long, Integer> count = new HashMap<>();
AtomicInteger total = new AtomicInteger(0);
for (Invite invite : invites) {
User inviter = invite.getInviter();
if (inviter != null) {
count.compute(inviter.getIdLong(), (key, value) -> value == null ? invite.getUses() : value + invite.getUses());
}
total.addAndGet(invite.getUses());
}
List<Map.Entry<Long, Integer>> sortedCount = new ArrayList<>(count.entrySet());
sortedCount.sort(Collections.reverseOrder(Comparator.comparingInt(Map.Entry::getValue)));
PagedResult<Map.Entry<Long, Integer>> paged = new PagedResult<>(event.getBot(), sortedCount).setIncreasedIndex(true).setAuthor("Invites Leaderboard", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
int percentInvited = Math.round(((float) data.getValue() / total.get()) * 100);
String percent = percentInvited >= 1 ? String.valueOf(percentInvited) : "<1";
Member member = event.getGuild().getMemberById(data.getKey());
String memberString = member == null ? String.valueOf(data.getKey()) : member.getUser().getAsTag();
return String.format("`%s` - %,d %s (%s%%)", memberString, data.getValue(), data.getValue() == 1 ? "invite" : "invites", percent);
});
paged.execute(event);
});
}
Aggregations