Search in sources :

Example 1 with Or

use of com.sx4.bot.entities.argument.Or 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 Or

use of com.sx4.bot.entities.argument.Or 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 Or

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

the class WelcomerCommand method screening.

@Command(value = "screening", aliases = { "member screening" }, description = "Toggles whether the bot should send a welcomer message after or before a member has gone through member screening")
@CommandId(461)
@Examples({ "welcomer screening" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void screening(Sx4CommandEvent event) {
    List<Bson> update = List.of(Operators.set("welcomer.screening", Operators.cond(Operators.exists("$welcomer.screening"), Operators.REMOVE, false)));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER).projection(Projections.include("welcomer.screening")).upsert(true);
    event.getMongo().findAndUpdateGuildById(event.getGuild().getIdLong(), update, options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        event.replySuccess("Welcomer will now send a message " + (data.getEmbedded(List.of("welcomer", "screening"), true) ? "after" : "before") + " member screening").queue();
    });
}
Also used : FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 4 with Or

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

the class HelpCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "command | module", endless = true, nullDefault = true) String commandName) {
    boolean embed = !event.isFromGuild() || event.getGuild().getSelfMember().hasPermission(event.getTextChannel(), Permission.MESSAGE_EMBED_LINKS);
    if (commandName == null) {
        List<Sx4Category> categories = Arrays.stream(ModuleCategory.ALL_ARRAY).filter(category -> !category.getCommands(event.isAuthorDeveloper()).isEmpty()).collect(Collectors.toList());
        PagedResult<Sx4Category> paged = new PagedResult<>(event.getBot(), categories).setPerPage(categories.size()).setSelect(SelectType.OBJECT).setSelectablePredicate((content, category) -> category.getName().equalsIgnoreCase(content) || Arrays.stream(category.getAliases()).anyMatch(content::equalsIgnoreCase)).setCustomFunction(page -> {
            MessageBuilder builder = new MessageBuilder();
            EmbedBuilder embedBuilder = new EmbedBuilder();
            embedBuilder.setAuthor("Help", null, event.getSelfUser().getEffectiveAvatarUrl());
            embedBuilder.setFooter(event.getPrefix() + "help <module> or respond below with a name of a module", event.getAuthor().getEffectiveAvatarUrl());
            embedBuilder.setDescription("All commands are put in a set category also known as a module, use `" + event.getPrefix() + "help <module>` on the module of your choice, The bot will then " + "list all the commands in that module. If you need further help feel free to join the [support server](https://discord.gg/PqJNcfB).");
            embedBuilder.addField("Modules", "`" + categories.stream().map(Sx4Category::getName).collect(Collectors.joining("`, `")) + "`", false);
            return builder.setEmbeds(embedBuilder.build());
        });
        paged.onSelect(select -> {
            Sx4Category category = select.getSelected();
            List<Sx4Command> categoryCommands = category.getCommands(event.isAuthorDeveloper()).stream().map(Sx4Command.class::cast).sorted(Comparator.comparing(Sx4Command::getCommandTrigger)).collect(Collectors.toList());
            PagedResult<Sx4Command> categoryPaged = HelpUtility.getCommandsPaged(event.getBot(), categoryCommands).setAuthor(category.getName(), null, event.getAuthor().getEffectiveAvatarUrl());
            categoryPaged.onSelect(categorySelect -> event.reply(HelpUtility.getHelpMessage(categorySelect.getSelected(), embed)).queue());
            categoryPaged.execute(event);
        });
        paged.execute(event);
    } else {
        Sx4Category category = SearchUtility.getModule(commandName);
        List<Sx4Command> commands = SearchUtility.getCommands(event.getCommandListener(), commandName, event.isAuthorDeveloper());
        if (category != null) {
            List<Sx4Command> categoryCommands = category.getCommands(event.isAuthorDeveloper()).stream().map(Sx4Command.class::cast).sorted(Comparator.comparing(Sx4Command::getCommandTrigger)).collect(Collectors.toList());
            PagedResult<Sx4Command> paged = HelpUtility.getCommandsPaged(event.getBot(), categoryCommands).setAuthor(category.getName(), null, event.getAuthor().getEffectiveAvatarUrl());
            paged.onSelect(select -> event.reply(HelpUtility.getHelpMessage(select.getSelected(), embed)).queue());
            paged.execute(event);
        } else if (!commands.isEmpty()) {
            PagedResult<Sx4Command> paged = new PagedResult<>(event.getBot(), commands).setAuthor(commandName, null, event.getAuthor().getEffectiveAvatarUrl()).setAutoSelect(true).setPerPage(15).setSelectablePredicate((content, command) -> command.getCommandTrigger().equals(content)).setDisplayFunction(Sx4Command::getUsage);
            paged.onSelect(select -> event.reply(HelpUtility.getHelpMessage(select.getSelected(), embed)).queue());
            paged.execute(event);
        } else {
            event.replyFailure("I could not find that command/module").queue();
        }
    }
}
Also used : Arrays(java.util.Arrays) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) SearchUtility(com.sx4.bot.utility.SearchUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) HelpUtility(com.sx4.bot.utility.HelpUtility) Sx4Category(com.sx4.bot.core.Sx4Category) List(java.util.List) SelectType(com.sx4.bot.paged.PagedResult.SelectType) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Comparator(java.util.Comparator) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Sx4Command(com.sx4.bot.core.Sx4Command) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4Category(com.sx4.bot.core.Sx4Category) PagedResult(com.sx4.bot.paged.PagedResult)

Example 5 with Or

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

the class MoveCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", nullDefault = true) Member member, @Argument(value = "voice channel", nullDefault = true) VoiceChannel channel) {
    if (member == null && channel == null) {
        event.replyFailure("Either a user or voice channel needs to be provided").queue();
        return;
    }
    Member effectiveMember = member == null ? event.getMember() : member;
    VoiceChannel memberChannel = effectiveMember.getVoiceState().getChannel();
    if (memberChannel == null) {
        event.replyFailure("That user is not in a voice channel").queue();
        return;
    }
    VoiceChannel effectiveChannel = channel == null ? event.getMember().getVoiceState().getChannel() : channel;
    if (effectiveChannel == null) {
        event.replyFailure("You are not in a voice channel").queue();
        return;
    }
    if (memberChannel.getIdLong() == effectiveChannel.getIdLong()) {
        event.replyFailure("You cannot move a user to the channel they are already connected to").queue();
        return;
    }
    if (!PermissionUtility.canConnect(event.getSelfMember(), effectiveChannel)) {
        event.replyFailure("I cannot move people to that voice channel").queue();
        return;
    }
    if (!PermissionUtility.canConnect(event.getMember(), effectiveChannel)) {
        event.replyFailure("You cannot move people to that voice channel").queue();
        return;
    }
    event.getGuild().moveVoiceMember(effectiveMember, effectiveChannel).flatMap($ -> event.replySuccess("Moved **" + effectiveMember.getUser().getAsTag() + "** to `" + effectiveChannel.getName() + "`")).queue();
}
Also used : ModuleCategory(com.sx4.bot.category.ModuleCategory) PermissionUtility(com.sx4.bot.utility.PermissionUtility) VoiceChannel(net.dv8tion.jda.api.entities.VoiceChannel) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Permission(net.dv8tion.jda.api.Permission) Member(net.dv8tion.jda.api.entities.Member) Argument(com.jockie.bot.core.argument.Argument) VoiceChannel(net.dv8tion.jda.api.entities.VoiceChannel) Member(net.dv8tion.jda.api.entities.Member)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)36 Command (com.jockie.bot.core.command.Command)25 Document (org.bson.Document)25 Argument (com.jockie.bot.core.argument.Argument)19 ModuleCategory (com.sx4.bot.category.ModuleCategory)19 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)19 Bson (org.bson.conversions.Bson)17 CommandId (com.sx4.bot.annotations.command.CommandId)16 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)16 Examples (com.sx4.bot.annotations.command.Examples)15 PagedResult (com.sx4.bot.paged.PagedResult)15 Permission (net.dv8tion.jda.api.Permission)15 Member (net.dv8tion.jda.api.entities.Member)13 List (java.util.List)12 CompletionException (java.util.concurrent.CompletionException)10 Option (com.jockie.bot.core.option.Option)8 Collectors (java.util.stream.Collectors)8 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)8 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)7 Operators (com.sx4.bot.database.mongo.model.Operators)7