Search in sources :

Example 1 with ReadonlyMessage

use of com.sx4.bot.entities.webhook.ReadonlyMessage in project Sx4 by sx4-discord-bot.

the class SuggestionManager method editSuggestion.

public CompletableFuture<ReadonlyMessage> editSuggestion(long messageId, long channelId, Document webhookData, WebhookEmbed embed) {
    User selfUser = this.bot.getShardManager().getShardById(0).getSelfUser();
    WebhookMessage message = new WebhookMessageBuilder().setAvatarUrl(webhookData.get("url", selfUser.getEffectiveAvatarUrl())).setUsername(webhookData.get("name", selfUser.getName())).addEmbeds(embed).build();
    WebhookClient webhook;
    if (this.webhooks.containsKey(channelId)) {
        webhook = this.webhooks.get(channelId);
    } else if (!webhookData.containsKey("id")) {
        return CompletableFuture.completedFuture(null);
    } else {
        webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.executor, this.client);
        this.webhooks.put(channelId, webhook);
    }
    return webhook.edit(messageId, message).thenApply(webhookMessage -> new ReadonlyMessage(webhookMessage, webhook.getId(), webhook.getToken()));
}
Also used : WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) User(net.dv8tion.jda.api.entities.User) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage)

Example 2 with ReadonlyMessage

use of com.sx4.bot.entities.webhook.ReadonlyMessage in project Sx4 by sx4-discord-bot.

the class FreeGameManager method sendFreeGameNotifications.

public CompletableFuture<List<ReadonlyMessage>> sendFreeGameNotifications(List<? extends FreeGame<?>> games) {
    games.forEach(this::addAnnouncedGame);
    List<Document> gameData = games.stream().map(FreeGame::toData).collect(Collectors.toList());
    if (!gameData.isEmpty()) {
        this.bot.getMongo().insertManyAnnouncedGames(gameData).whenComplete(MongoDatabase.exceptionally());
    }
    List<Bson> guildPipeline = List.of(Aggregates.match(Operators.expr(Operators.eq("$_id", "$$guildId"))), Aggregates.project(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L)))));
    List<Bson> pipeline = List.of(Aggregates.lookup("guilds", List.of(new Variable<>("guildId", "$guildId")), guildPipeline, "premium"), Aggregates.addFields(new Field<>("premium", Operators.cond(Operators.isEmpty("$premium"), false, Operators.get(Operators.arrayElemAt("$premium", 0), "premium")))));
    return this.bot.getMongo().aggregateFreeGameChannels(pipeline).thenComposeAsync(documents -> {
        List<WriteModel<Document>> bulkData = new ArrayList<>();
        List<CompletableFuture<List<ReadonlyMessage>>> futures = new ArrayList<>();
        for (Document data : documents) {
            if (!data.getBoolean("enabled", true)) {
                continue;
            }
            TextChannel channel = this.bot.getShardManager().getTextChannelById(data.getLong("channelId"));
            if (channel == null) {
                continue;
            }
            String avatar = channel.getJDA().getSelfUser().getEffectiveAvatarUrl();
            boolean premium = data.getBoolean("premium");
            Document webhookData = data.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
            long platforms = data.get("platforms", FreeGameType.ALL);
            List<WebhookMessage> messages = new ArrayList<>();
            for (FreeGame<?> game : games) {
                long raw = game.getType().getRaw();
                if ((platforms & raw) != raw) {
                    continue;
                }
                Formatter<Document> formatter = new JsonFormatter(data.get("message", FreeGameManager.DEFAULT_MESSAGE)).addVariable("game", game);
                WebhookMessage message;
                try {
                    message = MessageUtility.fromJson(formatter.parse()).setAvatarUrl(premium ? webhookData.get("avatar", avatar) : avatar).setUsername(premium ? webhookData.get("name", "Sx4 - Free Games") : "Sx4 - Free Games").build();
                } catch (IllegalArgumentException e) {
                    bulkData.add(new UpdateOneModel<>(Filters.eq("_id", data.getObjectId("_id")), Updates.unset("message")));
                    continue;
                }
                messages.add(message);
            }
            if (!messages.isEmpty()) {
                futures.add(this.sendFreeGameNotificationMessages(channel, webhookData, messages));
            }
        }
        if (!bulkData.isEmpty()) {
            this.bot.getMongo().bulkWriteFreeGameChannels(bulkData).whenComplete(MongoDatabase.exceptionally());
        }
        return FutureUtility.allOf(futures).thenApply(list -> list.stream().flatMap(List::stream).collect(Collectors.toList()));
    });
}
Also used : Document(org.bson.Document) Bson(org.bson.conversions.Bson) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage)

Example 3 with ReadonlyMessage

use of com.sx4.bot.entities.webhook.ReadonlyMessage in project Sx4 by sx4-discord-bot.

the class ModLogManager method sendModLog.

public CompletableFuture<ReadonlyMessage> sendModLog(TextChannel channel, Document webhookData, WebhookEmbed embed, boolean premium) {
    User selfUser = channel.getJDA().getSelfUser();
    WebhookMessage message = new WebhookMessageBuilder().setAvatarUrl(premium ? webhookData.get("avatar", selfUser.getEffectiveAvatarUrl()) : selfUser.getEffectiveAvatarUrl()).setUsername(premium ? webhookData.get("name", "Sx4 - Mod Logs") : "Sx4 - Mod Logs").addEmbeds(embed).build();
    WebhookClient webhook;
    if (this.webhooks.containsKey(channel.getIdLong())) {
        webhook = this.webhooks.get(channel.getIdLong());
    } else if (!webhookData.containsKey("id")) {
        return this.createWebhook(channel, message);
    } else {
        webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.executor, this.client);
        this.webhooks.put(channel.getIdLong(), webhook);
    }
    return webhook.send(message).thenApply(webhookMessage -> new ReadonlyMessage(webhookMessage, webhook.getId(), webhook.getToken())).exceptionallyCompose(exception -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof HttpException && ((HttpException) cause).getCode() == 404) {
            this.webhooks.remove(channel.getIdLong());
            return this.createWebhook(channel, message);
        }
        return CompletableFuture.failedFuture(exception);
    });
}
Also used : WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Document(org.bson.Document) BotPermissionException(com.sx4.bot.exceptions.mod.BotPermissionException) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Updates(com.mongodb.client.model.Updates) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Executors(java.util.concurrent.Executors) User(net.dv8tion.jda.api.entities.User) HttpException(club.minnced.discord.webhook.exception.HttpException) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) Guild(net.dv8tion.jda.api.entities.Guild) OkHttpClient(okhttp3.OkHttpClient) Sx4(com.sx4.bot.core.Sx4) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Map(java.util.Map) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) User(net.dv8tion.jda.api.entities.User) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) CompletionException(java.util.concurrent.CompletionException) HttpException(club.minnced.discord.webhook.exception.HttpException) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage)

Example 4 with ReadonlyMessage

use of com.sx4.bot.entities.webhook.ReadonlyMessage in project Sx4 by sx4-discord-bot.

the class SuggestionManager method sendSuggestion.

public CompletableFuture<ReadonlyMessage> sendSuggestion(TextChannel channel, Document webhookData, boolean premium, WebhookEmbed embed) {
    User selfUser = channel.getJDA().getSelfUser();
    WebhookMessage message = new WebhookMessageBuilder().setAvatarUrl(webhookData.get("avatar", selfUser.getEffectiveAvatarUrl())).setUsername(webhookData.get("name", "Sx4 - Suggestions")).addEmbeds(embed).build();
    WebhookClient webhook;
    if (this.webhooks.containsKey(channel.getIdLong())) {
        webhook = this.webhooks.get(channel.getIdLong());
    } else if (!webhookData.containsKey("id")) {
        return this.createWebhook(channel, message);
    } else {
        webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.executor, this.client);
        this.webhooks.put(channel.getIdLong(), webhook);
    }
    return webhook.send(message).thenApply(webhookMessage -> new ReadonlyMessage(webhookMessage, webhook.getId(), webhook.getToken())).exceptionallyCompose(exception -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof HttpException && ((HttpException) cause).getCode() == 404) {
            this.webhooks.remove(channel.getIdLong());
            return this.createWebhook(channel, message);
        }
        return CompletableFuture.failedFuture(exception);
    });
}
Also used : WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Document(org.bson.Document) BotPermissionException(com.sx4.bot.exceptions.mod.BotPermissionException) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Updates(com.mongodb.client.model.Updates) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) CompletionException(java.util.concurrent.CompletionException) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Executors(java.util.concurrent.Executors) User(net.dv8tion.jda.api.entities.User) HttpException(club.minnced.discord.webhook.exception.HttpException) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) Guild(net.dv8tion.jda.api.entities.Guild) OkHttpClient(okhttp3.OkHttpClient) Sx4(com.sx4.bot.core.Sx4) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Map(java.util.Map) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) User(net.dv8tion.jda.api.entities.User) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) CompletionException(java.util.concurrent.CompletionException) HttpException(club.minnced.discord.webhook.exception.HttpException) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage)

Example 5 with ReadonlyMessage

use of com.sx4.bot.entities.webhook.ReadonlyMessage in project Sx4 by sx4-discord-bot.

the class FreeGameManager method sendFreeGameNotificationMessages.

public CompletableFuture<List<ReadonlyMessage>> sendFreeGameNotificationMessages(TextChannel channel, Document webhookData, List<WebhookMessage> messages) {
    WebhookClient webhook;
    if (this.webhooks.containsKey(channel.getIdLong())) {
        webhook = this.webhooks.get(channel.getIdLong());
    } else if (!webhookData.containsKey("id")) {
        return this.createWebhook(channel, messages);
    } else {
        webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.webhookExecutor, this.client);
        this.webhooks.put(channel.getIdLong(), webhook);
    }
    List<ReadonlyMessage> completedMessages = new ArrayList<>();
    CompletableFuture<Boolean> future = CompletableFuture.completedFuture(null);
    for (WebhookMessage message : messages) {
        future = future.thenCompose($ -> webhook.send(message)).thenApply(webhookMessage -> completedMessages.add(new ReadonlyMessage(webhookMessage, webhook.getId(), webhook.getToken())));
    }
    return future.thenApply($ -> completedMessages).exceptionallyCompose(exception -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof HttpException && ((HttpException) cause).getCode() == 404) {
            this.webhooks.remove(channel.getIdLong());
            return this.createWebhook(channel, messages);
        }
        return CompletableFuture.completedFuture(Collections.emptyList());
    });
}
Also used : WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) Document(org.bson.Document) java.util(java.util) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) EpicFreeGame(com.sx4.bot.entities.info.EpicFreeGame) TextChannel(net.dv8tion.jda.api.entities.TextChannel) FreeGame(com.sx4.bot.entities.info.FreeGame) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) Formatter(com.sx4.bot.formatter.Formatter) Sx4(com.sx4.bot.core.Sx4) SteamFreeGame(com.sx4.bot.entities.info.SteamFreeGame) Element(org.jsoup.nodes.Element) Duration(java.time.Duration) FreeGameUtility(com.sx4.bot.utility.FreeGameUtility) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) ZoneOffset(java.time.ZoneOffset) FreeGameType(com.sx4.bot.entities.info.FreeGameType) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) Operators(com.sx4.bot.database.mongo.model.Operators) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) java.util.concurrent(java.util.concurrent) Predicate(java.util.function.Predicate) MessageUtility(com.sx4.bot.utility.MessageUtility) Collectors(java.util.stream.Collectors) HttpException(club.minnced.discord.webhook.exception.HttpException) OkHttpClient(okhttp3.OkHttpClient) OffsetDateTime(java.time.OffsetDateTime) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Jsoup(org.jsoup.Jsoup) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) HttpException(club.minnced.discord.webhook.exception.HttpException) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage)

Aggregations

WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)6 ReadonlyMessage (com.sx4.bot.entities.webhook.ReadonlyMessage)6 WebhookClient (com.sx4.bot.entities.webhook.WebhookClient)5 TextChannel (net.dv8tion.jda.api.entities.TextChannel)5 Document (org.bson.Document)5 Bson (org.bson.conversions.Bson)5 HttpException (club.minnced.discord.webhook.exception.HttpException)4 Sx4 (com.sx4.bot.core.Sx4)4 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)4 Permission (net.dv8tion.jda.api.Permission)4 OkHttpClient (okhttp3.OkHttpClient)4 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)3 BotPermissionException (com.sx4.bot.exceptions.mod.BotPermissionException)3 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)2 com.mongodb.client.model (com.mongodb.client.model)2 Updates (com.mongodb.client.model.Updates)2 JsonFormatter (com.sx4.bot.formatter.JsonFormatter)2 HttpCallback (com.sx4.bot.http.HttpCallback)2 java.util (java.util)2 HashMap (java.util.HashMap)2