Search in sources :

Example 1 with Alternative

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

the class StarboardCommand method emote.

@Command(value = "emote", aliases = { "emoji" }, description = "Sets the emote/emoji to be used for starboard")
@CommandId(199)
@Examples({ "starboard emote ☝️", "starboard emote <:upvote:761345612079693865>", "starboard emote reset" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void emote(Sx4CommandEvent event, @Argument(value = "emote | reset", endless = true) @AlternativeOptions("reset") Alternative<ReactionEmote> option) {
    ReactionEmote emote = option.getValue();
    boolean emoji = emote != null && emote.isEmoji();
    List<Bson> update = emote == null ? List.of(Operators.unset("starboard.emote")) : List.of(Operators.set("starboard.emote." + (emoji ? "name" : "id"), emoji ? emote.getEmoji() : emote.getIdLong()), Operators.unset("starboard.emote." + (emoji ? "id" : "name")));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).upsert(true).projection(Projections.include("starboard.emote"));
    event.getMongo().findAndUpdateGuildById(event.getGuild().getIdLong(), update, options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        Document emoteData = data == null ? null : data.getEmbedded(List.of("starboard", "emote"), Document.class);
        if ((emote == null && emoteData == null) || (emote != null && emoteData != null && (emoji ? emote.getEmoji().equals(emoteData.getString("name")) : emoteData.getLong("id") == emote.getIdLong()))) {
            event.replyFailure("Your starboard emote was already " + (emote == null ? "unset" : "set to that")).queue();
            return;
        }
        event.replySuccess("Your starboard emote has been " + (emote == null ? "unset" : "updated")).queue();
    });
}
Also used : Document(org.bson.Document) ReactionEmote(net.dv8tion.jda.api.entities.MessageReaction.ReactionEmote) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 2 with Alternative

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

the class SuggestionCommand method channel.

@Command(value = "channel", description = "Sets the channel where suggestions are set to")
@CommandId(83)
@Examples({ "suggestion channel", "suggestion channel #suggestions", "suggestion channel reset" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void channel(Sx4CommandEvent event, @Argument(value = "channel | reset", endless = true, nullDefault = true) @AlternativeOptions("reset") Alternative<TextChannel> option) {
    TextChannel channel = option == null ? event.getTextChannel() : option.isAlternative() ? null : option.getValue();
    List<Bson> update = List.of(Operators.set("suggestion.channelId", channel == null ? Operators.REMOVE : channel.getIdLong()), Operators.unset("suggestion.webhook.id"), Operators.unset("suggestion.webhook.token"));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.BEFORE).projection(Projections.include("suggestion.webhook.id", "suggestion.channelId")).upsert(true);
    event.getMongo().findAndUpdateGuildById(event.getGuild().getIdLong(), update, options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        long channelId = data == null ? 0L : data.getEmbedded(List.of("suggestion", "channelId"), 0L);
        event.getBot().getSuggestionManager().removeWebhook(channelId);
        if ((channel == null ? 0L : channel.getIdLong()) == channelId) {
            event.replyFailure("The suggestion channel is already " + (channel == null ? "unset" : "set to " + channel.getAsMention())).queue();
            return;
        }
        TextChannel oldChannel = channelId == 0L ? null : event.getGuild().getTextChannelById(channelId);
        long webhookId = data == null ? 0L : data.getEmbedded(List.of("suggestion", "webhook", "id"), 0L);
        if (oldChannel != null && webhookId != 0L) {
            oldChannel.deleteWebhookById(Long.toString(webhookId)).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_WEBHOOK));
        }
        event.replySuccess("The suggestion channel has been " + (channel == null ? "unset" : "set to " + channel.getAsMention())).queue();
    });
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 3 with Alternative

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

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

the class RoleCommand method add.

@Command(value = "add", description = "Add a role to a member")
@CommandId(250)
@Redirects({ "addrole", "add role", "ar" })
@Examples({ "role add @Shea#6653 Role", "role add Shea 345718366373150720", "role add @Role" })
@AuthorPermissions(permissions = { Permission.MANAGE_ROLES })
@BotPermissions(permissions = { Permission.MANAGE_ROLES })
public void add(Sx4CommandEvent event, @Argument(value = "user", nullDefault = true) @AlternativeOptions("all") Alternative<Member> option, @Argument(value = "role", endless = true) Role role) {
    if (role.isManaged()) {
        event.replyFailure("I cannot give managed roles").queue();
        return;
    }
    if (role.isPublicRole()) {
        event.replyFailure("I cannot give the @everyone role").queue();
        return;
    }
    if (!event.getMember().canInteract(role)) {
        event.replyFailure("You cannot give a role higher or equal than your top role").queue();
        return;
    }
    if (!event.getSelfMember().canInteract(role)) {
        event.replyFailure("I cannot give a role higher or equal than my top role").queue();
        return;
    }
    if (option != null && option.isAlternative()) {
        List<Member> members = event.getGuild().getMemberCache().applyStream(stream -> stream.filter(member -> !member.getRoles().contains(role)).collect(Collectors.toList()));
        if (members.size() == 0) {
            event.replyFailure("All users already have that role").queue();
            return;
        }
        if (!this.pending.add(event.getGuild().getIdLong())) {
            event.replyFailure("You can only have 1 concurrent role being added to all users").queue();
            return;
        }
        event.replyFormat("Adding %s to **%,d** user%s, another message will be sent once this is done %s", role.getAsMention(), members.size(), members.size() == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
        List<CompletableFuture<Integer>> futures = new ArrayList<>();
        for (Member member : members) {
            futures.add(event.getGuild().addRoleToMember(member, role).submit().handle((result, exception) -> exception == null ? 1 : 0));
        }
        FutureUtility.allOf(futures).whenComplete((completed, exception) -> {
            this.pending.remove(event.getGuild().getIdLong());
            int count = completed.stream().reduce(0, Integer::sum);
            event.replyFormat("Successfully added the role %s to **%,d/%,d** user%s %s", role.getAsMention(), count, members.size(), count == 1 ? "" : "s", event.getConfig().getSuccessEmote()).queue();
        });
    } else {
        Member effectiveMember = option == null ? event.getMember() : option.getValue();
        event.getGuild().addRoleToMember(effectiveMember, role).flatMap($ -> event.replySuccess(role.getAsMention() + " has been added to **" + effectiveMember.getUser().getAsTag() + "**")).queue();
    }
}
Also used : Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) Set(java.util.Set) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) Colour(com.sx4.bot.annotations.argument.Colour) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ModuleCategory(com.sx4.bot.category.ModuleCategory) Alternative(com.sx4.bot.entities.argument.Alternative) List(java.util.List) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Option(com.jockie.bot.core.option.Option) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) FutureUtility(com.sx4.bot.utility.FutureUtility) com.sx4.bot.annotations.command(com.sx4.bot.annotations.command) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) CompletableFuture(java.util.concurrent.CompletableFuture) ArrayList(java.util.ArrayList) Member(net.dv8tion.jda.api.entities.Member) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 5 with Alternative

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

the class ModLogCommand method remove.

@Command(value = "delete", aliases = { "remove" }, description = "Deletes a mod log from the  server")
@CommandId(69)
@Examples({ "modlog delete 5e45ce6d3688b30ee75201ae", "modlog delete all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void remove(Sx4CommandEvent event, @Argument(value = "id | all") @AlternativeOptions("all") Alternative<ObjectId> option) {
    User author = event.getAuthor();
    if (option.isAlternative()) {
        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, cause)) {
                return;
            }
            event.getMongo().deleteManyModLogs(Filters.eq("guildId", event.getGuild().getIdLong())).whenComplete((result, databaseException) -> {
                if (ExceptionUtility.sendExceptionally(event, databaseException)) {
                    return;
                }
                if (result.getDeletedCount() == 0) {
                    e.reply("There are no mod logs in this server " + event.getConfig().getFailureEmote()).queue();
                    return;
                }
                e.reply("All your mod logs have been deleted " + event.getConfig().getSuccessEmote()).queue();
            });
        });
    } else {
        ObjectId id = option.getValue();
        event.getMongo().findAndDeleteModLog(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong()))).whenComplete((data, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (data == null) {
                event.replyFailure("I could not find that mod log").queue();
                return;
            }
            WebhookClient webhook = event.getBot().getModLogManager().getWebhook(data.getLong("channelId"));
            if (webhook != null) {
                webhook.delete(data.getLong("messageId"));
            }
            event.replySuccess("That mod log has been deleted").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) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) 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) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Pair(net.dv8tion.jda.internal.utils.tuple.Pair) ButtonUtility(com.sx4.bot.utility.ButtonUtility) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Button(net.dv8tion.jda.api.interactions.components.Button) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Reason(com.sx4.bot.entities.mod.Reason) Waiter(com.sx4.bot.waiter.Waiter) GenericEvent(net.dv8tion.jda.api.events.GenericEvent) com.mongodb.client.model(com.mongodb.client.model) Range(com.sx4.bot.entities.argument.Range) Argument(com.jockie.bot.core.argument.Argument) Action(com.sx4.bot.entities.mod.action.Action) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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) Premium(com.sx4.bot.annotations.command.Premium) ModuleCategory(com.sx4.bot.category.ModuleCategory) ModLog(com.sx4.bot.entities.mod.ModLog) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) User(net.dv8tion.jda.api.entities.User) WebhookClient(club.minnced.discord.webhook.WebhookClient) Button(net.dv8tion.jda.api.interactions.components.Button) ObjectId(org.bson.types.ObjectId) 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) 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)

Aggregations

Command (com.jockie.bot.core.command.Command)24 Sx4Command (com.sx4.bot.core.Sx4Command)24 Bson (org.bson.conversions.Bson)21 CommandId (com.sx4.bot.annotations.command.CommandId)16 Examples (com.sx4.bot.annotations.command.Examples)16 Document (org.bson.Document)15 Argument (com.jockie.bot.core.argument.Argument)14 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)14 ModuleCategory (com.sx4.bot.category.ModuleCategory)14 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)14 Alternative (com.sx4.bot.entities.argument.Alternative)14 PagedResult (com.sx4.bot.paged.PagedResult)13 Permission (net.dv8tion.jda.api.Permission)13 Waiter (com.sx4.bot.waiter.Waiter)12 CancelException (com.sx4.bot.waiter.exception.CancelException)12 TimeoutException (com.sx4.bot.waiter.exception.TimeoutException)12 List (java.util.List)12 CompletionException (java.util.concurrent.CompletionException)12 GenericEvent (net.dv8tion.jda.api.events.GenericEvent)12 ButtonClickEvent (net.dv8tion.jda.api.events.interaction.ButtonClickEvent)12