Search in sources :

Example 21 with Sx4

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

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

the class TwitchNotificationCommand method add.

@Command(value = "add", description = "Adds a twitch notification to a specific channel")
@CommandId(494)
@Command.Cooldown(5)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "twitch notification add #channel esl_csgo", "twitch notification add pgl" })
public void add(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel, @Argument(value = "streamer name", endless = true) @Lowercase String streamer) {
    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;
    Request request = new Request.Builder().url("https://api.twitch.tv/helix/users?login=" + URLEncoder.encode(streamer, StandardCharsets.UTF_8)).addHeader("Authorization", "Bearer " + event.getBot().getTwitchConfig().getToken()).addHeader("Client-Id", event.getConfig().getTwitchClientId()).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        if (response.code() == 400) {
            event.replyFailure("I could not find that twitch streamer").queue();
            response.close();
            return;
        }
        Document json = Document.parse(response.body().string());
        List<Document> entries = json.getList("data", Document.class);
        if (entries.isEmpty()) {
            event.replyFailure("I could not find that twitch streamer").queue();
            return;
        }
        Document data = entries.get(0);
        String id = data.getString("id"), name = data.getString("display_name");
        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> countPipeline = List.of(Aggregates.match(Filters.and(Filters.eq("streamerId", id), Filters.exists("enabled", false))), Aggregates.limit(1), Aggregates.group(null, Accumulators.sum("streamerCount", 1)));
        List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())), Aggregates.group(null, Accumulators.push("notifications", Operators.ROOT)), Aggregates.unionWith("twitchNotifications", countPipeline), Aggregates.unionWith("guilds", guildPipeline), AggregateOperators.mergeFields("premium", "notifications", "streamerCount"), Aggregates.project(Projections.fields(Projections.computed("webhook", Operators.first(Operators.map(Operators.filter(Operators.ifNull("$notifications", Collections.EMPTY_LIST), Operators.and(Operators.exists("$$this.webhook"), Operators.eq("$$this.channelId", effectiveChannel.getIdLong()))), "$$this.webhook"))), Projections.computed("subscribe", Operators.eq(Operators.ifNull("$streamerCount", 0), 0)), Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.size(Operators.filter(Operators.ifNull("$notifications", Collections.EMPTY_LIST), Operators.extinct("$$this.enabled")))))));
        AtomicBoolean subscribe = new AtomicBoolean();
        event.getMongo().aggregateTwitchNotifications(pipeline).thenCompose(documents -> {
            Document counter = documents.isEmpty() ? null : documents.get(0);
            int count = counter == null ? 0 : counter.getInteger("count");
            if (counter != null && count >= 3 && !counter.getBoolean("premium")) {
                throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled twitch notifications, you can get premium at <https://www.patreon.com/Sx4>");
            }
            if (count >= 10) {
                throw new IllegalArgumentException("You can not have any more than 10 enabled twitch notifications");
            }
            subscribe.set(counter == null || counter.getBoolean("subscribe"));
            Document notification = new Document("streamerId", id).append("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
            Document webhook = counter == null ? null : counter.get("webhook", Document.class);
            if (webhook != null) {
                notification.append("webhook", webhook);
            }
            return event.getMongo().insertTwitchNotification(notification);
        }).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 notification setup for that twitch streamer in " + effectiveChannel.getAsMention()).queue();
                return;
            }
            if (cause instanceof IllegalArgumentException) {
                event.replyFailure(cause.getMessage()).queue();
                return;
            }
            if (ExceptionUtility.sendExceptionally(event, exception)) {
                return;
            }
            if (subscribe.get()) {
                event.getBot().getTwitchManager().subscribe(id);
            }
            event.replyFormat("Notifications will now be sent in %s when **%s** goes live with id `%s` %s", effectiveChannel.getAsMention(), name, result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).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) MongoWriteException(com.mongodb.MongoWriteException) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) Document(org.bson.Document) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) MessageChannel(net.dv8tion.jda.api.entities.MessageChannel) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) CompletionException(java.util.concurrent.CompletionException) BaseGuildMessageChannel(net.dv8tion.jda.api.entities.BaseGuildMessageChannel) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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 23 with Sx4

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

the class TwitchNotificationCommand method toggle.

@Command(value = "toggle", description = "Enables/disables a specific Twitch notification")
@CommandId(496)
@Command.Cooldown(5)
@Examples({ "twitch notification toggle 5e45ce6d3688b30ee75201ae" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void toggle(Sx4CommandEvent event, @Argument(value = "id") ObjectId id) {
    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> countPipeline = List.of(Aggregates.match(Operators.expr(Operators.and(Operators.and(Operators.eq("$streamerId", "$$notification.streamerId"), Operators.extinct("$enabled"))))), Aggregates.limit(2), Aggregates.group(null, Accumulators.sum("streamerCount", 1)));
    List<Bson> pipeline = List.of(Aggregates.match(Filters.eq("guildId", event.getGuild().getIdLong())), Aggregates.project(Projections.include("streamerId", "enabled")), Aggregates.group(null, Accumulators.push("notifications", Operators.ROOT)), Aggregates.unionWith("guilds", guildPipeline), AggregateOperators.mergeFields("premium", "notifications"), Aggregates.project(Projections.fields(Projections.include("premium", "notifications"), Projections.computed("notification", Operators.first(Operators.filter(Operators.ifNull("$notifications", Collections.EMPTY_LIST), Operators.eq("$$this._id", id)))))), Aggregates.lookup("twitchNotifications", List.of(new Variable<>("notification", "$notification")), countPipeline, "streamerCount"), Aggregates.project(Projections.fields(Projections.computed("streamerId", "$notification.streamerId"), Projections.computed("streamerCount", Operators.cond(Operators.isEmpty("$streamerCount"), 0, Operators.get(Operators.arrayElemAt("$streamerCount", 0), "streamerCount"))), Projections.computed("premium", Operators.ifNull("$premium", false)), Projections.computed("count", Operators.size(Operators.ifNull(Operators.filter("$notifications", Operators.extinct("$$this.enabled")), Collections.EMPTY_LIST))), Projections.computed("disabled", Operators.not(Operators.ifNull("$notification.enabled", true))))));
    AtomicInteger subscribe = new AtomicInteger();
    AtomicReference<String> streamerId = new AtomicReference<>();
    event.getMongo().aggregateTwitchNotifications(pipeline).thenCompose(documents -> {
        Document data = documents.isEmpty() ? null : documents.get(0);
        if (data == null || !data.containsKey("streamerId")) {
            throw new IllegalArgumentException("There is not a twitch notification with that id");
        }
        boolean disabled = data.getBoolean("disabled");
        int count = data.getInteger("count");
        if (disabled && count >= 3 && !data.getBoolean("premium")) {
            throw new IllegalArgumentException("You need to have Sx4 premium to have more than 3 enabled twitch notifications, you can get premium at <https://www.patreon.com/Sx4>");
        }
        if (count >= 10) {
            throw new IllegalArgumentException("You can not have any more than 10 enabled twitch notifications");
        }
        int streamerCount = data.getInteger("streamerCount", -1);
        if (disabled && streamerCount == 0) {
            subscribe.set(1);
        } else if (!disabled && streamerCount == 1) {
            subscribe.set(2);
        }
        streamerId.set(data.getString("streamerId"));
        List<Bson> update = List.of(Operators.set("enabled", Operators.cond(Operators.exists("$enabled"), Operators.REMOVE, false)));
        FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().returnDocument(ReturnDocument.AFTER).projection(Projections.include("enabled"));
        return event.getMongo().findAndUpdateTwitchNotification(Filters.eq("_id", id), update, options);
    }).whenComplete((data, exception) -> {
        Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
        if (cause instanceof IllegalArgumentException) {
            event.replyFailure(cause.getMessage()).queue();
            return;
        }
        if (ExceptionUtility.sendExceptionally(event, exception)) {
            return;
        }
        if (data == null) {
            event.replyFailure("There is not a twitch notification with that id").queue();
            return;
        }
        int value = subscribe.get();
        if (value == 1) {
            event.getBot().getTwitchManager().subscribe(streamerId.get());
        } else if (value == 2) {
            event.getBot().getTwitchManager().unsubscribe(streamerId.get());
        }
        event.replySuccess("That twitch notification is now **" + (data.get("enabled", true) ? "enabled" : "disabled") + "**").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) AtomicReference(java.util.concurrent.atomic.AtomicReference) Document(org.bson.Document) Bson(org.bson.conversions.Bson) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) CompletionException(java.util.concurrent.CompletionException) AuthorPermissions(com.sx4.bot.annotations.command.AuthorPermissions) 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 24 with Sx4

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

the class WelcomerCommand method stats.

@Command(value = "stats", aliases = { "settings" }, description = "View basic information about your welcomer configuration")
@CommandId(435)
@Examples({ "welcomer stats" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void stats(Sx4CommandEvent event) {
    Document data = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("welcomer")).get("welcomer", MongoDatabase.EMPTY_DOCUMENT);
    Document image = data.get("image", MongoDatabase.EMPTY_DOCUMENT);
    EmbedBuilder embed = new EmbedBuilder().setAuthor("Welcomer Stats", null, event.getSelfUser().getEffectiveAvatarUrl()).addField("Message Status", data.get("enabled", false) ? "Enabled" : "Disabled", true).addField("Channel", data.containsKey("channelId") ? "<#" + data.get("channelId") + ">" : "None", true).addField("Image Status", image.getBoolean("enabled", false) ? "Enabled" : "Disabled", true).addField("Private Message Status", data.getBoolean("dm", false) ? "Enabled" : "Disabled", true).addField("Webhook Name", data.getEmbedded(List.of("webhook", "name"), "Sx4 - Welcomer"), true).addField("Webhook Avatar", data.getEmbedded(List.of("webhook", "avatar"), event.getSelfUser().getEffectiveAvatarUrl()), true);
    event.reply(embed.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 25 with Sx4

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

the class LeaverCommand method stats.

@Command(value = "stats", aliases = { "settings" }, description = "View basic information about your leaver configuration")
@CommandId(440)
@Examples({ "leaver stats" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void stats(Sx4CommandEvent event) {
    Document data = event.getMongo().getGuildById(event.getGuild().getIdLong(), Projections.include("leaver")).get("leaver", MongoDatabase.EMPTY_DOCUMENT);
    EmbedBuilder embed = new EmbedBuilder().setAuthor("Leaver Stats", null, event.getSelfUser().getEffectiveAvatarUrl()).addField("Message Status", data.get("enabled", false) ? "Enabled" : "Disabled", true).addField("Channel", data.containsKey("channelId") ? "<#" + data.get("channelId") + ">" : "None", true).addField("Private Message Status", data.getBoolean("dm", false) ? "Enabled" : "Disabled", true).addField("Webhook Name", data.getEmbedded(List.of("webhook", "name"), "Sx4 - Leaver"), true).addField("Webhook Avatar", data.getEmbedded(List.of("webhook", "avatar"), event.getSelfUser().getEffectiveAvatarUrl()), true);
    event.reply(embed.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

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