Search in sources :

Example 81 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) TextChannel 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;
    }
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : 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()) {
                    event.getMongo().insertYouTubeNotification(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 {
            event.getMongo().insertYouTubeNotification(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) TextChannel(net.dv8tion.jda.api.entities.TextChannel) 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) 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) 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) 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) TextChannel(net.dv8tion.jda.api.entities.TextChannel) CompletionException(java.util.concurrent.CompletionException) 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)

Example 82 with AuthorPermissions

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

the class WelcomerCommand method channel.

@Command(value = "channel", description = "Sets the channel where welcomer messages are sent to")
@CommandId(93)
@Examples({ "welcomer channel", "welcomer channel #joins", "welcomer channel reset" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void channel(Sx4CommandEvent event, @Argument(value = "channel | reset", endless = true, nullDefault = true) @AlternativeOptions("reset") Alternative<TextChannel> option) {
    TextChannel channel = option == null ? event.getTextChannel() : option.isAlternative() ? null : option.getValue();
    List<Bson> update = List.of(Operators.set("welcomer.channelId", channel == null ? Operators.REMOVE : channel.getIdLong()), Operators.unset("welcomer.webhook.id"), Operators.unset("welcomer.webhook.token"));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().upsert(true).projection(Projections.include("welcomer.webhook.id", "welcomer.channelId")).returnDocument(ReturnDocument.BEFORE);
    event.getMongo().findAndUpdateGuildById(event.getGuild().getIdLong(), update, options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        long channelId = data == null ? 0L : data.getEmbedded(List.of("welcomer", "channelId"), 0L);
        event.getBot().getWelcomerManager().removeWebhook(channelId);
        if ((channel == null ? 0L : channel.getIdLong()) == channelId) {
            event.replyFailure("The welcomer channel is already " + (channel == null ? "unset" : "set to " + channel.getAsMention())).queue();
            return;
        }
        TextChannel oldChannel = channelId == 0L ? null : event.getGuild().getTextChannelById(channelId);
        long webhookId = data == null ? 0L : data.getEmbedded(List.of("welcomer", "webhook", "id"), 0L);
        if (oldChannel != null && webhookId != 0L) {
            oldChannel.deleteWebhookById(Long.toString(webhookId)).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_WEBHOOK));
        }
        event.replySuccess("The welcomer channel has been " + (channel == null ? "unset" : "set to " + channel.getAsMention())).queue();
    });
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 83 with AuthorPermissions

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

the class LoggerCommand method add.

@Command(value = "add", description = "Adds a logger to a certain channel")
@CommandId(54)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "logger add #logs", "logger add" })
public void add(Sx4CommandEvent event, @Argument(value = "channel", endless = true, nullDefault = true) TextChannel channel) {
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
    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> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", event.getGuild().getIdLong()), Filters.exists("enabled", false))), Aggregates.group(null, Accumulators.sum("count", 1)), Aggregates.limit(25), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("count", "$count"), Accumulators.max("premium", "$premium")), Aggregates.project(Projections.fields(Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.ifNull("$count", 0)))));
    event.getMongo().aggregateLoggers(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")) {
            event.replyFailure("You need to have Sx4 premium to have more than 3 enabled loggers, you can get premium at <https://www.patreon.com/Sx4>").queue();
            return CompletableFuture.completedFuture(null);
        }
        if (count == 25) {
            event.replyFailure("You can not have any more than 25 loggers").queue();
            return CompletableFuture.completedFuture(null);
        }
        Document data = new Document("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
        return event.getMongo().insertLogger(data);
    }).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 logger setup in " + effectiveChannel.getAsMention()).queue();
            return;
        }
        if (ExceptionUtility.sendExceptionally(event, exception) || result == null) {
            return;
        }
        event.replySuccess("You now have a logger setup in " + effectiveChannel.getAsMention()).queue();
    });
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) CompletableFuture(java.util.concurrent.CompletableFuture) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.mongodb.client.model(com.mongodb.client.model) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) LoggerCategory(com.sx4.bot.entities.management.LoggerCategory) Argument(com.jockie.bot.core.argument.Argument) LoggerEvent(com.sx4.bot.entities.management.LoggerEvent) 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) LoggerUtility(com.sx4.bot.utility.LoggerUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ErrorCategory(com.mongodb.ErrorCategory) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MongoWriteException(com.mongodb.MongoWriteException) CompletionException(java.util.concurrent.CompletionException) Document(org.bson.Document) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 84 with AuthorPermissions

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

the class LoggerCommand method remove.

@Command(value = "remove", description = "Removes a logger from a certain channel")
@CommandId(55)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "logger remove #logs", "logger remove" })
public void remove(Sx4CommandEvent event, @Argument(value = "channel", endless = true, nullDefault = true) TextChannel channel) {
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
    FindOneAndDeleteOptions options = new FindOneAndDeleteOptions().projection(Projections.include("webhook.id"));
    event.getMongo().findAndDeleteLogger(Filters.eq("channelId", effectiveChannel.getIdLong()), options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (data == null) {
            event.replyFailure("You don't have a logger in " + effectiveChannel.getAsMention()).queue();
            return;
        }
        event.getBot().getLoggerHandler().removeManager(effectiveChannel.getIdLong());
        Document webhook = data.get("webhook", Document.class);
        if (webhook != null) {
            effectiveChannel.deleteWebhookById(Long.toString(webhook.getLong("id"))).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_WEBHOOK));
        }
        event.replySuccess("You no longer have a logger setup in " + effectiveChannel.getAsMention()).queue();
    });
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 85 with AuthorPermissions

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

the class MediaModeCommand method types.

@Command(value = "types", description = "Sets what types are allowed to be sent in the channel")
@CommandId(352)
@Examples({ "media mode types PNG", "media mode types #media JPG PNG", "media mode types GIF MP4" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void types(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "types") MediaType... types) {
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
    event.getMongo().updateMediaChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), Updates.set("types", MediaType.getRaw(types)), new UpdateOptions()).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure("That media only channel already had those types set").queue();
            return;
        }
        event.replySuccess("Types for that media only channel have been updated").queue();
    });
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) UpdateOptions(com.mongodb.client.model.UpdateOptions) 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)

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