Search in sources :

Example 6 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class FreeGamesCommand method toggle.

@Command(value = "toggle", description = "Enables/disables a free game channel")
@CommandId(484)
@Examples({ "free games toggle", "free games toggle #channel" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void toggle(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true, endless = true) TextChannel channel) {
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
    List<Bson> update = List.of(Operators.set("enabled", Operators.cond(Operators.exists("$enabled"), Operators.REMOVE, false)));
    FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(Projections.include("enabled")).returnDocument(ReturnDocument.AFTER);
    event.getMongo().findAndUpdateFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), update, options).whenComplete((data, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        event.replySuccess("The free game channel in " + effectiveChannel.getAsMention() + " is now **" + (data.get("enabled", true) ? "enabled" : "disabled") + "**").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 7 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class FreeGamesCommand method add.

@Command(value = "add", description = "Add a channel to get free game notifications from Epic Games")
@CommandId(474)
@Examples({ "free games add", "free games add #channel" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Canary
public void add(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true, endless = true) TextChannel channel) {
    TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
    Document data = new Document("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
    event.getMongo().insertFreeGameChannel(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 free games channel in " + effectiveChannel.getAsMention()).queue();
            return;
        }
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        event.replySuccess("Free game notifications will now be sent in " + effectiveChannel.getAsMention()).queue();
    });
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) MongoWriteException(com.mongodb.MongoWriteException) CompletionException(java.util.concurrent.CompletionException) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 8 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class AutoRoleCommand method fix.

@Command(value = "fix", description = "Will give missing members the auto role if needed")
@CommandId(458)
@Examples({ "auto role fix @Role", "auto role fix Role", "auto role fix 406240455622262784" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@BotPermissions(permissions = { Permission.MANAGE_ROLES })
public void fix(Sx4CommandEvent event, @Argument(value = "role", endless = true) Role role) {
    Document data = event.getMongo().getAutoRole(Filters.eq("roleId", role.getIdLong()), Projections.include("filters"));
    if (data == null) {
        event.replyFailure("That role is not an auto role").queue();
        return;
    }
    if (!event.getSelfMember().canInteract(role)) {
        event.replyFailure("That auto role is above my top role").queue();
        return;
    }
    List<Document> filters = data.getList("filters", Document.class, Collections.emptyList());
    List<Member> members = event.getGuild().getMemberCache().applyStream(stream -> stream.filter(member -> AutoRoleUtility.filtersMatch(member, filters) && !member.getRoles().contains(role) && !member.isPending()).collect(Collectors.toList()));
    if (members.size() == 0) {
        event.replyFailure("No users currently need that auto role").queue();
        return;
    }
    if (!this.pending.add(event.getGuild().getIdLong())) {
        event.replyFailure("You already have an auto role fix in progress").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();
    });
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) Member(net.dv8tion.jda.api.entities.Member) TimedArgument(com.sx4.bot.entities.argument.TimedArgument) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) AutoRoleFilter(com.sx4.bot.entities.management.AutoRoleFilter) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) ModuleCategory(com.sx4.bot.category.ModuleCategory) Examples(com.sx4.bot.annotations.command.Examples) AutoRoleUtility(com.sx4.bot.utility.AutoRoleUtility) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ButtonType(com.sx4.bot.entities.interaction.ButtonType) ErrorCategory(com.mongodb.ErrorCategory) CompletableFuture(java.util.concurrent.CompletableFuture) Document(org.bson.Document) Member(net.dv8tion.jda.api.entities.Member) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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 9 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions 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 10 with AuthorPermissions

use of com.sx4.bot.annotations.command.AuthorPermissions in project Sx4 by sx4-discord-bot.

the class GiveawayCommand method setup.

@Command(value = "setup", description = "Setup giveaways for users to react to")
@CommandId(47)
@Examples({ "giveaway setup", "giveaway setup #giveaways 1 7d $10 Nitro" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void setup(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "winners") @DefaultNumber(0) @Limit(min = 1) int winners, @Argument(value = "duration", nullDefault = true) Duration duration, @Argument(value = "item", nullDefault = true, endless = true) String item) {
    if (channel != null && winners != 0 && duration != null && item != null) {
        long seconds = duration.toSeconds();
        if (seconds < 1) {
            event.replyFailure("The duration of a giveaway cannot be less than 1 second").queue();
            return;
        }
        channel.sendMessageEmbeds(this.getEmbed(winners, seconds, item)).queue(message -> {
            message.addReaction("🎉").queue();
            Document data = new Document("messageId", message.getIdLong()).append("channelId", channel.getIdLong()).append("guildId", event.getGuild().getIdLong()).append("winnersAmount", winners).append("endAt", Clock.systemUTC().instant().getEpochSecond() + seconds).append("duration", seconds).append("item", item);
            event.getMongo().insertGiveaway(data).whenComplete((result, exception) -> {
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.getBot().getGiveawayManager().putGiveaway(data, seconds);
                event.reply("Your giveaway has been created in " + channel.getAsMention() + " :tada:").queue();
            });
        });
        return;
    }
    AtomicReference<BaseGuildMessageChannel> atomicChannel = new AtomicReference<>();
    AtomicInteger atomicWinners = new AtomicInteger();
    AtomicReference<Duration> atomicDuration = new AtomicReference<>();
    AtomicReference<String> atomicItem = new AtomicReference<>();
    CompletableFuture.completedFuture(true).thenCompose($ -> {
        if (channel != null) {
            atomicChannel.set(channel);
            return CompletableFuture.completedFuture(true);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        event.reply("What channel would you like to start the giveaway in? Type `cancel` at anytime to cancel the creation.").queue(message -> {
            Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setPredicate(e -> {
                BaseGuildMessageChannel messageChannel = SearchUtility.getBaseMessageChannel(event.getGuild(), e.getMessage().getContentRaw());
                if (messageChannel != null) {
                    atomicChannel.set(messageChannel);
                    return true;
                }
                event.replyFailure("I could not find that channel").queue();
                return false;
            });
            waiter.onCancelled((type) -> {
                event.replySuccess("Cancelled").queue();
                future.complete(false);
            });
            waiter.onTimeout(() -> {
                event.reply("Response timed out :stopwatch:").queue();
                future.complete(false);
            });
            waiter.onSuccess(e -> future.complete(true));
            waiter.start();
        });
        return future;
    }).thenCompose(success -> {
        if (!success) {
            return CompletableFuture.completedFuture(false);
        }
        if (winners != 0) {
            atomicWinners.set(winners);
            return CompletableFuture.completedFuture(true);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        event.reply("How many winners would you like the giveaway to have?").queue(message -> {
            Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
                String content = e.getMessage().getContentRaw();
                if (NumberUtility.isNumberUnsigned(content)) {
                    int number = Integer.parseInt(content);
                    if (number < 1) {
                        event.replyFailure("You have to have at least 1 winner").queue();
                        return false;
                    }
                    atomicWinners.set(number);
                    return true;
                }
                event.replyFailure("That is not a number").queue();
                return false;
            });
            waiter.onCancelled((type) -> {
                event.replySuccess("Cancelled").queue();
                future.complete(false);
            });
            waiter.onTimeout(() -> {
                event.reply("Response timed out :stopwatch:").queue();
                future.complete(false);
            });
            waiter.onSuccess(e -> future.complete(true));
            waiter.start();
        });
        return future;
    }).thenCompose(success -> {
        if (!success) {
            return CompletableFuture.completedFuture(false);
        }
        if (duration != null) {
            atomicDuration.set(duration);
            return CompletableFuture.completedFuture(true);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        event.reply("How long would you like the giveaway to last?").queue(message -> {
            Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
                Duration durationReply = TimeUtility.getDurationFromString(e.getMessage().getContentRaw());
                if (durationReply.toSeconds() < 1) {
                    event.replyFailure("The duration of a giveaway cannot be less than 1 second").queue();
                    return false;
                }
                atomicDuration.set(durationReply);
                return true;
            });
            waiter.onCancelled((type) -> {
                event.replySuccess("Cancelled").queue();
                future.complete(false);
            });
            waiter.onTimeout(() -> {
                event.reply("Response timed out :stopwatch:").queue();
                future.complete(false);
            });
            waiter.onSuccess(e -> future.complete(true));
            waiter.start();
        });
        return future;
    }).thenCompose(success -> {
        if (!success) {
            return CompletableFuture.completedFuture(false);
        }
        if (item != null) {
            atomicItem.set(item);
            return CompletableFuture.completedFuture(true);
        }
        CompletableFuture<Boolean> future = new CompletableFuture<>();
        event.reply("What would you like to giveaway?").queue(message -> {
            Waiter<MessageReceivedEvent> waiter = new Waiter<>(event.getBot(), MessageReceivedEvent.class).setCancelPredicate(e -> e.getMessage().getContentRaw().equalsIgnoreCase("cancel")).setTimeout(30).setUnique(event.getAuthor().getIdLong(), event.getChannel().getIdLong()).setPredicate(e -> {
                String content = e.getMessage().getContentRaw();
                if (content.equalsIgnoreCase("cancel")) {
                    return false;
                }
                atomicItem.set(content);
                return true;
            });
            waiter.onCancelled((type) -> {
                event.replySuccess("Cancelled").queue();
                future.complete(false);
            });
            waiter.onTimeout(() -> {
                event.reply("Response timed out :stopwatch:").queue();
                future.complete(false);
            });
            waiter.onSuccess(e -> future.complete(true));
            waiter.start();
        });
        return future;
    }).thenAccept(success -> {
        if (!success) {
            return;
        }
        BaseGuildMessageChannel channelFuture = atomicChannel.get();
        int winnersFuture = atomicWinners.get();
        long durationFuture = atomicDuration.get().toSeconds();
        String itemFuture = atomicItem.get();
        channelFuture.sendMessageEmbeds(this.getEmbed(winnersFuture, durationFuture, itemFuture)).queue(message -> {
            message.addReaction("🎉").queue();
            Document data = new Document("messageId", message.getIdLong()).append("channelId", channelFuture.getIdLong()).append("guildId", event.getGuild().getIdLong()).append("winnersAmount", winnersFuture).append("endAt", Clock.systemUTC().instant().getEpochSecond() + durationFuture).append("duration", durationFuture).append("item", itemFuture);
            event.getMongo().insertGiveaway(data).whenComplete((result, exception) -> {
                if (ExceptionUtility.sendExceptionally(event, exception)) {
                    return;
                }
                event.getBot().getGiveawayManager().putGiveaway(data, durationFuture);
                event.reply("Your giveaway has been created in " + channelFuture.getAsMention() + " :tada:").queue();
            });
        });
    });
}
Also used : Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) FindOneAndUpdateOptions(com.mongodb.client.model.FindOneAndUpdateOptions) CommandId(com.sx4.bot.annotations.command.CommandId) CompletableFuture(java.util.concurrent.CompletableFuture) PagedResult(com.sx4.bot.paged.PagedResult) AtomicReference(java.util.concurrent.atomic.AtomicReference) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) Waiter(com.sx4.bot.waiter.Waiter) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) ShardManager(net.dv8tion.jda.api.sharding.ShardManager) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) SearchUtility(com.sx4.bot.utility.SearchUtility) ReturnDocument(com.mongodb.client.model.ReturnDocument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) DefaultNumber(com.sx4.bot.annotations.argument.DefaultNumber) Examples(com.sx4.bot.annotations.command.Examples) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) Collections(java.util.Collections) ButtonType(com.sx4.bot.entities.interaction.ButtonType) AtomicReference(java.util.concurrent.atomic.AtomicReference) Duration(java.time.Duration) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) CompletableFuture(java.util.concurrent.CompletableFuture) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Waiter(com.sx4.bot.waiter.Waiter) 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)88 Sx4Command (com.sx4.bot.core.Sx4Command)88 Bson (org.bson.conversions.Bson)52 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)48 CommandId (com.sx4.bot.annotations.command.CommandId)48 Examples (com.sx4.bot.annotations.command.Examples)48 Document (org.bson.Document)48 Argument (com.jockie.bot.core.argument.Argument)26 ModuleCategory (com.sx4.bot.category.ModuleCategory)26 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)26 Permission (net.dv8tion.jda.api.Permission)26 TextChannel (net.dv8tion.jda.api.entities.TextChannel)26 PagedResult (com.sx4.bot.paged.PagedResult)24 BaseGuildMessageChannel (net.dv8tion.jda.api.entities.BaseGuildMessageChannel)24 Operators (com.sx4.bot.database.mongo.model.Operators)23 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)22 CompletionException (java.util.concurrent.CompletionException)22 MessageChannel (net.dv8tion.jda.api.entities.MessageChannel)20 MongoWriteException (com.mongodb.MongoWriteException)19 com.mongodb.client.model (com.mongodb.client.model)19