Search in sources :

Example 1 with WebhookMessage

use of club.minnced.discord.webhook.send.WebhookMessage in project PurrBot by purrbot-site.

the class WebhookUtil method sendMsg.

public void sendMsg(String avatar, String name, String message, WebhookEmbed embed) {
    WebhookMessage msg = new WebhookMessageBuilder().setAvatarUrl(avatar).setUsername(name).setContent(message).addEmbeds(embed).build();
    client.send(msg);
}
Also used : WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder)

Example 2 with WebhookMessage

use of club.minnced.discord.webhook.send.WebhookMessage in project Sx4 by sx4-discord-bot.

the class PatreonEndpoint method postPatreon.

@POST
@Path("patreon")
public Response postPatreon(final String body, @HeaderParam("X-Patreon-Signature") final String signature, @HeaderParam("X-Patreon-Event") final String event) {
    String hash;
    try {
        hash = HmacUtility.getSignatureHex(this.bot.getConfig().getPatreonWebhookSecret(), body, HmacUtility.HMAC_MD5);
    } catch (InvalidKeyException | NoSuchAlgorithmException e) {
        return Response.status(500).build();
    }
    if (!hash.equals(signature)) {
        return Response.status(401).build();
    }
    Document document = Document.parse(body);
    WebhookMessage message = new WebhookMessageBuilder().setContent("Patreon payload received").addFile("patreon.json", document.toJson(MongoDatabase.PRETTY_JSON).getBytes(StandardCharsets.UTF_8)).build();
    this.webhook.send(message);
    int totalAmount = document.getEmbedded(List.of("data", "attributes", "lifetime_support_cents"), 0);
    if (totalAmount == 0) {
        return Response.status(204).build();
    }
    Document user = document.getList("included", Document.class).stream().filter(included -> included.getString("type").equals("user")).findFirst().orElse(null);
    if (user != null) {
        String discordId = user.getEmbedded(List.of("attributes", "social_connections", "discord", "user_id"), String.class);
        if (discordId != null) {
            this.bot.getPatreonManager().onPatreonEvent(new PatreonEvent(Long.parseLong(discordId), totalAmount));
        }
    }
    return Response.status(204).build();
}
Also used : WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) PatreonEvent(com.sx4.bot.events.patreon.PatreonEvent) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) Document(org.bson.Document) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 3 with WebhookMessage

use of club.minnced.discord.webhook.send.WebhookMessage 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 4 with WebhookMessage

use of club.minnced.discord.webhook.send.WebhookMessage 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 5 with WebhookMessage

use of club.minnced.discord.webhook.send.WebhookMessage in project Sx4 by sx4-discord-bot.

the class YouTubeHandler method onYouTubeUpload.

public void onYouTubeUpload(YouTubeUploadEvent event) {
    ShardManager shardManager = this.bot.getShardManager();
    String uploaderId = event.getChannel().getId();
    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.match(Filters.eq("uploaderId", uploaderId)), 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")))));
    this.bot.getMongo().aggregateYouTubeNotifications(pipeline).whenComplete((notifications, aggregateException) -> {
        if (ExceptionUtility.sendErrorMessage(aggregateException)) {
            return;
        }
        this.executor.submit(() -> {
            List<WriteModel<Document>> bulkUpdate = new ArrayList<>();
            notifications.forEach(notification -> {
                if (!notification.getBoolean("enabled", true)) {
                    return;
                }
                long channelId = notification.getLong("channelId");
                TextChannel textChannel = shardManager.getTextChannelById(channelId);
                if (textChannel == null) {
                    return;
                }
                Document webhookData = notification.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
                boolean premium = notification.getBoolean("premium");
                WebhookMessage message;
                try {
                    message = this.format(event, notification.get("message", YouTubeManager.DEFAULT_MESSAGE)).setAvatarUrl(premium ? webhookData.get("avatar", this.bot.getConfig().getYouTubeAvatar()) : this.bot.getConfig().getYouTubeAvatar()).setUsername(premium ? webhookData.get("name", "Sx4 - YouTube") : "Sx4 - YouTube").build();
                } catch (IllegalArgumentException e) {
                    // possibly create an error field when this happens so the user can debug what went wrong
                    bulkUpdate.add(new UpdateOneModel<>(Filters.eq("_id", notification.getObjectId("_id")), Updates.unset("message"), new UpdateOptions()));
                    return;
                }
                this.bot.getYouTubeManager().sendYouTubeNotification(textChannel, webhookData, message).whenComplete(MongoDatabase.exceptionally());
            });
            if (!bulkUpdate.isEmpty()) {
                this.bot.getMongo().bulkWriteYouTubeNotifications(bulkUpdate).whenComplete(MongoDatabase.exceptionally());
            }
            Document data = new Document("type", YouTubeType.UPLOAD.getRaw()).append("videoId", event.getVideo().getId()).append("title", event.getVideo().getTitle()).append("uploaderId", event.getChannel().getId());
            this.bot.getMongo().insertYouTubeNotificationLog(data).whenComplete(MongoDatabase.exceptionally());
        });
    });
}
Also used : ArrayList(java.util.ArrayList) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Document(org.bson.Document) Bson(org.bson.conversions.Bson) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) TextChannel(net.dv8tion.jda.api.entities.TextChannel)

Aggregations

WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)18 Document (org.bson.Document)13 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)12 TextChannel (net.dv8tion.jda.api.entities.TextChannel)9 Bson (org.bson.conversions.Bson)9 Sx4 (com.sx4.bot.core.Sx4)8 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)8 WebhookClient (com.sx4.bot.entities.webhook.WebhookClient)7 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)6 ReadonlyMessage (com.sx4.bot.entities.webhook.ReadonlyMessage)6 HttpException (club.minnced.discord.webhook.exception.HttpException)5 com.mongodb.client.model (com.mongodb.client.model)5 JsonFormatter (com.sx4.bot.formatter.JsonFormatter)5 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)5 MessageUtility (com.sx4.bot.utility.MessageUtility)5 CompletableFuture (java.util.concurrent.CompletableFuture)5 CompletionException (java.util.concurrent.CompletionException)5 NotNull (org.jetbrains.annotations.NotNull)5 Operators (com.sx4.bot.database.mongo.model.Operators)4 Formatter (com.sx4.bot.formatter.Formatter)4