Search in sources :

Example 41 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class AntiRegexCommand method set.

@Command(value = "set", description = "Sets the amount of attempts a user has for an anti regex")
@CommandId(460)
@Examples({ "anti regex set 5f023782ef9eba03390a740c @Shea#6653 0", "anti regex set 5f023782ef9eba03390a740c Shea 3", "anti regex set 5f023782ef9eba03390a740c 402557516728369153 2" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void set(Sx4CommandEvent event, @Argument(value = "id") ObjectId id, @Argument(value = "user") Member member, @Argument(value = "attempts") int attempts) {
    Bson filter = Filters.and(Filters.eq("regexId", id), Filters.eq("userId", member.getIdLong()), Filters.eq("guildId", event.getGuild().getIdLong()));
    CompletableFuture<Document> future;
    if (attempts == 0) {
        future = event.getMongo().findAndDeleteRegexAttempt(filter);
    } else {
        FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(Projections.include("attempts")).returnDocument(ReturnDocument.BEFORE).upsert(true);
        future = event.getMongo().findAndUpdateRegexAttempt(filter, Updates.set("attempts", attempts), options);
    }
    future.whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (data == null) {
            event.replyFailure("I could not find that anti regex").queue();
            return;
        }
        if (data.getInteger("attempts") == attempts) {
            event.replyFailure("That users attempts were already set to that").queue();
            return;
        }
        event.replySuccess("**" + member.getUser().getAsTag() + "** has had their attempts set to **" + attempts + "**").queue();
    });
}
Also used : Document(org.bson.Document) Bson(org.bson.conversions.Bson) 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 42 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class TwitchNotificationCommand method add.

@Command(value = "add", description = "Adds a twitch notification to a specific channel")
@CommandId(494)
@Command.Cooldown(5)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "twitch notification add #channel esl_csgo", "twitch notification add pgl" })
public void add(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "streamer name", endless = true) @Lowercase String streamer) {
    MessageChannel messageChannel = event.getChannel();
    if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
        event.replyFailure("You cannot use this channel type").queue();
        return;
    }
    BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
    Request request = new Request.Builder().url("https://api.twitch.tv/helix/users?login=" + URLEncoder.encode(streamer, StandardCharsets.UTF_8)).addHeader("Authorization", "Bearer " + event.getBot().getTwitchConfig().getToken()).addHeader("Client-Id", event.getConfig().getTwitchClientId()).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (response.code() == 400) {
            event.replyFailure("I could not find that twitch streamer").queue();
            response.close();
            return;
        }
        Document json = Document.parse(response.body().string());
        List<Document> entries = json.getList("data", Document.class);
        if (entries.isEmpty()) {
            event.replyFailure("I could not find that twitch streamer").queue();
            return;
        }
        Document data = entries.get(0);
        String id = data.getString("id"), name = data.getString("display_name");
        List<Bson> guildPipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))), Projections.computed("guildId", "$_id"))), Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())));
        List<Bson> countPipeline = List.of(Aggregates.match(Filters.and(Filters.eq("streamerId", id), Filters.exists("enabled", false))), Aggregates.limit(1), Aggregates.group(null, Accumulators.sum("streamerCount", 1)));
        List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())), Aggregates.group(null, Accumulators.push("notifications", Operators.ROOT)), Aggregates.unionWith("twitchNotifications", countPipeline), Aggregates.unionWith("guilds", guildPipeline), AggregateOperators.mergeFields("premium", "notifications", "streamerCount"), Aggregates.project(Projections.fields(Projections.computed("webhook", Operators.first(Operators.map(Operators.filter(Operators.ifNull("$notifications", Collections.EMPTY_LIST), Operators.and(Operators.exists("$$this.webhook"), Operators.eq("$$this.channelId", effectiveChannel.getIdLong()))), "$$this.webhook"))), Projections.computed("subscribe", Operators.eq(Operators.ifNull("$streamerCount", 0), 0)), Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.size(Operators.filter(Operators.ifNull("$notifications", Collections.EMPTY_LIST), Operators.extinct("$$this.enabled")))))));
        AtomicBoolean subscribe = new AtomicBoolean();
        event.getMongo().aggregateTwitchNotifications(pipeline).thenCompose(documents -> {
            Document counter = documents.isEmpty() ? null : documents.get(0);
            int count = counter == null ? 0 : counter.getInteger("count");
            if (counter != null && count >= 3 && !counter.getBoolean("premium")) {
                throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled twitch notifications, you can get premium at <https://www.patreon.com/Sx4>");
            }
            if (count >= 10) {
                throw new IllegalArgumentException("You can not have any more than 10 enabled twitch notifications");
            }
            subscribe.set(counter == null || counter.getBoolean("subscribe"));
            Document notification = new Document("streamerId", id).append("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
            Document webhook = counter == null ? null : counter.get("webhook", Document.class);
            if (webhook != null) {
                notification.append("webhook", webhook);
            }
            return event.getMongo().insertTwitchNotification(notification);
        }).whenComplete((result, exception) -> {
            Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
            if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                event.replyFailure("You already have a notification setup for that twitch streamer in " + effectiveChannel.getAsMention()).queue();
                return;
            }
            if (cause instanceof IllegalArgumentException) {
                event.replyFailure(cause.getMessage()).queue();
                return;
            }
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (subscribe.get()) {
                event.getBot().getTwitchManager().subscribe(id);
            }
            event.replyFormat("Notifications will now be sent in %s when **%s** goes live with id `%s` %s", effectiveChannel.getAsMention(), name, result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
        });
    });
}
Also used : Document(org.bson.Document) TwitchStream(com.sx4.bot.entities.twitch.TwitchStream) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) TwitchManager(com.sx4.bot.managers.TwitchManager) TwitchStreamType(com.sx4.bot.entities.twitch.TwitchStreamType) PagedResult(com.sx4.bot.paged.PagedResult) AggregateOperators(com.sx4.bot.database.mongo.model.AggregateOperators) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) 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) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) java.util(java.util) Command(com.jockie.bot.core.command.Command) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) CommandId(com.sx4.bot.annotations.command.CommandId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Bson(org.bson.conversions.Bson) AdvancedMessage(com.sx4.bot.annotations.argument.AdvancedMessage) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) Argument(com.jockie.bot.core.argument.Argument) Lowercase(com.sx4.bot.annotations.argument.Lowercase) Operators(com.sx4.bot.database.mongo.model.Operators) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) MessageUtility(com.sx4.bot.utility.MessageUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ErrorCategory(com.mongodb.ErrorCategory) MongoWriteException(com.mongodb.MongoWriteException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) CompletionException(java.util.concurrent.CompletionException) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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 43 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class TwitchNotificationCommand method remove.

@Command(value = "remove", description = "Remove a twitch notification by id")
@CommandId(495)
@Command.Cooldown(5)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "twitch notification remove 5e45ce6d3688b30ee75201ae" })
public void remove(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
    FindOneAndDeleteOptions options = new FindOneAndDeleteOptions().projection(Projections.include("channelId", "webhook", "streamerId"));
    event.getMongo().findAndDeleteTwitchNotification(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong())), options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (data == null) {
            event.replyFailure("I could not find that notification").queue();
            return;
        }
        long channelId = data.getLong("channelId");
        String streamerId = data.getString("streamerId");
        event.getBot().getTwitchManager().removeWebhook(channelId);
        BaseGuildMessageChannel channel = event.getGuild().getChannelById(BaseGuildMessageChannel.class, channelId);
        Document webhook = data.get("webhook", Document.class);
        if (webhook != null && channel != null) {
            channel.deleteWebhookById(Long.toString(webhook.getLong("id"))).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_WEBHOOK));
        }
        long count = event.getMongo().countTwitchNotifications(Filters.eq("streamerId", streamerId), new CountOptions().limit(1));
        if (count == 0) {
            event.getBot().getTwitchManager().unsubscribe(streamerId);
        }
        event.replySuccess("You will no longer receive notifications in <#" + channelId + "> for that streamer").queue();
    });
}
Also used : BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Document(org.bson.Document) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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 44 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class TwitchNotificationCommand method toggle.

@Command(value = "toggle", description = "Enables/disables a specific Twitch notification")
@CommandId(496)
@Command.Cooldown(5)
@Examples({ "twitch notification toggle 5e45ce6d3688b30ee75201ae" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void toggle(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
    List<Bson> guildPipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))), Projections.computed("guildId", "$_id"))), Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())));
    List<Bson> countPipeline = List.of(Aggregates.match(Operators.expr(Operators.and(Operators.and(Operators.eq("$streamerId", "$$notification.streamerId"), Operators.extinct("$enabled"))))), Aggregates.limit(2), Aggregates.group(null, Accumulators.sum("streamerCount", 1)));
    List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())), Aggregates.project(Projections.include("streamerId", "enabled")), Aggregates.group(null, Accumulators.push("notifications", Operators.ROOT)), Aggregates.unionWith("guilds", guildPipeline), AggregateOperators.mergeFields("premium", "notifications"), Aggregates.project(Projections.fields(Projections.include("premium", "notifications"), Projections.computed("notification", Operators.first(Operators.filter(Operators.ifNull("$notifications", Collections.EMPTY_LIST), Operators.eq("$$this._id", id)))))), Aggregates.lookup("twitchNotifications", List.of(new Variable<>("notification", "$notification")), countPipeline, "streamerCount"), Aggregates.project(Projections.fields(Projections.computed("streamerId", "$notification.streamerId"), Projections.computed("streamerCount", Operators.cond(Operators.isEmpty("$streamerCount"), 0, Operators.get(Operators.arrayElemAt("$streamerCount", 0), "streamerCount"))), Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.size(Operators.ifNull(Operators.filter("$notifications", Operators.extinct("$$this.enabled")), Collections.EMPTY_LIST))), Projections.computed("disabled", Operators.not(Operators.ifNull("$notification.enabled", true))))));
    AtomicInteger subscribe = new AtomicInteger();
    AtomicReference<String> streamerId = new AtomicReference<>();
    event.getMongo().aggregateTwitchNotifications(pipeline).thenCompose(documents -> {
        Document data = documents.isEmpty() ? null : documents.get(0);
        if (data == null || !data.containsKey("streamerId")) {
            throw new IllegalArgumentException("There is not a twitch notification with that id");
        }
        boolean disabled = data.getBoolean("disabled");
        int count = data.getInteger("count");
        if (disabled && count >= 3 && !data.getBoolean("premium")) {
            throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled twitch notifications, you can get premium at <https://www.patreon.com/Sx4>");
        }
        if (count >= 10) {
            throw new IllegalArgumentException("You can not have any more than 10 enabled twitch notifications");
        }
        int streamerCount = data.getInteger("streamerCount", -1);
        if (disabled && streamerCount == 0) {
            subscribe.set(1);
        } else if (!disabled && streamerCount == 1) {
            subscribe.set(2);
        }
        streamerId.set(data.getString("streamerId"));
        List<Bson> update = List.of(Operators.set("enabled", Operators.cond(Operators.exists("$enabled"), Operators.REMOVE, false)));
        FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER).projection(Projections.include("enabled"));
        return event.getMongo().findAndUpdateTwitchNotification(Filters.eq("_id", id), update, options);
    }).whenComplete((data, exception) -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof IllegalArgumentException) {
            event.replyFailure(cause.getMessage()).queue();
            return;
        }
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (data == null) {
            event.replyFailure("There is not a twitch notification with that id").queue();
            return;
        }
        int value = subscribe.get();
        if (value == 1) {
            event.getBot().getTwitchManager().subscribe(streamerId.get());
        } else if (value == 2) {
            event.getBot().getTwitchManager().unsubscribe(streamerId.get());
        }
        event.replySuccess("That twitch notification is now **" + (data.get("enabled", true) ? "enabled" : "disabled") + "**").queue();
    });
}
Also used : Document(org.bson.Document) TwitchStream(com.sx4.bot.entities.twitch.TwitchStream) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) TwitchManager(com.sx4.bot.managers.TwitchManager) TwitchStreamType(com.sx4.bot.entities.twitch.TwitchStreamType) PagedResult(com.sx4.bot.paged.PagedResult) AggregateOperators(com.sx4.bot.database.mongo.model.AggregateOperators) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) 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) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) java.util(java.util) Command(com.jockie.bot.core.command.Command) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) CommandId(com.sx4.bot.annotations.command.CommandId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Bson(org.bson.conversions.Bson) AdvancedMessage(com.sx4.bot.annotations.argument.AdvancedMessage) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) Argument(com.jockie.bot.core.argument.Argument) Lowercase(com.sx4.bot.annotations.argument.Lowercase) Operators(com.sx4.bot.database.mongo.model.Operators) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) MessageUtility(com.sx4.bot.utility.MessageUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ErrorCategory(com.mongodb.ErrorCategory) AtomicReference(java.util.concurrent.atomic.AtomicReference) Document(org.bson.Document) Bson(org.bson.conversions.Bson) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletionException(java.util.concurrent.CompletionException) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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 45 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class YouTubeNotificationCommand method add.

@Command(value = "add", description = "Add a youtube notification to be posted to a specific channel when the user uploads")
@CommandId(158)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "youtube notification add videos mrbeast", "youtube notification add mrbeast", "youtube notification add #videos pewdiepie" })
public void add(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "youtube channel", endless = true) String channelQuery) {
    if (!event.getBot().getConnectionHandler().isReady()) {
        event.replyFailure("The bot has to be fully started to use this command, try again later").queue();
        return;
    }
    MessageChannel messageChannel = event.getChannel();
    if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
        event.replyFailure("You cannot use this channel type").queue();
        return;
    }
    BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
    boolean id = this.id.matcher(channelQuery).matches();
    boolean search;
    String queryName, query;
    Matcher matcher = this.url.matcher(channelQuery);
    if (!id && matcher.matches()) {
        String path = matcher.group(1);
        search = false;
        queryName = path == null || path.equals("user") ? "forUsername" : "id";
        query = matcher.group(2);
    } else {
        search = !id;
        queryName = id ? "id" : "q";
        query = channelQuery;
    }
    Request channelRequest = new Request.Builder().url("https://www.googleapis.com/youtube/v3/" + (search ? "search" : "channels") + "?key=" + event.getConfig().getYouTube() + "&" + queryName + "=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&part=snippet&type=channel&maxResults=1").build();
    event.getHttpClient().newCall(channelRequest).enqueue((HttpCallback) channelResponse -> {
        Document json = Document.parse(channelResponse.body().string());
        List<Document> items = json.getList("items", Document.class, Collections.emptyList());
        if (items.isEmpty()) {
            event.replyFailure("I could not find that youtube channel").queue();
            return;
        }
        Document item = items.get(0);
        String channelId = search ? item.getEmbedded(List.of("id", "channelId"), String.class) : item.getString("id");
        Document notificationData = new Document("uploaderId", channelId).append("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
        if (!event.getBot().getYouTubeManager().hasExecutor(channelId)) {
            RequestBody body = new MultipartBody.Builder().addFormDataPart("hub.mode", "subscribe").addFormDataPart("hub.topic", "https://www.youtube.com/xml/feeds/videos.xml?channel_id=" + channelId).addFormDataPart("hub.callback", event.getConfig().getBaseUrl() + "/api/youtube").addFormDataPart("hub.verify", "sync").addFormDataPart("hub.verify_token", event.getConfig().getYouTube()).setType(MultipartBody.FORM).build();
            Request request = new Request.Builder().url("https://pubsubhubbub.appspot.com/subscribe").post(body).build();
            event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
                if (response.isSuccessful()) {
                    this.addNotification(event, effectiveChannel.getIdLong(), notificationData).whenComplete((result, exception) -> {
                        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
                        if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                            event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
                            return;
                        }
                        if (ExceptionUtility.sendExceptionally(event, exception)) {
                            return;
                        }
                        event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
                    });
                } else {
                    event.replyFailure("Oops something went wrong there, try again. If this repeats report this to my developer (Message: " + response.body().string() + ")").queue();
                }
            });
        } else {
            this.addNotification(event, effectiveChannel.getIdLong(), notificationData).whenComplete((result, exception) -> {
                Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
                if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
                    event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
                    return;
                }
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
            });
        }
    });
}
Also used : Document(org.bson.Document) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) 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) InsertOneResult(com.mongodb.client.result.InsertOneResult) 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) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) 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) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) 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) Matcher(java.util.regex.Matcher) MongoWriteException(com.mongodb.MongoWriteException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Document(org.bson.Document) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) CompletionException(java.util.concurrent.CompletionException) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) RequestBody(okhttp3.RequestBody) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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)

Aggregations

Command (com.jockie.bot.core.command.Command)88 Sx4Command (com.sx4.bot.core.Sx4Command)88 Bson (org.bson.conversions.Bson)52 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)48 CommandId (com.sx4.bot.annotations.command.CommandId)48 Examples (com.sx4.bot.annotations.command.Examples)48 Document (org.bson.Document)48 Argument (com.jockie.bot.core.argument.Argument)26 ModuleCategory (com.sx4.bot.category.ModuleCategory)26 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)26 Permission (net.dv8tion.jda.api.Permission)26 TextChannel (net.dv8tion.jda.api.entities.TextChannel)26 PagedResult (com.sx4.bot.paged.PagedResult)24 BaseGuildMessageChannel (net.dv8tion.jda.api.entities.BaseGuildMessageChannel)24 Operators (com.sx4.bot.database.mongo.model.Operators)23 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)22 CompletionException (java.util.concurrent.CompletionException)22 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)20 MongoWriteException (com.mongodb.MongoWriteException)19 com.mongodb.client.model (com.mongodb.client.model)19