use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class StarboardCommand method delete.
@Command(value = "delete", aliases = { "remove" }, description = "Deletes a starboard")
@CommandId(204)
@Examples({ "starboard delete 5ff636647f93247aeb2ac429", "starboard delete all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void delete(Sx4CommandEvent event, @Argument(value = "id | all") @AlternativeOptions("all") Alternative<ObjectId> option) {
if (option.isAlternative()) {
List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
event.reply(event.getAuthor().getName() + ", are you sure you want to delete **all** starboards in this server?").setActionRow(buttons).submit().thenCompose(message -> {
return new Waiter<>(event.getBot(), ButtonClickEvent.class).setPredicate(e -> ButtonUtility.handleButtonConfirmation(e, message, event.getAuthor())).setCancelPredicate(e -> ButtonUtility.handleButtonCancellation(e, message, event.getAuthor())).onFailure(e -> ButtonUtility.handleButtonFailure(e, message)).setTimeout(60).start();
}).whenComplete((e, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof CancelException) {
GenericEvent cancelEvent = ((CancelException) cause).getEvent();
if (cancelEvent != null) {
((ButtonClickEvent) cancelEvent).reply("Cancelled " + event.getConfig().getSuccessEmote()).queue();
}
return;
} else if (cause instanceof TimeoutException) {
event.reply("Timed out :stopwatch:").queue();
return;
} else if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getMongo().deleteManyStarboards(Filters.eq("guildId", event.getGuild().getIdLong())).thenCompose(result -> event.getMongo().deleteManyStars(Filters.eq("guildId", event.getGuild().getIdLong()))).whenComplete((result, databaseException) -> {
if (ExceptionUtility.sendExceptionally(event, databaseException)) {
return;
}
if (result.getDeletedCount() == 0) {
e.reply("There are no starboards in this server " + event.getConfig().getFailureEmote()).queue();
return;
}
e.reply("All starboards have been deleted in this server " + event.getConfig().getSuccessEmote()).queue();
});
});
} else {
ObjectId id = option.getValue();
AtomicReference<Document> atomicData = new AtomicReference<>();
event.getMongo().findAndDeleteStarboard(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong()))).thenCompose(data -> {
if (data == null) {
return CompletableFuture.completedFuture(null);
}
atomicData.set(data);
return event.getMongo().deleteManyStars(Filters.eq("messageId", data.getLong("originalMessageId")));
}).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (result == null) {
event.replyFailure("I could not find that starboard").queue();
return;
}
Document data = atomicData.get();
WebhookClient webhook = event.getBot().getStarboardManager().getWebhook(data.getLong("channelId"));
if (webhook != null) {
webhook.delete(data.getLong("messageId"));
}
event.replySuccess("That starboard has been deleted").queue();
});
}
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class SuggestionCommand method set.
@Command(value = "set", description = "Sets a suggestion to a specified state")
@CommandId(86)
@Examples({ "suggestion set 5e45ce6d3688b30ee75201ae pending Need some time to think about this", "suggestion set 5e45ce6d3688b30ee75201ae accepted I think this is a great idea", "suggestion 5e45ce6d3688b30ee75201ae set denied Not possible" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void set(Sx4CommandEvent event, @Argument(value = "id | message", acceptEmpty = true) Or<ObjectId, MessageArgument> argument, @Argument(value = "state") String stateName, @Argument(value = "reason", endless = true, nullDefault = true) String reason) {
Document data = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("suggestion.states", "suggestion.webhook")).get("suggestion", MongoDatabase.EMPTY_DOCUMENT);
List<Document> states = data.getList("states", Document.class, SuggestionState.DEFAULT_STATES);
Document state = states.stream().filter(stateData -> stateData.getString("dataName").equalsIgnoreCase(stateName)).findFirst().orElse(null);
if (state == null) {
event.replyFailure("You do not have a suggestion state with that name").queue();
return;
}
String stateData = state.getString("dataName");
Bson update = Updates.combine(reason == null ? Updates.unset("reason") : Updates.set("reason", reason), Updates.set("state", stateData), Updates.set("moderatorId", event.getAuthor().getIdLong()));
Bson filter = Filters.and(argument.hasFirst() ? Filters.eq("_id", argument.getFirst()) : Filters.eq("messageId", argument.getSecond().getMessageId()), Filters.eq("guildId", event.getGuild().getIdLong()));
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("channelId", "authorId", "reason", "state", "suggestion", "messageId", "image"));
event.getMongo().findAndUpdateSuggestion(filter, update, options).whenComplete((suggestionData, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (suggestionData == null) {
event.replyFailure("There is no suggestion with that id").queue();
return;
}
String reasonData = suggestionData.getString("reason");
boolean reasonMatch = reasonData == null && reason == null || (reasonData != null && reasonData.equals(reason));
if (suggestionData.getString("state").equals(stateData) && reasonMatch) {
event.replyFailure("That suggestion is already in that state and has the same reason").queue();
return;
}
TextChannel channel = event.getGuild().getTextChannelById(suggestionData.getLong("channelId"));
if (channel == null) {
event.replyFailure("The channel for that suggestion no longer exists").queue();
return;
}
User author = event.getShardManager().getUserById(suggestionData.getLong("authorId"));
long messageId = suggestionData.getLong("messageId");
if (author != null) {
author.openPrivateChannel().flatMap(privateChannel -> privateChannel.sendMessage("Your suggestion has been updated by a moderator, click the message link to view it\nhttps://discord.com/channels/" + event.getGuild().getIdLong() + "/" + channel.getIdLong() + "/" + messageId)).queue(null, ErrorResponseException.ignore(ErrorResponse.CANNOT_SEND_TO_USER));
}
WebhookEmbed embed = Suggestion.getWebhookEmbed(suggestionData.getObjectId("_id"), event.getAuthor(), author, suggestionData.getString("suggestion"), suggestionData.getString("image"), reason, new SuggestionState(state));
event.getBot().getSuggestionManager().editSuggestion(messageId, channel.getIdLong(), data.get("webhook", MongoDatabase.EMPTY_DOCUMENT), embed);
event.replySuccess("That suggestion has been set to the `" + stateData + "` state").queue();
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class SuggestionCommand method add.
@Command(value = "add", description = "Sends a suggestion to the suggestion channel if one is setup in the server")
@CommandId(84)
@Redirects({ "suggest" })
@Examples({ "suggestion add Add the dog emote", "suggestion Add a channel for people looking to play games" })
@BotPermissions(permissions = { Permission.MESSAGE_ADD_REACTION, Permission.MESSAGE_EMBED_LINKS })
public void add(Sx4CommandEvent event, @Argument(value = "suggestion", endless = true) String description) {
Document data = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("suggestion.channelId", "suggestion.enabled", "suggestion.webhook", "premium.endAt"));
Document suggestionData = data.get("suggestion", MongoDatabase.EMPTY_DOCUMENT);
if (!suggestionData.getBoolean("enabled", false)) {
event.replyFailure("Suggestions are not enabled in this server").queue();
return;
}
long channelId = suggestionData.get("channelId", 0L);
if (channelId == 0L) {
event.replyFailure("There is no suggestion channel").queue();
return;
}
TextChannel channel = event.getGuild().getTextChannelById(channelId);
if (channel == null) {
event.replyFailure("The suggestion channel no longer exists").queue();
return;
}
SuggestionState state = SuggestionState.PENDING;
String image = event.getMessage().getAttachments().stream().filter(Message.Attachment::isImage).map(Message.Attachment::getUrl).findFirst().orElse(null);
Suggestion suggestion = new Suggestion(channelId, event.getGuild().getIdLong(), event.getAuthor().getIdLong(), description, image, state.getDataName());
boolean premium = Clock.systemUTC().instant().getEpochSecond() < data.getEmbedded(List.of("premium", "endAt"), 0L);
event.getBot().getSuggestionManager().sendSuggestion(channel, suggestionData.get("webhook", MongoDatabase.EMPTY_DOCUMENT), premium, suggestion.getWebhookEmbed(null, event.getAuthor(), state)).whenComplete((message, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
suggestion.setMessageId(message.getId());
event.getMongo().insertSuggestion(suggestion.toData()).whenComplete((result, dataException) -> {
if (ExceptionUtility.sendExceptionally(event, dataException)) {
return;
}
channel.addReactionById(message.getId(), "✅").flatMap($ -> channel.addReactionById(message.getId(), "❌")).queue();
event.replySuccess("Your suggestion has been sent to " + channel.getAsMention()).queue();
});
});
}
use of com.jockie.bot.core.argument.Argument 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.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class SelfRoleCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "role", endless = true) Role role) {
Document selfRole = event.getMongo().getSelfRole(Filters.eq("roleId", role.getIdLong()), Projections.include("_id"));
if (selfRole == null) {
event.replyFailure("That role is not a self role").queue();
return;
}
boolean hasRole = event.getMember().getRoles().contains(role);
RestAction<Void> action;
if (hasRole) {
action = event.getGuild().removeRoleFromMember(event.getMember(), role);
} else {
action = event.getGuild().addRoleToMember(event.getMember(), role);
}
action.flatMap($ -> event.replySuccess("You " + (hasRole ? "no longer" : "now") + " have " + role.getAsMention())).queue();
}
Aggregations