Search in sources :

Example 36 with Sx4

use of com.sx4.bot.core.Sx4 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 37 with Sx4

use of com.sx4.bot.core.Sx4 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)

Example 38 with Sx4

use of com.sx4.bot.core.Sx4 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 39 with Sx4

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

the class LoggerCommand method avatar.

@Command(value = "avatar", description = "Set the avatar of the webhook that sends logs")
@CommandId(424)
@Examples({ "logger avatar #logs Shea#6653", "logger avatar https://i.imgur.com/i87lyNO.png" })
@Premium
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void avatar(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "avatar", endless = true, acceptEmpty = true) @ImageUrl String url) {
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
    event.getMongo().updateLogger(Filters.eq("channelId", effectiveChannel.getIdLong()), Updates.set("webhook.avatar", url)).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure("Your webhook avatar for that logger was already set to that").queue();
            return;
        }
        event.replySuccess("Your webhook avatar has been updated for that logger, this only works with premium <https://patreon.com/Sx4>").queue();
    });
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 40 with Sx4

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

the class LoggerCommand method name.

@Command(value = "name", description = "Set the name of the webhook that sends logs")
@CommandId(423)
@Examples({ "logger name #logs Logs", "logger name Logger" })
@Premium
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void name(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "name", endless = true) String name) {
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
    event.getMongo().updateLogger(Filters.eq("channelId", effectiveChannel.getIdLong()), Updates.set("webhook.name", name)).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure("Your webhook name for that logger was already set to that").queue();
            return;
        }
        event.replySuccess("Your webhook name has been updated for that logger, this only works with premium <https://patreon.com/Sx4>").queue();
    });
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Aggregations

Document (org.bson.Document)28 Sx4Command (com.sx4.bot.core.Sx4Command)24 Command (com.jockie.bot.core.command.Command)23 Bson (org.bson.conversions.Bson)21 Permission (net.dv8tion.jda.api.Permission)19 CompletableFuture (java.util.concurrent.CompletableFuture)16 com.mongodb.client.model (com.mongodb.client.model)14 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)14 Operators (com.sx4.bot.database.mongo.model.Operators)14 CompletionException (java.util.concurrent.CompletionException)13 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)13 Argument (com.jockie.bot.core.argument.Argument)12 ModuleCategory (com.sx4.bot.category.ModuleCategory)12 Sx4 (com.sx4.bot.core.Sx4)12 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)12 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)12 BaseGuildMessageChannel (net.dv8tion.jda.api.entities.BaseGuildMessageChannel)12 CommandId (com.sx4.bot.annotations.command.CommandId)11 Examples (com.sx4.bot.annotations.command.Examples)10 User (net.dv8tion.jda.api.entities.User)10