Search in sources :

Example 26 with BotPermissions

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

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

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

the class WarnCommand method list.

@Command(value = "list", description = "Lists all the warned users in the server and how many warnings they have")
@CommandId(258)
@Examples({ "warn list" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event) {
    List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())), Aggregates.project(Projections.fields(Projections.include("userId"), Projections.computed("warnings", Operators.cond(Operators.or(Operators.isNull("$reset"), Operators.isNull("$warnings")), Operators.ifNull("$warnings", 0), Operators.max(0, Operators.subtract("$warnings", Operators.multiply(Operators.toInt(Operators.floor(Operators.divide(Operators.subtract(Operators.nowEpochSecond(), "$lastWarning"), "$reset.after"))), "$reset.amount"))))))), Aggregates.match(Filters.ne("warnings", 0)), Aggregates.sort(Sorts.descending("warnings")));
    event.getMongo().aggregateWarnings(pipeline).whenComplete((users, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (users.isEmpty()) {
            event.replyFailure("There are no users with warnings in this server").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), users).setAuthor("Warned Users", null, event.getGuild().getIconUrl()).setIndexed(false).setDisplayFunction(data -> {
            long userId = data.getLong("userId");
            User user = event.getShardManager().getUserById(userId);
            return "`" + (user == null ? "Anonymous#0000 (" + userId + ")" : MarkdownSanitizer.escape(user.getAsTag())) + "` - Warning **#" + data.getInteger("warnings") + "**";
        });
        paged.execute(event);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document) Bson(org.bson.conversions.Bson) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 29 with BotPermissions

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

the class AntiRegexCommand method formatters.

@Command(value = "formatters", aliases = { "format", "formatting" }, description = "Get all the formatters for anti regex you can use")
@CommandId(468)
@Examples({ "anti regex formatters" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void formatters(Sx4CommandEvent event) {
    EmbedBuilder embed = new EmbedBuilder().setAuthor("Anti-Regex Formatters", null, event.getSelfUser().getEffectiveAvatarUrl());
    FormatterManager manager = FormatterManager.getDefaultManager();
    StringJoiner content = new StringJoiner("\n");
    for (FormatterVariable<?> variable : manager.getVariables(User.class)) {
        content.add("`{user." + variable.getName() + "}` - " + variable.getDescription());
    }
    for (FormatterVariable<?> variable : manager.getVariables(TextChannel.class)) {
        content.add("`{channel." + variable.getName() + "}` - " + variable.getDescription());
    }
    content.add("`{regex.id}` - Gets the id of the regex");
    content.add("`{regex.action.name}` - Gets the mod action name if one is set");
    content.add("`{regex.action.exists}` - Returns true or false if an action exists");
    content.add("`{regex.attempts.current}` - Gets the current attempts for the user");
    content.add("`{regex.attempts.max}` - Gets the max attempts set for the anti regex");
    embed.setDescription(content.toString());
    event.reply(embed.build()).queue();
}
Also used : FormatterManager(com.sx4.bot.formatter.FormatterManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) StringJoiner(java.util.StringJoiner) 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 30 with BotPermissions

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

the class TwitchNotificationCommand method list.

@Command(value = "list", description = "View all the twitch notifications you have setup throughout your server")
@CommandId(502)
@Examples({ "twitch notification list" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void list(Sx4CommandEvent event) {
    List<Document> notifications = event.getMongo().getTwitchNotifications(Filters.eq("guildId", event.getGuild().getIdLong()), Projections.include("streamerId", "channelId", "message")).into(new ArrayList<>());
    if (notifications.isEmpty()) {
        event.replyFailure("You have no notifications setup in this server").queue();
        return;
    }
    List<String> streamers = notifications.stream().map(d -> d.getString("streamerId")).distinct().collect(Collectors.toList());
    int size = streamers.size();
    List<CompletableFuture<Map<String, TwitchStreamer>>> futures = new ArrayList<>();
    for (int i = 0; i < Math.ceil(size / 100D); i++) {
        List<String> splitStreamers = streamers.subList(i * 100, Math.min((i + 1) * 100, size));
        String ids = String.join("&id=", splitStreamers);
        Request request = new Request.Builder().url("https://api.twitch.tv/helix/users?id=" + ids).addHeader("Authorization", "Bearer " + event.getBot().getTwitchConfig().getToken()).addHeader("Client-Id", event.getBot().getConfig().getTwitchClientId()).build();
        CompletableFuture<Map<String, TwitchStreamer>> future = new CompletableFuture<>();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            Document json = Document.parse(response.body().string());
            List<Document> entries = json.getList("data", Document.class);
            Map<String, TwitchStreamer> names = new HashMap<>();
            for (Document entry : entries) {
                String id = entry.getString("id");
                names.put(id, new TwitchStreamer(id, entry.getString("display_name"), entry.getString("login")));
            }
            future.complete(names);
        });
        futures.add(future);
    }
    FutureUtility.allOf(futures).whenComplete((maps, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        Map<String, TwitchStreamer> names = new HashMap<>();
        for (Map<String, TwitchStreamer> map : maps) {
            names.putAll(map);
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), notifications).setSelect().setAuthor("Twitch Notifications", null, event.getGuild().getIconUrl()).setDisplayFunction(data -> {
            TwitchStreamer streamer = names.get(data.getString("streamerId"));
            return String.format("%s - [%s](%s)", data.getObjectId("_id").toHexString(), streamer == null ? "Unknown" : streamer.getName(), streamer == null ? "https://twitch.tv" : streamer.getUrl());
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) TwitchStream(com.sx4.bot.entities.twitch.TwitchStream) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) TwitchManager(com.sx4.bot.managers.TwitchManager) TwitchStreamType(com.sx4.bot.entities.twitch.TwitchStreamType) PagedResult(com.sx4.bot.paged.PagedResult) AggregateOperators(com.sx4.bot.database.mongo.model.AggregateOperators) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) CompletionException(java.util.concurrent.CompletionException) FormatterManager(com.sx4.bot.formatter.FormatterManager) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) java.util(java.util) Command(com.jockie.bot.core.command.Command) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) CommandId(com.sx4.bot.annotations.command.CommandId) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) CompletableFuture(java.util.concurrent.CompletableFuture) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) AtomicReference(java.util.concurrent.atomic.AtomicReference) Bson(org.bson.conversions.Bson) AdvancedMessage(com.sx4.bot.annotations.argument.AdvancedMessage) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.mongodb.client.model(com.mongodb.client.model) FutureUtility(com.sx4.bot.utility.FutureUtility) Argument(com.jockie.bot.core.argument.Argument) Lowercase(com.sx4.bot.annotations.argument.Lowercase) Operators(com.sx4.bot.database.mongo.model.Operators) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) MessageUtility(com.sx4.bot.utility.MessageUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) ErrorCategory(com.mongodb.ErrorCategory) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document) CompletableFuture(java.util.concurrent.CompletableFuture) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Sx4Command(com.sx4.bot.core.Sx4Command) Command(com.jockie.bot.core.command.Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Aggregations

Command (com.jockie.bot.core.command.Command)44 Sx4Command (com.sx4.bot.core.Sx4Command)44 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)37 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)33 CommandId (com.sx4.bot.annotations.command.CommandId)33 Examples (com.sx4.bot.annotations.command.Examples)31 Document (org.bson.Document)29 PagedResult (com.sx4.bot.paged.PagedResult)25 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)21 Bson (org.bson.conversions.Bson)20 Argument (com.jockie.bot.core.argument.Argument)14 ModuleCategory (com.sx4.bot.category.ModuleCategory)14 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)14 Permission (net.dv8tion.jda.api.Permission)14 User (net.dv8tion.jda.api.entities.User)14 Collectors (java.util.stream.Collectors)12 AtomicInteger (java.util.concurrent.atomic.AtomicInteger)11 java.util (java.util)10 ArrayList (java.util.ArrayList)10 FormatterManager (com.sx4.bot.formatter.FormatterManager)9