use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.
the class StarboardHandler method onGuildMessageReactionAdd.
public void onGuildMessageReactionAdd(GuildMessageReactionAddEvent event) {
if (event.getUser().isBot()) {
return;
}
List<Bson> starboardPipeline = List.of(Aggregates.match(Filters.or(Filters.eq("originalMessageId", event.getMessageIdLong()), Filters.eq("messageId", event.getMessageIdLong()))), Aggregates.project(Projections.include("originalMessageId", "channelId")));
List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("_id", event.getGuild().getIdLong())), Aggregates.project(Projections.fields(Projections.include("starboard"), Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))))), Aggregates.unionWith("starboards", starboardPipeline), Aggregates.group(null, Accumulators.max("messageId", "$originalMessageId"), Accumulators.max("channelId", "$channelId"), Accumulators.max("starboard", "$starboard"), Accumulators.max("premium", "$premium")));
this.bot.getMongo().aggregateGuilds(pipeline).whenComplete((documents, aggregateException) -> {
if (ExceptionUtility.sendErrorMessage(aggregateException)) {
return;
}
if (documents.isEmpty()) {
return;
}
Document data = documents.get(0);
Document starboard = data.get("starboard", MongoDatabase.EMPTY_DOCUMENT);
if (!starboard.get("enabled", false)) {
return;
}
long channelId = starboard.get("channelId", 0L), messageChannelId = data.get("channelId", 0L);
TextChannel messageChannel = messageChannelId == 0L ? event.getChannel() : event.getGuild().getTextChannelById(messageChannelId);
TextChannel channel = channelId == 0L ? null : event.getGuild().getTextChannelById(channelId);
if (channel == null || messageChannel == null) {
return;
}
ReactionEmote emote = event.getReactionEmote();
boolean emoji = emote.isEmoji();
Document emoteData = starboard.get("emote", new Document("name", "⭐"));
if ((emoji && !emote.getEmoji().equals(emoteData.getString("name"))) || (!emoji && (!emoteData.containsKey("id") || emoteData.getLong("id") != emote.getIdLong()))) {
return;
}
Long originalMessageId = data.getLong("messageId");
long messageId = originalMessageId == null ? event.getMessageIdLong() : originalMessageId;
messageChannel.retrieveMessageById(messageId).queue(message -> {
String image = message.getAttachments().stream().filter(Attachment::isImage).map(Attachment::getUrl).findFirst().orElse(null);
Document star = new Document("userId", event.getUser().getIdLong()).append("messageId", messageId).append("guildId", event.getGuild().getIdLong());
this.bot.getMongo().insertStar(star).thenCompose(result -> {
Bson update = Updates.combine(Updates.inc("count", 1), Updates.setOnInsert("originalMessageId", messageId), Updates.setOnInsert("guildId", event.getGuild().getIdLong()), Updates.setOnInsert("channelId", event.getChannel().getIdLong()), Updates.set("content", message.getContentRaw()), Updates.set("authorId", message.getAuthor().getIdLong()));
if (image != null) {
update = Updates.combine(update, Updates.set("image", image));
}
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER).upsert(true);
return this.bot.getMongo().findAndUpdateStarboard(Filters.eq("originalMessageId", messageId), update, options);
}).thenCompose(updatedData -> {
WebhookMessage webhookMessage = this.getStarboardMessage(starboard, updatedData, event.getGuild(), event.getMember(), emote, data.getBoolean("premium"));
if (webhookMessage == null) {
return CompletableFuture.completedFuture(null);
}
if (updatedData.containsKey("messageId")) {
this.bot.getStarboardManager().editStarboard(updatedData.getLong("messageId"), channel.getIdLong(), starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
// return null so no update is made in the next stage
return CompletableFuture.completedFuture(null);
} else {
return this.bot.getStarboardManager().sendStarboard(channel, starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
}
}).whenComplete((createdMessage, exception) -> {
if (exception instanceof CompletionException) {
Throwable cause = exception.getCause();
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
// duplicate star just ignore
return;
}
}
if (ExceptionUtility.sendErrorMessage(exception)) {
return;
}
if (createdMessage != null) {
Route.CompiledRoute route = Route.Messages.ADD_REACTION.compile(Long.toString(createdMessage.getChannelId()), Long.toString(createdMessage.getId()), EncodingUtil.encodeReaction(emote.getAsReactionCode()), "@me");
new RestActionImpl<>(event.getJDA(), route).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_EMOJI, ErrorResponse.MISSING_PERMISSIONS, ErrorResponse.MISSING_ACCESS));
this.bot.getMongo().updateStarboard(Filters.eq("originalMessageId", messageId), Updates.set("messageId", createdMessage.getId())).whenComplete(MongoDatabase.exceptionally());
}
});
});
});
}
use of com.sx4.bot.annotations.command.Premium in project Sx4 by sx4-discord-bot.
the class StarboardHandler method onGuildMessageReactionRemove.
public void onGuildMessageReactionRemove(GuildMessageReactionRemoveEvent event) {
User user = event.getUser();
if (user == null || user.isBot()) {
return;
}
List<Bson> starboardPipeline = List.of(Aggregates.match(Filters.or(Filters.eq("originalMessageId", event.getMessageIdLong()), Filters.eq("messageId", event.getMessageIdLong()))), Aggregates.project(Projections.include("originalMessageId", "messageId", "count")));
List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("_id", event.getGuild().getIdLong())), Aggregates.project(Projections.fields(Projections.include("starboard"), Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))))), Aggregates.unionWith("starboards", starboardPipeline), Aggregates.group(null, Accumulators.max("count", "$count"), Accumulators.max("messageId", "$messageId"), Accumulators.max("originalMessageId", "$originalMessageId"), Accumulators.max("starboard", "$starboard"), Accumulators.max("premium", "$premium")));
this.bot.getMongo().aggregateGuilds(pipeline).whenComplete((documents, aggregateException) -> {
if (ExceptionUtility.sendErrorMessage(aggregateException)) {
return;
}
if (documents.isEmpty()) {
return;
}
Document data = documents.get(0);
Document starboard = data.get("starboard", MongoDatabase.EMPTY_DOCUMENT);
if (!starboard.get("enabled", false)) {
return;
}
long channelId = starboard.get("channelId", 0L);
TextChannel channel = channelId == 0L ? null : event.getGuild().getTextChannelById(channelId);
if (channel == null) {
return;
}
ReactionEmote emote = event.getReactionEmote();
boolean emoji = emote.isEmoji();
Document emoteData = starboard.get("emote", new Document("name", "⭐"));
if ((emoji && !emote.getEmoji().equals(emoteData.getString("name"))) || (!emoji && (!emoteData.containsKey("id") || emoteData.getLong("id") != emote.getIdLong()))) {
return;
}
Long originalMessageId = data.getLong("originalMessageId");
if (originalMessageId == null) {
return;
}
List<Document> config = starboard.getList("messages", Document.class, StarboardManager.DEFAULT_CONFIGURATION);
this.bot.getMongo().deleteStarById(event.getUserIdLong(), originalMessageId).thenCompose(result -> {
if (result.getDeletedCount() == 0) {
return CompletableFuture.completedFuture(null);
}
List<Bson> update = List.of(Operators.set("count", Operators.subtract("$count", 1)), Operators.set("messageId", Operators.cond(Operators.isEmpty(Operators.filter(config, Operators.gte(Operators.subtract("$count", 1), "$$this.stars"))), Operators.REMOVE, "$messageId")));
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER);
return this.bot.getMongo().findAndUpdateStarboard(Filters.eq("originalMessageId", originalMessageId), update, options);
}).whenComplete((updatedData, exception) -> {
if (ExceptionUtility.sendErrorMessage(exception) || updatedData == null) {
return;
}
if (!data.containsKey("messageId")) {
return;
}
WebhookMessage webhookMessage = this.getStarboardMessage(starboard, updatedData, event.getGuild(), event.getMember(), emote, data.getBoolean("premium"));
if (webhookMessage == null) {
this.bot.getStarboardManager().deleteStarboard(data.getLong("messageId"), channel.getIdLong(), starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT));
} else {
this.bot.getStarboardManager().editStarboard(data.getLong("messageId"), channel.getIdLong(), starboard.get("webhook", MongoDatabase.EMPTY_DOCUMENT), webhookMessage);
}
});
});
}
use of com.sx4.bot.annotations.command.Premium 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);
});
}
use of com.sx4.bot.annotations.command.Premium 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();
});
}
use of com.sx4.bot.annotations.command.Premium 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();
});
}
Aggregations