Search in sources :

Example 1 with WebhookClient

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

the class SuggestionCommand method remove.

@Command(value = "remove", aliases = { "delete" }, description = "Removes a suggestion, can be your own or anyones if you have the manage server permission")
@CommandId(85)
@Examples({ "suggestion remove 5e45ce6d3688b30ee75201ae", "suggestion remove all" })
public void remove(Sx4CommandEvent event, @Argument(value = "id | message | all", acceptEmpty = true) @AlternativeOptions("all") Alternative<Or<MessageArgument, ObjectId>> option) {
    User author = event.getAuthor();
    if (option.isAlternative()) {
        if (!event.hasPermission(event.getMember(), Permission.MANAGE_SERVER)) {
            event.replyFailure("You are missing the permission " + Permission.MANAGE_SERVER.getName() + " to execute this, you can remove your own suggestions only").queue();
            return;
        }
        List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
        event.reply(author.getName() + ", are you sure you want to delete **all** the suggestions in this server?").setActionRow(buttons).submit().thenCompose(message -> {
            return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
        }).whenComplete((e, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof CancelException) {
                GenericEvent cancelEvent = ((CancelException) cause).getEvent();
                if (cancelEvent != null) {
                    ((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
                }
                return;
            } else if (cause instanceof TimeoutException) {
                event.reply("Timed out :stopwatch:").queue();
                return;
            } else if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            event.getMongo().deleteManySuggestions(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
                if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    e.reply("This server has no suggestions " + event.getConfig().getFailureEmote()).queue();
                    return;
                }
                e.reply("All suggestions have been deleted in this server " + event.getConfig().getSuccessEmote()).queue();
            });
        });
    } else {
        Or<MessageArgument, ObjectId> argument = option.getValue();
        boolean hasPermission = event.hasPermission(event.getMember(), Permission.MANAGE_SERVER);
        Bson filter = Filters.and(argument.hasFirst() ? Filters.eq("messageId", argument.getFirst().getMessageId()) : Filters.eq("_id", argument.getSecond()), Filters.eq("guildId", event.getGuild().getIdLong()));
        if (!hasPermission) {
            filter = Filters.and(Filters.eq("authorId", author.getIdLong()), filter);
        }
        event.getMongo().findAndDeleteSuggestion(filter).whenComplete((data, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (data == null) {
                event.replyFailure("I could not find that suggestion").queue();
                return;
            }
            if (data.getLong("authorId") != author.getIdLong() && !hasPermission) {
                event.replyFailure("You do not own that suggestion").queue();
                return;
            }
            WebhookClient webhook = event.getBot().getSuggestionManager().getWebhook(data.getLong("channelId"));
            if (webhook != null) {
                webhook.delete(data.getLong("messageId"));
            }
            event.replySuccess("That suggestion has been removed").queue();
        });
    }
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Suggestion(com.sx4.bot.entities.management.Suggestion) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) ColourUtility(com.sx4.bot.utility.ColourUtility) ButtonUtility(com.sx4.bot.utility.ButtonUtility) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Or(com.sx4.bot.entities.argument.Or) Argument(com.jockie.bot.core.argument.Argument) Message(net.dv8tion.jda.api.entities.Message) Operators(com.sx4.bot.database.mongo.model.Operators) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Colour(com.sx4.bot.annotations.argument.Colour) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) SuggestionState(com.sx4.bot.entities.management.SuggestionState) Collections(java.util.Collections) User(net.dv8tion.jda.api.entities.User) WebhookClient(club.minnced.discord.webhook.WebhookClient) ObjectId(org.bson.types.ObjectId) Bson(org.bson.conversions.Bson) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 2 with WebhookClient

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

the class ModLogCommand method remove.

@Command(value = "delete", aliases = { "remove" }, description = "Deletes a mod log from the  server")
@CommandId(69)
@Examples({ "modlog delete 5e45ce6d3688b30ee75201ae", "modlog delete all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void remove(Sx4CommandEvent event, @Argument(value = "id | all") @AlternativeOptions("all") Alternative<ObjectId> option) {
    User author = event.getAuthor();
    if (option.isAlternative()) {
        List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
        event.reply(author.getName() + ", are you sure you want to delete **all** the suggestions in this server?").setActionRow(buttons).submit().thenCompose(message -> {
            return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
        }).whenComplete((e, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof CancelException) {
                GenericEvent cancelEvent = ((CancelException) cause).getEvent();
                if (cancelEvent != null) {
                    ((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
                }
                return;
            } else if (cause instanceof TimeoutException) {
                event.reply("Timed out :stopwatch:").queue();
                return;
            } else if (ExceptionUtility.sendExceptionally(event, cause)) {
                return;
            }
            event.getMongo().deleteManyModLogs(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
                if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    e.reply("There are no mod logs in this server " + event.getConfig().getFailureEmote()).queue();
                    return;
                }
                e.reply("All your mod logs have been deleted " + event.getConfig().getSuccessEmote()).queue();
            });
        });
    } else {
        ObjectId id = option.getValue();
        event.getMongo().findAndDeleteModLog(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong()))).whenComplete((data, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (data == null) {
                event.replyFailure("I could not find that mod log").queue();
                return;
            }
            WebhookClient webhook = event.getBot().getModLogManager().getWebhook(data.getLong("channelId"));
            if (webhook != null) {
                webhook.delete(data.getLong("messageId"));
            }
            event.replySuccess("That mod log has been deleted").queue();
        });
    }
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Pair(net.dv8tion.jda.internal.utils.tuple.Pair) ButtonUtility(com.sx4.bot.utility.ButtonUtility) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Reason(com.sx4.bot.entities.mod.Reason) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) Range(com.sx4.bot.entities.argument.Range) Argument(com.jockie.bot.core.argument.Argument) Action(com.sx4.bot.entities.mod.action.Action) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Premium(com.sx4.bot.annotations.command.Premium) ModuleCategory(com.sx4.bot.category.ModuleCategory) ModLog(com.sx4.bot.entities.mod.ModLog) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) User(net.dv8tion.jda.api.entities.User) WebhookClient(club.minnced.discord.webhook.WebhookClient) Button(net.dv8tion.jda.api.interactions.components.Button) ObjectId(org.bson.types.ObjectId) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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)

Example 3 with WebhookClient

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

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

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

the class LoggerManager method createWebhook.

private void createWebhook(TextChannel channel, List<Request> requests) {
    channel.createWebhook("Sx4 - Logger").submit().whenComplete((webhook, exception) -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof ErrorResponseException && ((ErrorResponseException) cause).getErrorResponse() == ErrorResponse.MAX_WEBHOOKS) {
            this.disableLogger(channel.getIdLong());
            return;
        }
        if (ExceptionUtility.sendErrorMessage(exception)) {
            requests.forEach(failedRequest -> this.queue.addFirst(failedRequest.incrementAttempts()));
            this.handleQueue();
            return;
        }
        this.webhook = new WebhookClient(webhook.getIdLong(), webhook.getToken(), this.webhookExecutor, this.webhookClient);
        Bson update = Updates.combine(Updates.set("webhook.id", webhook.getIdLong()), Updates.set("webhook.token", webhook.getToken()));
        this.bot.getMongo().updateLogger(Filters.eq("channelId", channel.getIdLong()), update, new UpdateOptions()).whenComplete((result, databaseException) -> {
            ExceptionUtility.sendErrorMessage(databaseException);
            requests.forEach(failedRequest -> this.queue.addFirst(failedRequest.incrementAttempts()));
            this.handleQueue();
        });
    });
}
Also used : WebhookClient(com.sx4.bot.entities.webhook.WebhookClient) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson)

Aggregations

WebhookClient (com.sx4.bot.entities.webhook.WebhookClient)8 TextChannel (net.dv8tion.jda.api.entities.TextChannel)8 Document (org.bson.Document)8 Bson (org.bson.conversions.Bson)8 WebhookMessage (club.minnced.discord.webhook.send.WebhookMessage)7 Permission (net.dv8tion.jda.api.Permission)7 User (net.dv8tion.jda.api.entities.User)7 HttpException (club.minnced.discord.webhook.exception.HttpException)5 WebhookMessageBuilder (club.minnced.discord.webhook.send.WebhookMessageBuilder)5 com.mongodb.client.model (com.mongodb.client.model)5 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)5 ReadonlyMessage (com.sx4.bot.entities.webhook.ReadonlyMessage)5 CompletionException (java.util.concurrent.CompletionException)5 WebhookEmbed (club.minnced.discord.webhook.send.WebhookEmbed)4 Operators (com.sx4.bot.database.mongo.model.Operators)4 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)4 WebhookClient (club.minnced.discord.webhook.WebhookClient)3 Argument (com.jockie.bot.core.argument.Argument)3 Command (com.jockie.bot.core.command.Command)3 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)3