Search in sources :

Example 1 with JsonFormatter

use of com.sx4.bot.formatter.JsonFormatter 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 2 with JsonFormatter

use of com.sx4.bot.formatter.JsonFormatter in project Sx4 by sx4-discord-bot.

the class LeaverUtility method getLeaverMessage.

public static WebhookMessageBuilder getLeaverMessage(Document messageData, Member member) {
    Guild guild = member.getGuild();
    User user = member.getUser();
    OffsetDateTime now = OffsetDateTime.now();
    Formatter<Document> formatter = new JsonFormatter(messageData).member(member).user(user).guild(guild).addVariable(Member.class, "age", LeaverUtility.FORMATTER.parse(Duration.between(member.getTimeJoined(), now).toSeconds())).addVariable(User.class, "age", LeaverUtility.FORMATTER.parse(Duration.between(user.getTimeCreated(), now).toSeconds())).addVariable("now", now);
    return MessageUtility.fromJson(formatter.parse());
}
Also used : JsonFormatter(com.sx4.bot.formatter.JsonFormatter) User(net.dv8tion.jda.api.entities.User) OffsetDateTime(java.time.OffsetDateTime) Guild(net.dv8tion.jda.api.entities.Guild) Document(org.bson.Document)

Example 3 with JsonFormatter

use of com.sx4.bot.formatter.JsonFormatter in project Sx4 by sx4-discord-bot.

the class FreeGamesCommand method preview.

@Command(value = "preview", description = "Preview your free game notification message")
@CommandId(481)
@Examples({ "free games preview" })
public void preview(Sx4CommandEvent event) {
    Document data = event.getMongo().getFreeGameChannel(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("message"));
    if (data == null) {
        event.replyFailure("You don't have a free game channel setup").queue();
        return;
    }
    FreeGameUtility.retrieveFreeGames(event.getHttpClient(), freeGames -> {
        Formatter<Document> formatter = new JsonFormatter(data.get("message", FreeGameManager.DEFAULT_MESSAGE)).addVariable("game", freeGames.get(0));
        MessageUtility.fromWebhookMessage(event.getChannel(), MessageUtility.fromJson(formatter.parse()).build()).queue();
    });
}
Also used : JsonFormatter(com.sx4.bot.formatter.JsonFormatter) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 4 with JsonFormatter

use of com.sx4.bot.formatter.JsonFormatter in project Sx4 by sx4-discord-bot.

the class YouTubeNotificationCommand method preview.

@Command(value = "preview", description = "Previews your YouTube notification message")
@CommandId(465)
@Examples({ "youtube notification preview 5e45ce6d3688b30ee75201ae" })
public void preview(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
    Document data = event.getMongo().getYouTubeNotification(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong())), Projections.include("uploaderId", "message"));
    if (data == null) {
        event.replyFailure("I could not find that notification").queue();
        return;
    }
    String channelId = data.getString("uploaderId");
    Request request = new Request.Builder().url("https://www.youtube.com/feeds/videos.xml?channel_id=" + channelId).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (response.code() == 404) {
            event.replyFailure("The YouTube channel for this notification no longer exists").queue();
            return;
        }
        JSONObject channel = XML.toJSONObject(response.body().string());
        JSONObject feed = channel.getJSONObject("feed");
        JSONArray entries = feed.optJSONArray("entry");
        YouTubeVideo video;
        if (entries == null || entries.isEmpty()) {
            OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
            video = new YouTubeVideo("dQw4w9WgXcQ", "This channel had no uploads", now, now);
        } else {
            JSONObject entry = entries.getJSONObject(0);
            video = new YouTubeVideo(entry.getString("yt:videoId"), entry.getString("title"), entry.getString("updated"), entry.getString("published"));
        }
        String channelName = feed.getString("title");
        Document message = new JsonFormatter(data.get("message", YouTubeManager.DEFAULT_MESSAGE)).addVariable("video", video).addVariable("channel", new YouTubeChannel(channelId, channelName)).parse();
        try {
            MessageUtility.fromWebhookMessage(event.getTextChannel(), MessageUtility.fromJson(message).build()).queue();
        } catch (IllegalArgumentException e) {
            event.replyFailure(e.getMessage()).queue();
        }
    });
}
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) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) JSONObject(org.json.JSONObject) YouTubeChannel(com.sx4.bot.entities.youtube.YouTubeChannel) OffsetDateTime(java.time.OffsetDateTime) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) JSONArray(org.json.JSONArray) YouTubeVideo(com.sx4.bot.entities.youtube.YouTubeVideo) Document(org.bson.Document) 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 5 with JsonFormatter

use of com.sx4.bot.formatter.JsonFormatter in project Sx4 by sx4-discord-bot.

the class WelcomerUtility method getWelcomerMessage.

public static void getWelcomerMessage(OkHttpClient httpClient, Document messageData, String bannerId, Member member, boolean canary, boolean image, boolean gif, BiConsumer<WebhookMessageBuilder, Throwable> consumer) {
    Guild guild = member.getGuild();
    User user = member.getUser();
    OffsetDateTime now = OffsetDateTime.now();
    Formatter<Document> formatter = new JsonFormatter(messageData).member(member).user(user).guild(guild).addVariable(User.class, "age", TimeUtility.LONG_TIME_FORMATTER.parse(Duration.between(user.getTimeCreated(), now).toSeconds())).addVariable("now", now);
    if (!image) {
        WebhookMessageBuilder builder;
        if (messageData != null) {
            try {
                builder = MessageUtility.fromJson(formatter.parse());
            } catch (IllegalArgumentException e) {
                consumer.accept(null, e);
                return;
            }
        } else {
            builder = new WebhookMessageBuilder();
        }
        consumer.accept(builder, null);
    } else {
        ImageRequest request = new ImageRequest(Config.get().getImageWebserverUrl("welcomer")).addQuery("avatar", user.getEffectiveAvatarUrl()).addQuery("name", user.getAsTag()).addQuery("gif", gif).addQuery("directory", canary ? "sx4-canary" : "sx4-main");
        if (bannerId != null) {
            request.addQuery("banner_id", bannerId);
        }
        httpClient.newCall(request.build(Config.get().getImageWebserver())).enqueue((HttpCallback) response -> {
            if (response.isSuccessful()) {
                String fileName = "welcomer." + response.header("Content-Type").split("/")[1];
                formatter.addVariable("file.name", fileName).addVariable("file.url", "attachment://" + fileName);
                WebhookMessageBuilder builder;
                if (messageData == null) {
                    builder = new WebhookMessageBuilder();
                } else {
                    try {
                        builder = MessageUtility.fromJson(formatter.parse());
                    } catch (IllegalArgumentException e) {
                        consumer.accept(null, e);
                        return;
                    }
                }
                builder.addFile(fileName, response.body().bytes());
                consumer.accept(builder, null);
            } else {
                response.close();
            }
        });
    }
}
Also used : JsonFormatter(com.sx4.bot.formatter.JsonFormatter) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Document(org.bson.Document) Config(com.sx4.bot.config.Config) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) Guild(net.dv8tion.jda.api.entities.Guild) OkHttpClient(okhttp3.OkHttpClient) OffsetDateTime(java.time.OffsetDateTime) Formatter(com.sx4.bot.formatter.Formatter) Duration(java.time.Duration) BiConsumer(java.util.function.BiConsumer) User(net.dv8tion.jda.api.entities.User) OffsetDateTime(java.time.OffsetDateTime) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Guild(net.dv8tion.jda.api.entities.Guild) Document(org.bson.Document)

Aggregations

JsonFormatter (com.sx4.bot.formatter.JsonFormatter)5 Document (org.bson.Document)5 OffsetDateTime (java.time.OffsetDateTime)3 Command (com.jockie.bot.core.command.Command)2 Sx4Command (com.sx4.bot.core.Sx4Command)2 HttpCallback (com.sx4.bot.http.HttpCallback)2 WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)1 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)1 Argument (com.jockie.bot.core.argument.Argument)1 ErrorCategory (com.mongodb.ErrorCategory)1 MongoWriteException (com.mongodb.MongoWriteException)1 com.mongodb.client.model (com.mongodb.client.model)1 AdvancedMessage (com.sx4.bot.annotations.argument.AdvancedMessage)1 ImageUrl (com.sx4.bot.annotations.argument.ImageUrl)1 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)1 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)1 CommandId (com.sx4.bot.annotations.command.CommandId)1 Examples (com.sx4.bot.annotations.command.Examples)1 ModuleCategory (com.sx4.bot.category.ModuleCategory)1 Config (com.sx4.bot.config.Config)1