Search in sources :

Example 11 with Redirects

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

the class ReputationCommand method leaderboard.

@Command(value = "leaderboard", aliases = { "lb" }, description = "View the leaderboard for reputation across the bot")
@CommandId(421)
@Redirects({ "leaderboard reputation", "lb rep", "lb reputation", "leaderboard rep" })
@Examples({ "reputation leaderboard", "reputation leaderboard --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void leaderboard(Sx4CommandEvent event, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
    List<Bson> pipeline = List.of(Aggregates.project(Projections.computed("reputation", "$reputation.amount")), Aggregates.match(Filters.exists("reputation")), Aggregates.sort(Sorts.descending("reputation")));
    event.getMongo().aggregateUsers(pipeline).whenComplete((documents, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        List<Map.Entry<User, Integer>> users = new ArrayList<>();
        AtomicInteger userIndex = new AtomicInteger(-1);
        int i = 0;
        for (Document data : documents) {
            User user = event.getShardManager().getUserById(data.getLong("_id"));
            if (user == null) {
                continue;
            }
            if (!event.getGuild().isMember(user) && guild) {
                continue;
            }
            i++;
            users.add(Map.entry(user, data.getInteger("reputation")));
            if (user.getIdLong() == event.getAuthor().getIdLong()) {
                userIndex.set(i);
            }
        }
        if (users.isEmpty()) {
            event.replyFailure("There are no users which fit into this leaderboard").queue();
            return;
        }
        PagedResult<Map.Entry<User, Integer>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
            int rank = userIndex.get();
            EmbedBuilder embed = new EmbedBuilder().setTitle("Reputation Leaderboard").setFooter(event.getAuthor().getName() + "'s Rank: " + (rank == -1 ? "N/A" : NumberUtility.getSuffixed(rank)) + " | Page " + page.getPage() + "/" + page.getMaxPage(), event.getAuthor().getEffectiveAvatarUrl());
            page.forEach((entry, index) -> embed.appendDescription(String.format("%d. `%s` - %,d reputation\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue())));
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PagedResult(com.sx4.bot.paged.PagedResult) Redirects(com.sx4.bot.annotations.command.Redirects) 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 12 with Redirects

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

the class GameCommand method list.

@Command(value = "list", aliases = { "game list", "game list @Shea#6653", "game list Shea" }, description = "Lists basic info on all games a user has played on Sx4")
@CommandId(297)
@Redirects({ "games" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    User user = member == null ? event.getAuthor() : member.getUser();
    List<Document> games = event.getMongo().getGames(Filters.eq("userId", user.getIdLong()), Projections.include("type", "state")).into(new ArrayList<>());
    if (games.isEmpty()) {
        event.replyFailure("That user has not played any games yet").queue();
        return;
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), games).setAuthor("Game List", null, user.getEffectiveAvatarUrl()).setIndexed(false).setPerPage(15).setSelect().setDisplayFunction(game -> "`" + GameType.fromId(game.getInteger("type")).getName() + "` - " + StringUtility.title(GameState.fromId(game.getInteger("state")).name()));
    paged.execute(event);
}
Also used : User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) Redirects(com.sx4.bot.annotations.command.Redirects) 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)

Example 13 with Redirects

use of com.sx4.bot.annotations.command.Redirects 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();
        });
    });
}
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) Suggestion(com.sx4.bot.entities.management.Suggestion) TextChannel(net.dv8tion.jda.api.entities.TextChannel) Message(net.dv8tion.jda.api.entities.Message) SuggestionState(com.sx4.bot.entities.management.SuggestionState) Document(org.bson.Document) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 14 with Redirects

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

the class RoleCommand method remove.

@Command(value = "remove", description = "Remove a role from a member")
@CommandId(251)
@Redirects({ "removerole", "remove role", "rr" })
@Examples({ "role remove @Shea#6653 Role", "role remove Shea 345718366373150720", "role remove @Role" })
@AuthorPermissions(permissions = { Permission.MANAGE_ROLES })
@BotPermissions(permissions = { Permission.MANAGE_ROLES })
public void remove(Sx4CommandEvent event, @Argument(value = "user", nullDefault = true) Member member, @Argument(value = "role", endless = true) Role role) {
    if (role.isManaged()) {
        event.replyFailure("I cannot remove managed roles").queue();
        return;
    }
    if (role.isPublicRole()) {
        event.replyFailure("I cannot remove the @everyone role").queue();
        return;
    }
    if (!event.getMember().canInteract(role)) {
        event.replyFailure("You cannot remove a role higher or equal than your top role").queue();
        return;
    }
    if (!event.getSelfMember().canInteract(role)) {
        event.replyFailure("I cannot remove a role higher or equal than my top role").queue();
        return;
    }
    Member effectiveMember = member == null ? event.getMember() : member;
    event.getGuild().removeRoleFromMember(effectiveMember, role).flatMap($ -> event.replySuccess(role.getAsMention() + " has been removed from **" + 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) Member(net.dv8tion.jda.api.entities.Member) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 15 with Redirects

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

the class HelpUtility method getHelpMessage.

public static Message getHelpMessage(ICommand initialCommand, boolean embed) {
    MessageBuilder builder = new MessageBuilder();
    Sx4Command command = initialCommand instanceof DummyCommand ? (Sx4Command) ((DummyCommand) initialCommand).getActualCommand() : (Sx4Command) initialCommand;
    String usage = command.getSubCommands().isEmpty() ? command.getUsage() : command.getUsage().trim().equals(command.getCommandTrigger()) ? command.getUsage() + " <sub command>" : command.getUsage() + " | <sub command>";
    StringBuilder options = new StringBuilder();
    for (int i = 0; i < command.getOptions().size(); i++) {
        IOption<?> option = command.getOptions().get(i);
        options.append("`").append(option.getName()).append(option.getType() != boolean.class ? "=<value>" : "").append("` - ").append(option.getDescription()).append(i == command.getOptions().size() - 1 ? "" : "\n");
    }
    if (embed) {
        EmbedBuilder embedBuilder = new EmbedBuilder();
        embedBuilder.setTitle(command.getCommandTrigger());
        embedBuilder.addField("Description", command.getDescription(), false);
        embedBuilder.addField("Usage", usage, false);
        if (!command.getOptions().isEmpty()) {
            embedBuilder.addField("Options", options.toString(), false);
        }
        if (command.getExamples().length != 0) {
            embedBuilder.addField("Examples", "`" + String.join("`\n`", command.getExamples()) + "`", false);
        }
        if (!command.getAuthorDiscordPermissions().isEmpty()) {
            embedBuilder.addField("Required Permissions", command.getAuthorDiscordPermissions().stream().map(Permission::getName).collect(Collectors.joining(", ")), false);
        }
        if (!command.getAliases().isEmpty()) {
            embedBuilder.addField("Aliases", String.join(", ", command.getAliases()), false);
        }
        if (command.getRedirects().length != 0) {
            embedBuilder.addField("Redirects", String.join(", ", command.getRedirects()), false);
        }
        if (!command.getSubCommands().isEmpty()) {
            embedBuilder.addField("Sub Commands", command.getSubCommands().stream().map(ICommand::getCommand).collect(Collectors.joining(", ")), false);
        }
        if (command.isPremiumCommand()) {
            embedBuilder.setFooter("Premium Command ⭐");
        }
        return builder.setEmbeds(embedBuilder.build()).build();
    } else {
        String placeHolder = "%s:\n%s\n\n";
        Formatter formatter = new Formatter();
        formatter.format(">>> **" + command.getCommandTrigger() + "**\n\n");
        formatter.format(placeHolder, "Description", command.getDescription());
        formatter.format(placeHolder, "Usage", usage);
        if (!command.getOptions().isEmpty()) {
            formatter.format(placeHolder, "Options", options);
        }
        if (command.getExamples().length != 0) {
            formatter.format(placeHolder, "Examples", "`" + String.join("`\n`", command.getExamples()) + "`");
        }
        if (!command.getAuthorDiscordPermissions().isEmpty()) {
            formatter.format(placeHolder, "Required Permissions", command.getAuthorDiscordPermissions().stream().map(Permission::getName).collect(Collectors.joining(", ")));
        }
        if (!command.getAliases().isEmpty()) {
            formatter.format(placeHolder, "Aliases", String.join(", ", command.getAliases()));
        }
        if (command.getRedirects().length != 0) {
            formatter.format(placeHolder, "Redirects", String.join(", ", command.getRedirects()));
        }
        if (!command.getSubCommands().isEmpty()) {
            formatter.format(placeHolder, "Required Permissions", command.getSubCommands().stream().map(ICommand::getCommand).collect(Collectors.joining(", ")));
        }
        Message message = builder.setContent(formatter.toString()).build();
        formatter.close();
        return message;
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Sx4Command(com.sx4.bot.core.Sx4Command) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Message(net.dv8tion.jda.api.entities.Message) ICommand(com.jockie.bot.core.command.ICommand) Formatter(java.util.Formatter) Permission(net.dv8tion.jda.api.Permission) DummyCommand(com.jockie.bot.core.command.impl.DummyCommand)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)15 Command (com.jockie.bot.core.command.Command)14 User (net.dv8tion.jda.api.entities.User)11 Document (org.bson.Document)11 Bson (org.bson.conversions.Bson)10 CommandId (com.sx4.bot.annotations.command.CommandId)9 Redirects (com.sx4.bot.annotations.command.Redirects)9 ArrayList (java.util.ArrayList)9 PagedResult (com.sx4.bot.paged.PagedResult)8 Argument (com.jockie.bot.core.argument.Argument)7 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)7 Examples (com.sx4.bot.annotations.command.Examples)7 ModuleCategory (com.sx4.bot.category.ModuleCategory)7 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)7 Alternative (com.sx4.bot.entities.argument.Alternative)7 List (java.util.List)7 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)7 Permission (net.dv8tion.jda.api.Permission)6 Member (net.dv8tion.jda.api.entities.Member)6 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)5