Search in sources :

Example 6 with Sx4

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

the class SteamCommand method connect.

@Command(value = "connect", description = "Connect your steam account with Sx4")
@CommandId(488)
@Examples({ "steam connect" })
public void connect(Sx4CommandEvent event) {
    String id = event.getAuthor().getId();
    long timestamp = Instant.now().getEpochSecond();
    String signature;
    try {
        signature = HmacUtility.getSignatureHex(event.getConfig().getSteam(), id + timestamp, HmacUtility.HMAC_MD5);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        event.replyFailure("Something went wrong there, try again").queue();
        return;
    }
    String redirectUrl = URLEncoder.encode(event.getConfig().getBaseUrl() + "/redirect/steam?user_id=" + id + "&timestamp=" + timestamp + "&signature=" + signature, StandardCharsets.UTF_8);
    MessageEmbed embed = new EmbedBuilder().setAuthor("Steam Authorization").setDescription("The link below will allow you to link your steam account on Sx4\n**:warning: Do not give this link to anyone :warning:**\n\n[Authorize](https://sx4.dev/connect/steam?redirect_url=" + redirectUrl + ")").setColor(event.getConfig().getOrange()).setFooter("The authorization link will expire in 5 minutes").build();
    event.getAuthor().openPrivateChannel().flatMap(channel -> channel.sendMessageEmbeds(embed)).flatMap($ -> event.replySuccess("I sent you a message containing your authorization link")).onErrorFlatMap($ -> event.replyFailure("I failed to send you your authorization link, make sure to have your dms open")).queue();
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) TextNode(org.jsoup.nodes.TextNode) Permission(net.dv8tion.jda.api.Permission) Projections(com.mongodb.client.model.Projections) CommandId(com.sx4.bot.annotations.command.CommandId) Cooldown(com.jockie.bot.core.command.Command.Cooldown) PagedResult(com.sx4.bot.paged.PagedResult) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Element(org.jsoup.nodes.Element) Option(com.jockie.bot.core.option.Option) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Request(okhttp3.Request) HmacUtility(com.sx4.bot.utility.HmacUtility) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) Examples(com.sx4.bot.annotations.command.Examples) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) InvalidKeyException(java.security.InvalidKeyException) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Jsoup(org.jsoup.Jsoup) Pattern(java.util.regex.Pattern) StringUtility(com.sx4.bot.utility.StringUtility) JSONArray(org.json.JSONArray) SteamGameCache(com.sx4.bot.cache.SteamGameCache) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) InvalidKeyException(java.security.InvalidKeyException) 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 7 with Sx4

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

the class FreeGamesCommand method avatar.

@Command(value = "avatar", description = "Set the avatar of the webhook that sends free game notifications")
@CommandId(480)
@Examples({ "free games avatar Shea#6653", "free games avatar https://i.imgur.com/i87lyNO.png" })
@Premium
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void avatar(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "avatar", endless = true, acceptEmpty = true) @ImageUrl String url) {
    MessageChannel messageChannel = event.getChannel();
    if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
        event.replyFailure("You cannot use this channel type").queue();
        return;
    }
    BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
    event.getMongo().updateFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), Updates.set("webhook.avatar", url), new UpdateOptions()).whenComplete((result, exception) -> {
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (result.getMatchedCount() == 0) {
            event.replyFailure("You don't have a free game channel setup").queue();
            return;
        }
        if (result.getModifiedCount() == 0) {
            event.replyFailure("Your webhook avatar for free game notifications was already set to that").queue();
            return;
        }
        event.replySuccess("Your webhook avatar has been updated for that free game notifications, this only works with premium <https://patreon.com/Sx4>").queue();
    });
}
Also used : MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 8 with Sx4

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

the class AntiRegexCommand method add.

@Command(value = "add", description = "Add a custom regex to be checked on every message")
@CommandId(125)
@Examples({ "anti regex add [0-9]+", "anti regex add https://discord\\.com/channels/([0-9]+)/([0-9]+)/?" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void add(Sx4CommandEvent event, @Argument(value = "regex", endless = true) Pattern pattern) {
    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 patternData = new Document("guildId", event.getGuild().getIdLong()).append("type", RegexType.REGEX.getId()).append("pattern", pattern.pattern());
        return event.getMongo().insertRegex(patternData);
    }).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;
        }
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        event.replySuccess("The regex `" + result.getInsertedId().asObjectId().getValue().toHexString() + "` is now active").queue();
    });
}
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 9 with Sx4

use of com.sx4.bot.core.Sx4 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 10 with Sx4

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

the class PremiumCommand method check.

@Command(value = "check", description = "Checks when the current premium in the server expires")
@CommandId(178)
@Examples({ "premium check" })
public void check(Sx4CommandEvent event) {
    long endAt = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("premium.endAt")).getEmbedded(List.of("premium", "endAt"), 0L);
    if (endAt == 0) {
        event.replyFailure("This server currently doesn't have premium, you can give it premium with credit <https://patreon.com/Sx4>").queue();
        return;
    }
    OffsetDateTime expire = OffsetDateTime.ofInstant(Instant.ofEpochSecond(endAt), ZoneOffset.UTC);
    if (expire.isBefore(OffsetDateTime.now(ZoneOffset.UTC))) {
        event.replyFailure("Premium for this server expired on the **" + String.format(expire.format(this.formatter), NumberUtility.getSuffix(expire.getDayOfMonth())) + "**, you can renew it with more credit <https://patreon.com/Sx4>").queue();
        return;
    }
    event.replyFormat("Premium for this server will expire on the **" + String.format(expire.format(this.formatter), NumberUtility.getSuffix(expire.getDayOfMonth())) + "**").queue();
}
Also used : OffsetDateTime(java.time.OffsetDateTime) 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

Document (org.bson.Document)28 Sx4Command (com.sx4.bot.core.Sx4Command)24 Command (com.jockie.bot.core.command.Command)23 Bson (org.bson.conversions.Bson)21 Permission (net.dv8tion.jda.api.Permission)19 CompletableFuture (java.util.concurrent.CompletableFuture)16 com.mongodb.client.model (com.mongodb.client.model)14 MongoDatabase (com.sx4.bot.database.mongo.MongoDatabase)14 Operators (com.sx4.bot.database.mongo.model.Operators)14 CompletionException (java.util.concurrent.CompletionException)13 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)13 Argument (com.jockie.bot.core.argument.Argument)12 ModuleCategory (com.sx4.bot.category.ModuleCategory)12 Sx4 (com.sx4.bot.core.Sx4)12 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)12 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)12 BaseGuildMessageChannel (net.dv8tion.jda.api.entities.BaseGuildMessageChannel)12 CommandId (com.sx4.bot.annotations.command.CommandId)11 Examples (com.sx4.bot.annotations.command.Examples)10 User (net.dv8tion.jda.api.entities.User)10