Search in sources :

Example 1 with MessageArgument

use of com.sx4.bot.entities.argument.MessageArgument in project Sx4 by sx4-discord-bot.

the class SuggestionCommand method view.

@Command(value = "view", aliases = { "list" }, description = "View a suggestion in the current channel")
@CommandId(87)
@Examples({ "suggestion view 5e45ce6d3688b30ee75201ae", "suggestion view" })
public void view(Sx4CommandEvent event, @Argument(value = "id | message", nullDefault = true, acceptEmpty = true) Or<MessageArgument, ObjectId> argument) {
    Bson filter = Filters.eq("guildId", event.getGuild().getIdLong());
    if (argument != null) {
        filter = Filters.and(filter, argument.hasFirst() ? Filters.eq("messageId", argument.getFirst().getMessageId()) : Filters.eq("_id", argument.getSecond()));
    }
    List<Bson> guildPipeline = List.of(Aggregates.project(Projections.computed("states", Operators.ifNull("$suggestion.states", SuggestionState.getDefaultStates()))), Aggregates.match(Filters.eq("_id", event.getGuild().getIdLong())));
    List<Bson> pipeline = List.of(Aggregates.match(filter), Aggregates.group(null, Accumulators.push("suggestions", Operators.ROOT)), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("states", "$states"), Accumulators.max("suggestions", Operators.ifNull("$suggestions", Collections.EMPTY_LIST))));
    event.getMongo().aggregateSuggestions(pipeline).whenComplete((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        Document data = documents.isEmpty() ? MongoDatabase.EMPTY_DOCUMENT : documents.get(0);
        List<Document> suggestions = data.getList("suggestions", Document.class);
        if (suggestions.isEmpty()) {
            event.replyFailure("There are no suggestions in this server").queue();
            return;
        }
        List<Document> states = data.getList("states", Document.class);
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), suggestions).setIncreasedIndex(true).setDisplayFunction(d -> {
            long authorId = d.getLong("authorId");
            User author = event.getShardManager().getUserById(authorId);
            return String.format("`%s` by %s - **%s**", d.getObjectId("_id").toHexString(), author == null ? authorId : author.getAsTag(), d.getString("state"));
        });
        paged.onSelect(select -> {
            Suggestion suggestion = Suggestion.fromData(select.getSelected());
            event.reply(suggestion.getEmbed(event.getShardManager(), suggestion.getFullState(states))).queue();
        });
        paged.execute(event);
    });
}
Also used : Suggestion(com.sx4.bot.entities.management.Suggestion) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 2 with MessageArgument

use of com.sx4.bot.entities.argument.MessageArgument in project Sx4 by sx4-discord-bot.

the class SuggestionCommand method remove.

@Command(value = "remove", aliases = { "delete" }, description = "Removes a suggestion, can be your own or anyones if you have the manage server permission")
@CommandId(85)
@Examples({ "suggestion remove 5e45ce6d3688b30ee75201ae", "suggestion remove all" })
public void remove(Sx4CommandEvent event, @Argument(value = "id | message | all", acceptEmpty = true) @AlternativeOptions("all") Alternative<Or<MessageArgument, ObjectId>> option) {
    User author = event.getAuthor();
    if (option.isAlternative()) {
        if (!event.hasPermission(event.getMember(), Permission.MANAGE_SERVER)) {
            event.replyFailure("You are missing the permission " + Permission.MANAGE_SERVER.getName() + " to execute this, you can remove your own suggestions only").queue();
            return;
        }
        List<Button> buttons = List.of(Button.success("yes", "Yes"), Button.danger("no", "No"));
        event.reply(author.getName() + ", are you sure you want to delete **all** the suggestions 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().deleteManySuggestions(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
                if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    e.reply("This server has no suggestions " + event.getConfig().getFailureEmote()).queue();
                    return;
                }
                e.reply("All suggestions have been deleted in this server " + event.getConfig().getSuccessEmote()).queue();
            });
        });
    } else {
        Or<MessageArgument, ObjectId> argument = option.getValue();
        boolean hasPermission = event.hasPermission(event.getMember(), Permission.MANAGE_SERVER);
        Bson filter = Filters.and(argument.hasFirst() ? Filters.eq("messageId", argument.getFirst().getMessageId()) : Filters.eq("_id", argument.getSecond()), Filters.eq("guildId", event.getGuild().getIdLong()));
        if (!hasPermission) {
            filter = Filters.and(Filters.eq("authorId", author.getIdLong()), filter);
        }
        event.getMongo().findAndDeleteSuggestion(filter).whenComplete((data, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (data == null) {
                event.replyFailure("I could not find that suggestion").queue();
                return;
            }
            if (data.getLong("authorId") != author.getIdLong() && !hasPermission) {
                event.replyFailure("You do not own that suggestion").queue();
                return;
            }
            WebhookClient webhook = event.getBot().getSuggestionManager().getWebhook(data.getLong("channelId"));
            if (webhook != null) {
                webhook.delete(data.getLong("messageId"));
            }
            event.replySuccess("That suggestion has been removed").queue();
        });
    }
}
Also used : Document(org.bson.Document) CancelException(com.sx4.bot.waiter.exception.CancelException) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) ButtonClickEvent(net.dv8tion.jda.api.events.interaction.ButtonClickEvent) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Suggestion(com.sx4.bot.entities.management.Suggestion) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) TextChannel(net.dv8tion.jda.api.entities.TextChannel) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) ColourUtility(com.sx4.bot.utility.ColourUtility) ButtonUtility(com.sx4.bot.utility.ButtonUtility) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Or(com.sx4.bot.entities.argument.Or) Argument(com.jockie.bot.core.argument.Argument) Message(net.dv8tion.jda.api.entities.Message) 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) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Colour(com.sx4.bot.annotations.argument.Colour) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) SuggestionState(com.sx4.bot.entities.management.SuggestionState) Collections(java.util.Collections) User(net.dv8tion.jda.api.entities.User) WebhookClient(club.minnced.discord.webhook.WebhookClient) ObjectId(org.bson.types.ObjectId) Bson(org.bson.conversions.Bson) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Button(net.dv8tion.jda.api.interactions.components.Button) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) CompletionException(java.util.concurrent.CompletionException) CancelException(com.sx4.bot.waiter.exception.CancelException) Waiter(com.sx4.bot.waiter.Waiter) TimeoutException(com.sx4.bot.waiter.exception.TimeoutException) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 3 with MessageArgument

use of com.sx4.bot.entities.argument.MessageArgument in project Sx4 by sx4-discord-bot.

the class GiveawayCommand method reroll.

@Command(value = "reroll", aliases = { "re roll" }, description = "Rerolls the winners for an ended giveaway")
@CommandId(49)
@Examples({ "giveaway reroll 727224132202397726" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void reroll(Sx4CommandEvent event, @Argument(value = "message id") MessageArgument messageArgument) {
    Document data = event.getMongo().getGiveawayById(messageArgument.getMessageId());
    if (data == null) {
        event.replyFailure("There is no giveaway with that id").queue();
        return;
    }
    if (!data.containsKey("winners")) {
        event.replyFailure("That giveaway has not ended yet").queue();
        return;
    }
    event.getBot().getGiveawayManager().endGiveaway(data, true);
}
Also used : Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) 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)

Example 4 with MessageArgument

use of com.sx4.bot.entities.argument.MessageArgument in project Sx4 by sx4-discord-bot.

the class GiveawayCommand method end.

@Command(value = "end", description = "Ends an active giveaway early")
@CommandId(50)
@Examples({ "giveaway end 727224132202397726" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void end(Sx4CommandEvent event, @Argument(value = "message id") MessageArgument messageArgument) {
    Document data = event.getMongo().getGiveawayById(messageArgument.getMessageId());
    if (data == null) {
        event.replyFailure("There is no giveaway with that id").queue();
        return;
    }
    if (data.containsKey("winners")) {
        event.replyFailure("That giveaway has already ended").queue();
        return;
    }
    event.getBot().getGiveawayManager().endGiveaway(data, true);
}
Also used : Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) 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)

Example 5 with MessageArgument

use of com.sx4.bot.entities.argument.MessageArgument in project Sx4 by sx4-discord-bot.

the class DiscordCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", nullDefault = true) Member member, @Argument(value = "text | message id", endless = true) @Limit(max = 250) Or<MessageArgument, String> option, @Option(value = "light", description = "Sets the discord theme to light") boolean light) {
    if (member == null && option.hasSecond()) {
        event.replyFailure("You need to provide a user when not giving a message").queue();
        return;
    }
    this.getContext(option, member).thenAccept(pair -> {
        Member effectiveMember = pair.getLeft();
        User user = effectiveMember.getUser();
        String text = pair.getRight();
        Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("discord")).addField("name", effectiveMember.getEffectiveName()).addField("avatar", user.getEffectiveAvatarUrl()).addField("bot", user.isBot()).addField("dark_theme", !light).addField("colour", effectiveMember.getColorRaw()).addField("text", text).addAllFields(this.getMentions(event.getShardManager(), event.getGuild(), text)).build(event.getConfig().getImageWebserver());
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
    });
}
Also used : Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) Request(okhttp3.Request) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Permission(net.dv8tion.jda.api.Permission) SearchUtility(com.sx4.bot.utility.SearchUtility) Set(java.util.Set) CompletableFuture(java.util.concurrent.CompletableFuture) HashSet(java.util.HashSet) ModuleCategory(com.sx4.bot.category.ModuleCategory) Pair(net.dv8tion.jda.internal.utils.tuple.Pair) Matcher(java.util.regex.Matcher) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) Or(com.sx4.bot.entities.argument.Or) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)9 Command (com.jockie.bot.core.command.Command)7 Document (org.bson.Document)7 Argument (com.jockie.bot.core.argument.Argument)5 ModuleCategory (com.sx4.bot.category.ModuleCategory)5 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)5 MessageArgument (com.sx4.bot.entities.argument.MessageArgument)5 Permission (net.dv8tion.jda.api.Permission)5 Bson (org.bson.conversions.Bson)5 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)4 CommandId (com.sx4.bot.annotations.command.CommandId)4 Examples (com.sx4.bot.annotations.command.Examples)4 Or (com.sx4.bot.entities.argument.Or)4 PagedResult (com.sx4.bot.paged.PagedResult)4 TextChannel (net.dv8tion.jda.api.entities.TextChannel)4 User (net.dv8tion.jda.api.entities.User)4 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)3 Operators (com.sx4.bot.database.mongo.model.Operators)3 Alternative (com.sx4.bot.entities.argument.Alternative)3 Waiter (com.sx4.bot.waiter.Waiter)3