Search in sources :

Example 56 with HttpCallback

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);
    });
}
Also used : Document(org.bson.Document) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) ZoneOffset(java.time.ZoneOffset) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) FormatterManager(com.sx4.bot.formatter.FormatterManager) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) YouTubeChannel(com.sx4.bot.entities.youtube.YouTubeChannel) MultipartBody(okhttp3.MultipartBody) Pattern(java.util.regex.Pattern) java.util(java.util) Command(com.jockie.bot.core.command.Command) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) RequestBody(okhttp3.RequestBody) Bson(org.bson.conversions.Bson) AdvancedMessage(com.sx4.bot.annotations.argument.AdvancedMessage) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.mongodb.client.model(com.mongodb.client.model) YouTubeManager(com.sx4.bot.managers.YouTubeManager) FutureUtility(com.sx4.bot.utility.FutureUtility) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) MessageUtility(com.sx4.bot.utility.MessageUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) SelectType(com.sx4.bot.paged.PagedResult.SelectType) YouTubeVideo(com.sx4.bot.entities.youtube.YouTubeVideo) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) JSONArray(org.json.JSONArray) ErrorCategory(com.mongodb.ErrorCategory) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document) CompletableFuture(java.util.concurrent.CompletableFuture) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Sx4Command(com.sx4.bot.core.Sx4Command) Command(com.jockie.bot.core.command.Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 57 with HttpCallback

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);
}
Also used : TimeUnit(java.util.concurrent.TimeUnit) Request(okhttp3.Request) OkHttpClient(okhttp3.OkHttpClient) JSONObject(org.json.JSONObject) HttpCallback(com.sx4.bot.http.HttpCallback) Map(java.util.Map) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) HashMap(java.util.HashMap) Executors(java.util.concurrent.Executors) JSONObject(org.json.JSONObject) Request(okhttp3.Request)

Example 58 with HttpCallback

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);
}
Also used : ActionType(net.dv8tion.jda.api.audit.ActionType) Document(org.bson.Document) WebhookClient(club.minnced.discord.webhook.WebhookClient) GuildJoinEvent(net.dv8tion.jda.api.events.guild.GuildJoinEvent) Permission(net.dv8tion.jda.api.Permission) ZonedDateTime(java.time.ZonedDateTime) Member(net.dv8tion.jda.api.entities.Member) AuditLogEntry(net.dv8tion.jda.api.audit.AuditLogEntry) RequestBody(okhttp3.RequestBody) WebhookEmbedBuilder(club.minnced.discord.webhook.send.WebhookEmbedBuilder) Sx4(com.sx4.bot.core.Sx4) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) ZoneOffset(java.time.ZoneOffset) MediaType(okhttp3.MediaType) Request(okhttp3.Request) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) HttpCallback(com.sx4.bot.http.HttpCallback) Instant(java.time.Instant) GuildLeaveEvent(net.dv8tion.jda.api.events.guild.GuildLeaveEvent) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) EventListener(net.dv8tion.jda.api.hooks.EventListener) NotNull(org.jetbrains.annotations.NotNull) WebhookClientBuilder(club.minnced.discord.webhook.WebhookClientBuilder) Request(okhttp3.Request) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Document(org.bson.Document)

Example 59 with HttpCallback

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());
        }
    });
}
Also used : Document(org.bson.Document) Operators(com.sx4.bot.database.mongo.model.Operators) Request(okhttp3.Request) UpdateOneModel(com.mongodb.client.model.UpdateOneModel) HttpCallback(com.sx4.bot.http.HttpCallback) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) HashMap(java.util.HashMap) WriteModel(com.mongodb.client.model.WriteModel) ArrayList(java.util.ArrayList) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) List(java.util.List) Sx4(com.sx4.bot.core.Sx4) Map(java.util.Map) PatreonListener(com.sx4.bot.hooks.PatreonListener) PatreonEvent(com.sx4.bot.events.patreon.PatreonEvent) UpdateOptions(com.mongodb.client.model.UpdateOptions) UpdateOneModel(com.mongodb.client.model.UpdateOneModel) Request(okhttp3.Request) ArrayList(java.util.ArrayList) List(java.util.List) Document(org.bson.Document) HashMap(java.util.HashMap) Map(java.util.Map) UpdateOptions(com.mongodb.client.model.UpdateOptions)

Example 60 with HttpCallback

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);
    });
}
Also used : Document(org.bson.Document) MarkdownSanitizer(net.dv8tion.jda.api.utils.MarkdownSanitizer) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Item(com.sx4.bot.entities.economy.item.Item) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Map(java.util.Map) Option(com.jockie.bot.core.option.Option) com.mongodb.client.model(com.mongodb.client.model) ZoneOffset(java.time.ZoneOffset) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Month(java.time.Month) TextStyle(java.time.format.TextStyle) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) User(net.dv8tion.jda.api.entities.User) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) Document(org.bson.Document) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) OffsetDateTime(java.time.OffsetDateTime) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) PagedResult(com.sx4.bot.paged.PagedResult) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Aggregations

HttpCallback (com.sx4.bot.http.HttpCallback)73 Request (okhttp3.Request)71 ModuleCategory (com.sx4.bot.category.ModuleCategory)62 Sx4Command (com.sx4.bot.core.Sx4Command)62 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)62 Argument (com.jockie.bot.core.argument.Argument)57 Permission (net.dv8tion.jda.api.Permission)57 Document (org.bson.Document)40 ImageRequest (com.sx4.bot.entities.image.ImageRequest)35 ImageUtility (com.sx4.bot.utility.ImageUtility)33 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)27 ImageUrl (com.sx4.bot.annotations.argument.ImageUrl)24 PagedResult (com.sx4.bot.paged.PagedResult)18 StandardCharsets (java.nio.charset.StandardCharsets)17 URLEncoder (java.net.URLEncoder)16 List (java.util.List)16 Option (com.jockie.bot.core.option.Option)13 OffsetDateTime (java.time.OffsetDateTime)11 ZoneOffset (java.time.ZoneOffset)11 Limit (com.sx4.bot.annotations.argument.Limit)10