Search in sources :

Example 36 with BotPermissions

use of com.sx4.bot.annotations.command.BotPermissions 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;
    }
    BaseGuildMessageChannel channel = event.getGuild().getChannelById(BaseGuildMessageChannel.class, 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) net.dv8tion.jda.api.entities(net.dv8tion.jda.api.entities) WebhookClient(club.minnced.discord.webhook.WebhookClient) Command(com.jockie.bot.core.command.Command) 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) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) PagedResult(com.sx4.bot.paged.PagedResult) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) ColourUtility(com.sx4.bot.utility.ColourUtility) Button(net.dv8tion.jda.api.interactions.components.buttons.Button) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) AlternativeOptions(com.sx4.bot.annotations.argument.AlternativeOptions) 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) Operators(com.sx4.bot.database.mongo.model.Operators) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) Sx4Command(com.sx4.bot.core.Sx4Command) Colour(com.sx4.bot.annotations.argument.Colour) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) ImageUrl(com.sx4.bot.annotations.argument.ImageUrl) CustomButtonId(com.sx4.bot.entities.interaction.CustomButtonId) 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) ButtonType(com.sx4.bot.entities.interaction.ButtonType) Suggestion(com.sx4.bot.entities.management.Suggestion) 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 37 with BotPermissions

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

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

Example 39 with BotPermissions

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

the class LeaverCommand method formatters.

@Command(value = "formatters", aliases = { "format", "formatting" }, description = "Get all the formatters for leaver you can use")
@CommandId(442)
@Examples({ "leaver formatters" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void formatters(Sx4CommandEvent event) {
    EmbedBuilder embed = new EmbedBuilder().setAuthor("Leaver 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(Member.class)) {
        content.add("`{member." + variable.getName() + "}` - " + variable.getDescription());
    }
    for (FormatterVariable<?> variable : manager.getVariables(Guild.class)) {
        content.add("`{server." + variable.getName() + "}` - " + variable.getDescription());
    }
    for (FormatterVariable<?> variable : manager.getVariables(OffsetDateTime.class)) {
        content.add("`{now." + variable.getName() + "}` - " + variable.getDescription());
    }
    content.add("`{user.age}` - Gets the age of a user as a string");
    content.add("`{member.age}` - Gets the age of a member as a string");
    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) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command)

Example 40 with BotPermissions

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

the class SteamCommand method game.

@Command(value = "game", description = "View information about a game on steam")
@CommandId(34)
@Examples({ "steam game Grand Theft Auto", "steam game 1293830", "steam game https://store.steampowered.com/app/1293830/Forza_Horizon_4/" })
@Cooldown(5)
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void game(Sx4CommandEvent event, @Argument(value = "query", endless = true, nullDefault = true) String query, @Option(value = "random", description = "Gets a random game") boolean random) {
    if (query == null && !random) {
        event.replyHelp().queue();
        return;
    }
    SteamGameCache cache = event.getBot().getSteamGameCache();
    if (cache.getGames().isEmpty()) {
        event.replyFailure("The steam cache is currently empty, try again").queue();
        return;
    }
    Matcher urlMatcher;
    List<Document> games;
    if (query == null) {
        List<Document> cacheGames = cache.getGames();
        games = List.of(cacheGames.get(event.getRandom().nextInt(cacheGames.size())));
    } else if (NumberUtility.isNumberUnsigned(query)) {
        games = List.of(new Document("appid", Integer.parseInt(query)));
    } else if ((urlMatcher = this.gamePattern.matcher(query)).matches()) {
        games = List.of(new Document("appid", Integer.parseInt(urlMatcher.group(1))));
    } else {
        games = cache.getGames(query);
        if (games.isEmpty()) {
            event.replyFailure("I could not find any games with that query").queue();
            return;
        }
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), games).setAuthor("Steam Search", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setIncreasedIndex(true).setAutoSelect(true).setTimeout(60).setDisplayFunction(game -> game.getString("name"));
    paged.onSelect(select -> {
        Document game = select.getSelected();
        int appId = game.getInteger("appid");
        Request request = new Request.Builder().url("https://store.steampowered.com/api/appdetails?cc=gb&appids=" + appId).build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            Document json = Document.parse(response.body().string()).get(String.valueOf(appId), Document.class);
            if (!json.getBoolean("success")) {
                event.replyFailure("Steam failed to get data for that game").queue();
                return;
            }
            List<MessageEmbed> embeds = new ArrayList<>();
            Document gameInfo = json.get("data", Document.class);
            String description = Jsoup.parse(gameInfo.getString("short_description")).text();
            String price;
            if (gameInfo.containsKey("price_overview")) {
                Document priceOverview = gameInfo.get("price_overview", Document.class);
                double initialPrice = priceOverview.getInteger("initial") / 100D, finalPrice = priceOverview.getInteger("final") / 100D;
                price = initialPrice == finalPrice ? String.format("£%,.2f", finalPrice) : String.format("~~£%,.2f~~ £%,.2f (-%d%%)", initialPrice, finalPrice, priceOverview.getInteger("discount_percent"));
            } else {
                price = gameInfo.getBoolean("is_free") ? "Free" : "Unknown";
            }
            EmbedBuilder embed = new EmbedBuilder();
            embed.setDescription(description);
            embed.setTitle(gameInfo.getString("name"), "https://store.steampowered.com/app/" + appId);
            embed.setAuthor("Steam", "https://steamcommunity.com", "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png");
            embed.setImage(gameInfo.getString("header_image"));
            embed.addField("Price", price, true);
            embed.setFooter("Developed by " + (gameInfo.containsKey("developers") ? String.join(", ", gameInfo.getList("developers", String.class)) : "Unknown"), null);
            Document releaseDate = gameInfo.get("release_date", Document.class);
            String date = releaseDate.getString("date");
            embed.addField("Release Date", String.format("%s%s", date.isBlank() ? "Unknown" : date, releaseDate.getBoolean("coming_soon") ? " (Coming Soon)" : ""), true);
            Object age = gameInfo.get("required_age");
            embed.addField("Required Age", age instanceof Integer ? ((int) age) == 0 ? "No Age Restriction" : String.valueOf((int) age) : (String) age, true);
            embed.addField("Recommendations", String.format("%,d", gameInfo.getEmbedded(List.of("recommendations", "total"), 0)), true);
            embed.addField("Supported Languages", gameInfo.containsKey("supported_languages") ? Jsoup.parse(gameInfo.getString("supported_languages")).text() : "Unknown", true);
            List<Document> genres = gameInfo.getList("genres", Document.class);
            embed.addField("Genres", genres == null ? "None" : genres.stream().map(genre -> genre.getString("description")).collect(Collectors.joining("\n")), true);
            embeds.add(embed.build());
            gameInfo.getList("screenshots", Document.class).stream().limit(3).map(d -> d.getString("path_thumbnail")).map(url -> embed.setImage(url).build()).forEach(embeds::add);
            event.getChannel().sendMessageEmbeds(embeds).queue();
        });
    });
    paged.onTimeout(() -> event.reply("Response timed out :stopwatch:").queue());
    paged.execute(event);
}
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) Matcher(java.util.regex.Matcher) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) Document(org.bson.Document) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) SteamGameCache(com.sx4.bot.cache.SteamGameCache) JSONObject(org.json.JSONObject) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) Cooldown(com.jockie.bot.core.command.Command.Cooldown) 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