Search in sources :

Example 11 with WebhookClient

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

the class StarboardCommand method delete.

@Command(value = "delete", aliases = { "remove" }, description = "Deletes a starboard")
@CommandId(204)
@Examples({ "starboard delete 5ff636647f93247aeb2ac429", "starboard delete all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void delete(Sx4CommandEvent event, @Argument(value = "id | all") @AlternativeOptions("all") Alternative<ObjectId> option) {
    if (option.isAlternative()) {
        String acceptId = new CustomButtonId.Builder().setType(ButtonType.STARBOARD_DELETE_CONFIRM).setOwners(event.getAuthor().getIdLong()).setTimeout(60).getId();
        String rejectId = new CustomButtonId.Builder().setType(ButtonType.GENERIC_REJECT).setOwners(event.getAuthor().getIdLong()).setTimeout(60).getId();
        List<Button> buttons = List.of(Button.success(acceptId, "Yes"), Button.danger(rejectId, "No"));
        event.reply(event.getAuthor().getName() + ", are you sure you want to delete **all** starboards in this server?").setActionRow(buttons).queue();
    } else {
        ObjectId id = option.getValue();
        AtomicReference<Document> atomicData = new AtomicReference<>();
        event.getMongo().findAndDeleteStarboard(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong()))).thenCompose(data -> {
            if (data == null) {
                return CompletableFuture.completedFuture(null);
            }
            atomicData.set(data);
            return event.getMongo().deleteManyStars(Filters.eq("messageId", data.getLong("originalMessageId")));
        }).whenComplete((result, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (result == null) {
                event.replyFailure("I could not find that starboard").queue();
                return;
            }
            Document data = atomicData.get();
            WebhookClient webhook = event.getBot().getStarboardManager().getWebhook(data.getLong("channelId"));
            if (webhook != null) {
                webhook.delete(data.getLong("messageId"));
            }
            event.replySuccess("That starboard has been deleted").queue();
        });
    }
}
Also used : Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.mongodb.client.model(com.mongodb.client.model) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) Operators(com.sx4.bot.database.mongo.model.Operators) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) StarboardManager(com.sx4.bot.managers.StarboardManager) FormatterManager(com.sx4.bot.formatter.FormatterManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) StringJoiner(java.util.StringJoiner) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) Comparator(java.util.Comparator) ButtonType(com.sx4.bot.entities.interaction.ButtonType) WebhookClient(club.minnced.discord.webhook.WebhookClient) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) ObjectId(org.bson.types.ObjectId) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) AtomicReference(java.util.concurrent.atomic.AtomicReference) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 12 with WebhookClient

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

the class LoggerManager method handleQueue.

private void handleQueue() {
    this.executor.submit(() -> {
        try {
            Request request = this.queue.poll();
            if (request == null) {
                return;
            }
            if (request.getAttempts() == LoggerManager.MAX_RETRIES) {
                this.handleQueue();
                return;
            }
            Guild guild = request.getGuild();
            if (guild == null) {
                this.handleQueue();
                return;
            }
            long channelId = request.getChannelId();
            BaseGuildMessageChannel channel = request.getChannel(guild);
            if (channel == null) {
                this.bot.getMongo().deleteLogger(Filters.eq("channelId", channelId)).whenComplete((result, exception) -> {
                    ExceptionUtility.sendErrorMessage(exception);
                    this.queue.clear();
                });
                return;
            }
            List<WebhookEmbed> embeds = new ArrayList<>(request.getEmbeds());
            int length = MessageUtility.getWebhookEmbedLength(embeds);
            List<Request> skippedRequests = new ArrayList<>(), requests = new ArrayList<>();
            requests.add(request);
            Request nextRequest;
            while ((nextRequest = this.queue.poll()) != null) {
                List<WebhookEmbed> nextEmbeds = nextRequest.getEmbeds();
                int nextLength = MessageUtility.getWebhookEmbedLength(nextEmbeds);
                if (embeds.size() + nextEmbeds.size() > WebhookMessage.MAX_EMBEDS || length + nextLength > MessageEmbed.EMBED_MAX_LENGTH_BOT) {
                    skippedRequests.add(nextRequest);
                    break;
                }
                embeds.addAll(nextEmbeds);
                requests.add(nextRequest);
                length += nextLength;
            }
            // Keep order of logs
            skippedRequests.forEach(this.queue::addFirst);
            Document logger = request.getLogger();
            Document webhookData = logger.get("webhook", MongoDatabase.EMPTY_DOCUMENT);
            boolean premium = logger.getBoolean("premium");
            WebhookMessage message = new WebhookMessageBuilder().addEmbeds(embeds).setUsername(premium ? webhookData.get("name", "Sx4 - Logger") : "Sx4 - Logger").setAvatarUrl(premium ? webhookData.get("avatar", request.getJDA().getSelfUser().getEffectiveAvatarUrl()) : request.getJDA().getSelfUser().getEffectiveAvatarUrl()).build();
            if (this.webhook == null) {
                if (!webhookData.containsKey("id")) {
                    if (guild.getSelfMember().hasPermission(channel, Permission.MANAGE_WEBHOOKS)) {
                        this.createWebhook(channel, requests);
                        return;
                    }
                    this.handleQueue();
                    return;
                } else {
                    this.webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.webhookExecutor, this.webhookClient);
                }
            }
            this.webhook.send(message).whenComplete((result, exception) -> {
                Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
                if (cause instanceof HttpException && ((HttpException) cause).getCode() == 404) {
                    if (guild.getSelfMember().hasPermission(channel, Permission.MANAGE_WEBHOOKS)) {
                        this.createWebhook(channel, requests);
                        return;
                    }
                    this.disableLogger(channel.getIdLong());
                    return;
                }
                if (ExceptionUtility.sendErrorMessage(exception)) {
                    requests.forEach(failedRequest -> this.queue.addFirst(failedRequest.incrementAttempts()));
                }
                this.handleQueue();
            });
        } catch (Throwable exception) {
            // Continue queue even if an exception occurs to avoid the queue getting stuck
            ExceptionUtility.sendErrorMessage(exception);
            this.handleQueue();
        }
    });
}
Also used : WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) ArrayList(java.util.ArrayList) Guild(net.dv8tion.jda.api.entities.Guild) Document(org.bson.Document) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) HttpException(club.minnced.discord.webhook.exception.HttpException) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel)

Example 13 with WebhookClient

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

the class ModLogManager method editModLog.

public CompletableFuture<club.minnced.discord.webhook.receive.ReadonlyMessage> editModLog(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);
}
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)

Example 14 with WebhookClient

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

the class YouTubeManager method sendYouTubeNotification.

public CompletableFuture<ReadonlyMessage> sendYouTubeNotification(BaseGuildMessageChannel channel, Document webhookData, WebhookMessage message) {
    long channelId = channel.getIdLong();
    WebhookClient webhook;
    if (this.webhooks.containsKey(channelId)) {
        webhook = this.webhooks.get(channelId);
    } else if (!webhookData.containsKey("id")) {
        return this.createWebhook(channel, message);
    } else {
        webhook = new WebhookClient(webhookData.getLong("id"), webhookData.getString("token"), this.scheduledExecutor, this.client);
        this.webhooks.put(channelId, 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(channelId);
            return this.createWebhook(channel, message);
        }
        return CompletableFuture.failedFuture(exception);
    });
}
Also used : Document(org.bson.Document) BotPermissionException(com.sx4.bot.exceptions.mod.BotPermissionException) Request(okhttp3.Request) java.util(java.util) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) HttpCallback(com.sx4.bot.http.HttpCallback) java.util.concurrent(java.util.concurrent) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Channel(net.dv8tion.jda.api.entities.Channel) RequestBody(okhttp3.RequestBody) HttpException(club.minnced.discord.webhook.exception.HttpException) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) Bson(org.bson.conversions.Bson) OkHttpClient(okhttp3.OkHttpClient) MultipartBody(okhttp3.MultipartBody) Sx4(com.sx4.bot.core.Sx4) YouTubeListener(com.sx4.bot.hooks.YouTubeListener) com.sx4.bot.events.youtube(com.sx4.bot.events.youtube) WebhookMessage(club.minnced.discord.webhook.send.WebhookMessage) Clock(java.time.Clock) com.mongodb.client.model(com.mongodb.client.model) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage) WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) HttpException(club.minnced.discord.webhook.exception.HttpException) ReadonlyMessage(com.sx4.bot.entities.webhook.ReadonlyMessage)

Example 15 with WebhookClient

use of com.sx4.bot.entities.webhook.WebhookClient 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)

Aggregations

WebhookClient (com.sx4.bot.entities.webhook.WebhookClient)14 Bson (org.bson.conversions.Bson)13 WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)12 Document (org.bson.Document)11 HttpException (club.minnced.discord.webhook.exception.HttpException)10 ReadonlyMessage (com.sx4.bot.entities.webhook.ReadonlyMessage)10 Permission (net.dv8tion.jda.api.Permission)10 Sx4 (com.sx4.bot.core.Sx4)9 OkHttpClient (okhttp3.OkHttpClient)9 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)8 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)8 BotPermissionException (com.sx4.bot.exceptions.mod.BotPermissionException)7 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)6 CompletableFuture (java.util.concurrent.CompletableFuture)6 com.mongodb.client.model (com.mongodb.client.model)5 Updates (com.mongodb.client.model.Updates)5 HttpCallback (com.sx4.bot.http.HttpCallback)5 java.util (java.util)5 BaseGuildMessageChannel (net.dv8tion.jda.api.entities.BaseGuildMessageChannel)5 User (net.dv8tion.jda.api.entities.User)5