use of com.sx4.bot.http.HttpCallback 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);
});
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class Currency method pollCurrencies.
public static void pollCurrencies(OkHttpClient client) {
Currency.EXECUTOR.scheduleAtFixedRate(() -> {
Request request = new Request.Builder().url("https://api.exchangerate.host/latest?base=EUR").build();
client.newCall(request).enqueue((HttpCallback) response -> {
JSONObject json = new JSONObject(response.body().string());
JSONObject rates = json.getJSONObject("rates");
for (String currency : rates.keySet()) {
Currency.CURRENCIES.put(currency, rates.getDouble(currency));
}
});
}, 0, 1, TimeUnit.HOURS);
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class ServerLogHandler method postGuildCount.
public void postGuildCount() {
if (this.bot.getConfig().isCanary()) {
return;
}
this.executor.scheduleAtFixedRate(() -> {
ShardManager manager = this.bot.getShardManager();
long guildCount = manager.getGuildCache().size();
int shardCount = manager.getShardsTotal();
Document topGGData = new Document().append("server_count", guildCount).append("shard_count", shardCount);
Request topGGRequest = new Request.Builder().post(RequestBody.create(MediaType.parse("application/json"), topGGData.toJson())).url("https://top.gg/api/bots/440996323156819968/stats").addHeader("Authorization", this.bot.getConfig().getTopGG()).addHeader("Content-Type", "application/json").build();
this.bot.getHttpClient().newCall(topGGRequest).enqueue((HttpCallback) response -> {
System.out.println("Posted guild count to top.gg");
response.close();
});
Document discordListData = new Document().append("serverCount", guildCount);
Request discordListRequest = new Request.Builder().post(RequestBody.create(MediaType.parse("application/json"), discordListData.toJson())).url("https://api.discordlist.space/v2/bots/440996323156819968").addHeader("Authorization", "Bot " + this.bot.getConfig().getDiscordListSpace()).addHeader("Content-Type", "application/json").build();
this.bot.getHttpClient().newCall(discordListRequest).enqueue((HttpCallback) response -> {
System.out.println("Posted guild count to discordlist.space");
response.close();
});
}, 30, 30, TimeUnit.MINUTES);
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class PatreonManager method ensurePatrons.
public void ensurePatrons() {
Request request = new Request.Builder().url("https://www.patreon.com/api/oauth2/v2/campaigns/" + this.bot.getConfig().getPatreonCampaignId() + "/members?fields%5Bmember%5D=lifetime_support_cents&fields%5Buser%5D=social_connections&include=user&page%5Bsize%5D=100000").header("Authorization", "Bearer " + this.bot.getConfig().getPatreonAccessToken()).build();
this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
List<WriteModel<Document>> bulkData = new ArrayList<>();
Map<String, Integer> total = new HashMap<>();
for (Document member : data.getList("data", Document.class)) {
int totalAmount = member.getEmbedded(List.of("attributes", "lifetime_support_cents"), 0);
if (totalAmount != 0) {
total.put(member.getEmbedded(List.of("relationships", "user", "data", "id"), String.class), totalAmount);
}
}
for (Document user : data.getList("included", Document.class)) {
String discordId = user.getEmbedded(List.of("attributes", "social_connections", "discord", "user_id"), String.class);
if (discordId == null) {
continue;
}
int totalAmount = total.getOrDefault(user.getString("id"), 0);
if (totalAmount == 0) {
continue;
}
List<Bson> update = List.of(Operators.set("premium.credit", Operators.add(Operators.ifNull("$premium.credit", 0), Operators.subtract(totalAmount, Operators.ifNull("$premium.total", 0)))), Operators.set("premium.endAt", Operators.add(Operators.cond(Operators.or(Operators.extinct("$premium.endAt"), Operators.lt("$premium.endAt", Operators.nowEpochSecond())), Operators.nowEpochSecond(), "$premium.endAt"), Operators.multiply(Operators.toInt(Operators.round(Operators.multiply(Operators.divide(Operators.subtract(totalAmount, Operators.ifNull("$premium.total", 0)), this.bot.getConfig().getPremiumPrice()), this.bot.getConfig().getPremiumDays()))), 86400))), Operators.set("premium.total", totalAmount));
bulkData.add(new UpdateOneModel<>(Filters.eq("_id", Long.parseLong(discordId)), update, new UpdateOptions().upsert(true)));
}
if (!bulkData.isEmpty()) {
this.bot.getMongo().bulkWriteUsers(bulkData).whenComplete(MongoDatabase.exceptionally());
}
});
}
use of com.sx4.bot.http.HttpCallback 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);
});
}
Aggregations