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