Search in sources :

Example 66 with Command

use of com.jockie.bot.core.command.Command in project Sx4 by sx4-discord-bot.

the class AntiRegexCommand method add.

@Command(value = "add", description = "Add a regex from `anti regex template list` to be checked on every message")
@CommandId(106)
@Examples({ "anti regex add 5f023782ef9eba03390a740c" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void add(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
    Document regex = event.getMongo().getRegexTemplateById(id, Projections.include("pattern", "title", "type"));
    if (regex == null) {
        event.replyFailure("I could not find that regex template").queue();
        return;
    }
    List<Bson> guildPipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))), Projections.computed("guildId", "$_id"))), Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())));
    List<Bson> pipeline = List.of(Aggregates.match(Filters.and(Filters.eq("guildId", event.getGuild().getIdLong()), Filters.exists("enabled", false), Filters.eq("type", RegexType.REGEX.getId()))), Aggregates.group(null, Accumulators.sum("count", 1)), Aggregates.limit(10), Aggregates.unionWith("guilds", guildPipeline), Aggregates.group(null, Accumulators.max("count", "$count"), Accumulators.max("premium", "$premium")), Aggregates.project(Projections.fields(Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.ifNull("$count", 0)))));
    event.getMongo().aggregateRegexes(pipeline).thenCompose(documents -> {
        Document counter = documents.isEmpty() ? null : documents.get(0);
        int count = counter == null ? 0 : counter.getInteger("count");
        if (count >= 3 && !counter.getBoolean("premium")) {
            throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled anti regexes, you can get premium at <https://www.patreon.com/Sx4>");
        }
        if (count == 10) {
            throw new IllegalArgumentException("You cannot have any more than 10 anti regexes");
        }
        Document pattern = new Document("regexId", id).append("guildId", event.getGuild().getIdLong()).append("type", regex.getInteger("type", RegexType.REGEX.getId())).append("pattern", regex.getString("pattern"));
        return event.getMongo().insertRegex(pattern);
    }).thenCompose(result -> {
        event.replySuccess("The regex `" + result.getInsertedId().asObjectId().getValue().toHexString() + "` is now active").queue();
        return event.getMongo().updateRegexTemplateById(id, Updates.inc("uses", 1L));
    }).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 that anti regex setup in this server").queue();
            return;
        } else if (cause instanceof IllegalArgumentException) {
            event.replyFailure(cause.getMessage()).queue();
            return;
        }
        ExceptionUtility.sendExceptionally(event, exception);
    });
}
Also used : HolderType(com.sx4.bot.entities.settings.HolderType) Document(org.bson.Document) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) FormatterVariable(com.sx4.bot.formatter.function.FormatterVariable) MarkdownSanitizer(net.dv8tion.jda.api.utils.MarkdownSanitizer) Command(com.jockie.bot.core.command.Command) MongoWriteException(com.mongodb.MongoWriteException) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) ModAction(com.sx4.bot.entities.mod.action.ModAction) CompletableFuture(java.util.concurrent.CompletableFuture) TimedArgument(com.sx4.bot.entities.argument.TimedArgument) PagedResult(com.sx4.bot.paged.PagedResult) ArrayList(java.util.ArrayList) MatchAction(com.sx4.bot.entities.mod.auto.MatchAction) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Duration(java.time.Duration) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) com.mongodb.client.model(com.mongodb.client.model) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) 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) Sx4Command(com.sx4.bot.core.Sx4Command) WhitelistType(com.sx4.bot.entities.management.WhitelistType) CompletionException(java.util.concurrent.CompletionException) FormatterManager(com.sx4.bot.formatter.FormatterManager) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) StringJoiner(java.util.StringJoiner) ObjectId(org.bson.types.ObjectId) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) RegexType(com.sx4.bot.entities.mod.auto.RegexType) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) ErrorCategory(com.mongodb.ErrorCategory) MongoWriteException(com.mongodb.MongoWriteException) CompletionException(java.util.concurrent.CompletionException) Document(org.bson.Document) Bson(org.bson.conversions.Bson) 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 67 with Command

use of com.jockie.bot.core.command.Command in project Sx4 by sx4-discord-bot.

the class TwitchNotificationCommand method preview.

@Command(value = "preview", description = "Preview a twitch notification")
@CommandId(503)
@Examples({ "twitch notification preview 5e45ce6d3688b30ee75201ae" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void preview(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
    Document data = event.getMongo().getTwitchNotification(Filters.and(Filters.eq("_id", id), Filters.eq("guildId", event.getGuild().getIdLong())), Projections.include("streamerId", "message"));
    if (data == null) {
        event.replyFailure("I could not find that notification").queue();
        return;
    }
    String streamerId = data.getString("streamerId");
    Request request = new Request.Builder().url("https://api.twitch.tv/helix/users?id=" + streamerId).addHeader("Authorization", "Bearer " + event.getBot().getTwitchConfig().getToken()).addHeader("Client-Id", event.getBot().getConfig().getTwitchClientId()).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document json = Document.parse(response.body().string());
        List<Document> entries = json.getList("data", Document.class);
        if (entries.isEmpty()) {
            event.replyFailure("The twitch streamer for that notification no longer exists").queue();
            return;
        }
        Document entry = entries.get(0);
        Document message = new JsonFormatter(data.get("message", TwitchManager.DEFAULT_MESSAGE)).addVariable("stream", new TwitchStream("0", TwitchStreamType.LIVE, "https://cdn.discordapp.com/attachments/344091594972069888/969319515714371604/twitch-test-preview.png", "Preview Title", "Preview Game", OffsetDateTime.now())).addVariable("streamer", new TwitchStreamer(entry.getString("id"), entry.getString("display_name"), entry.getString("login"))).parse();
        try {
            MessageUtility.fromWebhookMessage(event.getChannel(), MessageUtility.fromJson(message).build()).queue();
        } catch (IllegalArgumentException e) {
            event.replyFailure(e.getMessage()).queue();
        }
    });
}
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) JsonFormatter(com.sx4.bot.formatter.JsonFormatter) TwitchStream(com.sx4.bot.entities.twitch.TwitchStream) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) TwitchStreamer(com.sx4.bot.entities.twitch.TwitchStreamer) Document(org.bson.Document) 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)

Example 68 with Command

use of com.jockie.bot.core.command.Command in project Sx4 by sx4-discord-bot.

the class BlacklistCommand method reset.

@Command(value = "reset", description = "Reset the blacklist for a specific role/user in a channel")
@CommandId(181)
@Examples({ "blacklist reset #channel", "blacklist reset all" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void reset(Sx4CommandEvent event, @Argument(value = "channel", endless = true) @AlternativeOptions("all") Alternative<TextChannel> option) {
    List<Bson> update = List.of(Operators.set("holders", Operators.reduce(Operators.ifNull("$holders", Collections.EMPTY_LIST), Collections.EMPTY_LIST, Operators.concatArrays("$$value", Operators.cond(Operators.isEmpty(Operators.ifNull(Operators.first(Operators.map(List.of("$$this"), "$$holder.whitelisted", "holder")), Collections.EMPTY_LIST)), Collections.EMPTY_LIST, List.of(Operators.removeObject("$$this", "blacklisted")))))));
    if (option.isAlternative()) {
        event.getMongo().updateManyBlacklists(Filters.eq("guildId", event.getGuild().getIdLong()), update, new UpdateOptions()).whenComplete((result, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (result.getModifiedCount() == 0) {
                event.replyFailure("Nothing was blacklisted in this server").queue();
                return;
            }
            event.replySuccess("Reset **" + result.getModifiedCount() + "** channels of their blacklist configurations").queue();
        });
    } else {
        TextChannel channel = option.getValue();
        event.getMongo().updateBlacklist(Filters.eq("channelId", channel.getIdLong()), update, new UpdateOptions()).whenComplete((result, exception) -> {
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (result.getModifiedCount() == 0) {
                event.replyFailure("Nothing was blacklisted in that channel").queue();
                return;
            }
            event.replySuccess("That channel no longer has any blacklists").queue();
        });
    }
}
Also used : TextChannel(net.dv8tion.jda.api.entities.TextChannel) Bson(org.bson.conversions.Bson) 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 69 with Command

use of com.jockie.bot.core.command.Command in project Sx4 by sx4-discord-bot.

the class BlacklistCommand method list.

@Command(value = "list", description = "Lists the commands roles/users blacklisted from using in a specific channel")
@CommandId(182)
@Examples({ "blacklist list", "blacklist list #channel" })
public void list(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true, endless = true) TextChannel channel) {
    List<TextChannel> channels = channel == null ? event.getGuild().getTextChannels() : List.of(channel);
    PagedResult<TextChannel> channelPaged = new PagedResult<>(event.getBot(), channels).setAutoSelect(true).setAuthor("Channels", null, event.getGuild().getIconUrl()).setDisplayFunction(TextChannel::getAsMention);
    channelPaged.onSelect(channelSelect -> {
        TextChannel selectedChannel = channelSelect.getSelected();
        Document blacklist = event.getMongo().getBlacklist(Filters.eq("channelId", selectedChannel.getIdLong()), Projections.include("holders"));
        if (blacklist == null) {
            event.replyFailure("Nothing is blacklisted in " + selectedChannel.getAsMention()).queue();
            return;
        }
        List<Document> holders = blacklist.getList("holders", Document.class).stream().filter(holder -> !holder.getList("blacklisted", Long.class, Collections.emptyList()).isEmpty()).sorted(Comparator.comparingInt(a -> a.getInteger("type"))).collect(Collectors.toList());
        if (holders.isEmpty()) {
            event.replyFailure("Nothing is blacklisted in " + selectedChannel.getAsMention()).queue();
            return;
        }
        PagedResult<Document> holderPaged = new PagedResult<>(event.getBot(), holders).setAuthor("Users/Roles", null, event.getGuild().getIconUrl()).setDisplayFunction(holder -> {
            long id = holder.getLong("id");
            int type = holder.getInteger("type");
            if (type == HolderType.ROLE.getType()) {
                Role role = event.getGuild().getRoleById(id);
                return role == null ? "Deleted Role (" + id + ")" : role.getAsMention();
            } else {
                User user = event.getShardManager().getUserById(id);
                return user == null ? "Unknown User (" + id + ")" : user.getAsTag();
            }
        });
        holderPaged.onSelect(holderSelect -> {
            Document holder = holderSelect.getSelected();
            List<Long> blacklisted = holder.getList("blacklisted", Long.class, Collections.emptyList());
            BitSet bitSet = BitSet.valueOf(blacklisted.stream().mapToLong(l -> l).toArray());
            List<Sx4Command> commands = event.getCommandListener().getAllCommands().stream().map(Sx4Command.class::cast).filter(command -> bitSet.get(command.getId())).collect(Collectors.toList());
            PagedResult<Sx4Command> commandPaged = new PagedResult<>(event.getBot(), commands).setAuthor("Blacklisted Commands", null, event.getGuild().getIconUrl()).setDisplayFunction(Sx4Command::getCommandTrigger).setSelect().setIndexed(false);
            commandPaged.execute(event);
        });
        holderPaged.execute(event);
    });
    channelPaged.execute(event);
}
Also used : HolderType(com.sx4.bot.entities.settings.HolderType) Document(org.bson.Document) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) Operators(com.sx4.bot.database.mongo.model.Operators) java.util(java.util) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult) Collectors(java.util.stream.Collectors) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) Alternative(com.sx4.bot.entities.argument.Alternative) Examples(com.sx4.bot.annotations.command.Examples) IPermissionHolder(net.dv8tion.jda.api.entities.IPermissionHolder) Role(net.dv8tion.jda.api.entities.Role) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) com.mongodb.client.model(com.mongodb.client.model) Argument(com.jockie.bot.core.argument.Argument) User(net.dv8tion.jda.api.entities.User) Sx4Command(com.sx4.bot.core.Sx4Command) Document(org.bson.Document) Role(net.dv8tion.jda.api.entities.Role) TextChannel(net.dv8tion.jda.api.entities.TextChannel) PagedResult(com.sx4.bot.paged.PagedResult) 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 70 with Command

use of com.jockie.bot.core.command.Command in project Sx4 by sx4-discord-bot.

the class FakePermissionsCommand method list.

@Command(value = "list", description = "Lists all permissions you can use as arguments")
@CommandId(175)
@Examples({ "fake permissions list" })
public void list(Sx4CommandEvent event) {
    EmbedBuilder embed = new EmbedBuilder().setDescription(Arrays.stream(Permission.values()).filter(Predicate.not(Permission.UNKNOWN::equals)).map(Permission::name).collect(Collectors.joining("\n"))).setAuthor("Fake Permissions", null, event.getGuild().getIconUrl());
    event.reply(embed.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Permission(net.dv8tion.jda.api.Permission) 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)178 Sx4Command (com.sx4.bot.core.Sx4Command)178 CommandId (com.sx4.bot.annotations.command.CommandId)118 Examples (com.sx4.bot.annotations.command.Examples)116 Document (org.bson.Document)113 Bson (org.bson.conversions.Bson)97 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)82 PagedResult (com.sx4.bot.paged.PagedResult)71 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)59 Argument (com.jockie.bot.core.argument.Argument)53 ModuleCategory (com.sx4.bot.category.ModuleCategory)53 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)53 Permission (net.dv8tion.jda.api.Permission)52 BotPermissions (com.sx4.bot.annotations.command.BotPermissions)46 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)43 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)43 User (net.dv8tion.jda.api.entities.User)43 Operators (com.sx4.bot.database.mongo.model.Operators)41 Collectors (java.util.stream.Collectors)36 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)31