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();
});
}
});
}
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();
});
}
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();
});
}
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();
});
}
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();
});
}
Aggregations