Search in sources :

Example 91 with Argument

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

the class SteamCommand method game.

@Command(value = "profile", description = "Look up information about a steam profile")
@CommandId(212)
@Examples({ "steam profile dog", "steam profile https://steamcommunity.com/id/dog" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void game(Sx4CommandEvent event, @Argument(value = "query", endless = true, nullDefault = true) String query) {
    List<Document> profiles;
    if (query == null) {
        List<Document> connections = event.getMongo().getUserById(event.getAuthor().getIdLong(), Projections.include("connections.steam")).getEmbedded(List.of("connections", "steam"), Collections.emptyList());
        if (connections.isEmpty()) {
            event.replyFailure("You do not have a steam account linked, use `steam connect` to link an account or provide an argument to search").queue();
            return;
        }
        profiles = connections.stream().map(data -> data.append("url", "https://steamcommunity.com/profiles/" + data.getLong("id"))).collect(Collectors.toList());
    } else {
        profiles = List.of(new Document("url", this.getProfileUrl(query)));
    }
    PagedResult<Document> paged = new PagedResult<>(event.getBot(), profiles).setAutoSelect(true).setAuthor("Steam Profiles", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setDisplayFunction(data -> "[" + data.getString("name") + "](" + data.getString("url") + ")");
    paged.onSelect(select -> {
        String url = select.getSelected().getString("url");
        Request request = new Request.Builder().url(url + "?xml=1").build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            JSONObject json = XML.toJSONObject(response.body().string());
            if (json.has("response")) {
                event.replyFailure("I could not find that steam user").queue();
                return;
            }
            JSONObject profile = json.getJSONObject("profile");
            if (profile.getInt("visibilityState") == 1) {
                event.replyFailure("That profile is private").queue();
                return;
            }
            JSONObject mostPlayedGames = profile.optJSONObject("mostPlayedGames");
            JSONArray gamesArray = mostPlayedGames == null ? new JSONArray() : mostPlayedGames.optJSONArray("mostPlayedGame");
            if (gamesArray == null) {
                gamesArray = new JSONArray().put(mostPlayedGames.getJSONObject("mostPlayedGame"));
            }
            double hours = 0D;
            StringBuilder gamesString = new StringBuilder();
            for (int i = 0; i < gamesArray.length(); i++) {
                JSONObject game = gamesArray.getJSONObject(i);
                hours += game.getDouble("hoursPlayed");
                gamesString.append(String.format("[%s](%s) - **%.1f** hours\n", game.getString("gameName"), game.getString("gameLink"), game.getDouble("hoursPlayed")));
            }
            String stateMessage = profile.getString("stateMessage");
            String location = profile.getString("location");
            String realName = profile.getString("realname");
            EmbedBuilder embed = new EmbedBuilder();
            embed.setAuthor(profile.getString("steamID"), url, profile.getString("avatarFull"));
            embed.setDescription(Jsoup.parse(profile.getString("summary")).text());
            embed.setFooter("ID: " + profile.getLong("steamID64"));
            embed.setThumbnail(profile.getString("avatarFull"));
            embed.addField("Real Name", realName.isBlank() ? "None Given" : realName, true);
            embed.addField("Created At", LocalDate.parse(profile.getString("memberSince"), DateTimeFormatter.ofPattern("LLLL d, yyyy")).format(this.formatter), true);
            embed.addField("Status", StringUtility.title(profile.getString("onlineState")), true);
            embed.addField("State Message", Jsoup.parse(stateMessage).text(), true);
            embed.addField("Vac Bans", String.valueOf(profile.getInt("vacBanned")), true);
            if (!location.isBlank()) {
                embed.addField("Location", location, true);
            }
            if (hours != 0) {
                gamesString.append(String.format("\nTotal - **%.1f** hours", hours));
                embed.addField("Games Played (2 Weeks)", gamesString.toString(), false);
            }
            event.reply(embed.build()).queue();
        });
    });
    paged.execute(event);
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) 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) EmbedType(net.dv8tion.jda.api.entities.EmbedType) JSONObject(org.json.JSONObject) Matcher(java.util.regex.Matcher) Role(net.dv8tion.jda.api.entities.Role) XML(org.json.XML) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) 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) 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) JSONObject(org.json.JSONObject) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) JSONArray(org.json.JSONArray) Document(org.bson.Document) 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 92 with Argument

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

the class TranslateCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "to") Locale to, @Argument(value = "query | message id", endless = true, acceptEmpty = true) Or<MessageArgument, String> option, @Option(value = "from", description = "Choose what language to translate from") Locale from) {
    String toTag = to.getLanguage(), fromTag = from == null ? "auto" : from.getLanguage();
    this.getQuery(option).whenComplete((query, exception) -> {
        if (query.length() > 1000) {
            event.replyFailure("Query length cannot be any more than **1000** characters").queue();
            return;
        }
        FormBody requestBody = new FormBody.Builder().addEncoded("f.req", "%5B%5B%5B%22MkEWBc%22%2C%22%5B%5B%5C%22" + URLEncoder.encode(query, StandardCharsets.UTF_8).replace("%0A", "\n") + "%5C%22%2C%5C%22" + fromTag + "%5C%22%2C%5C%22" + toTag + "%5C%22%2Ctrue%5D%2C%5Bnull%5D%5D%22%2Cnull%2C%22generic%22%5D%5D%5D").build();
        Request request = new Request.Builder().url("https://translate.google.com/_/TranslateWebserverUi/data/batchexecute").post(requestBody).build();
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> event.reply(this.getEmbed(response.body().string(), query, from, to)).queue());
    });
}
Also used : TextNode(org.jsoup.nodes.TextNode) MessageArgument(com.sx4.bot.entities.argument.MessageArgument) Permission(net.dv8tion.jda.api.Permission) CompletableFuture(java.util.concurrent.CompletableFuture) FormBody(okhttp3.FormBody) JSONObject(org.json.JSONObject) Locale(java.util.Locale) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Element(org.jsoup.nodes.Element) Option(com.jockie.bot.core.option.Option) Or(com.sx4.bot.entities.argument.Or) Argument(com.jockie.bot.core.argument.Argument) Message(net.dv8tion.jda.api.entities.Message) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) SearchUtility(com.sx4.bot.utility.SearchUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) Document(org.jsoup.nodes.Document) StringJoiner(java.util.StringJoiner) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Jsoup(org.jsoup.Jsoup) JSONArray(org.json.JSONArray) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) FormBody(okhttp3.FormBody) Request(okhttp3.Request)

Example 93 with Argument

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

the class UrbanDictionaryCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
    Request request = new Request.Builder().url("http://api.urbandictionary.com/v0/define?term=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
    event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
        Document json = Document.parse(response.body().string());
        List<Document> list = json.getList("list", Document.class, Collections.emptyList());
        if (list.isEmpty()) {
            event.replyFailure("I could not find any results for that query").queue();
            return;
        }
        PagedResult<Document> paged = new PagedResult<>(event.getBot(), list).setPerPage(1).setCustomFunction(page -> {
            EmbedBuilder embed = new EmbedBuilder();
            embed.setFooter(PagedResult.DEFAULT_FOOTER_TEXT, null);
            embed.setTitle("Page " + page.getPage() + "/" + page.getMaxPage());
            page.forEach((data, index) -> {
                String readMore = "... [Read more](" + data.getString("permalink") + ")";
                String definition = this.getUrbanText(data.getString("definition"), readMore);
                String example = this.getUrbanText(data.getString("example"), readMore);
                embed.setAuthor(data.getString("word"), data.getString("permalink"), null);
                embed.addField("Definition", definition, false);
                if (!example.isEmpty()) {
                    embed.addField("Example", example, false);
                }
                embed.addField("Upvotes", data.getInteger("thumbs_up") + " 👍", true);
                embed.addField("Downvotes", data.getInteger("thumbs_down") + " 👎", true);
            });
            return new MessageBuilder().setEmbeds(embed.build());
        });
        paged.execute(event);
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) PagedResult(com.sx4.bot.paged.PagedResult) StandardCharsets(java.nio.charset.StandardCharsets) ModuleCategory(com.sx4.bot.category.ModuleCategory) URLEncoder(java.net.URLEncoder) List(java.util.List) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Collections(java.util.Collections) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) List(java.util.List) Document(org.bson.Document) PagedResult(com.sx4.bot.paged.PagedResult)

Example 94 with Argument

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

the class UserBannerCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
    User user = member == null ? event.getAuthor() : member.getUser();
    user.retrieveProfile().queue(profile -> {
        String banner = profile.getBannerUrl();
        if (banner == null) {
            int accent = profile.getAccentColorRaw();
            if (accent == User.DEFAULT_ACCENT_COLOR_RAW) {
                event.replyFailure("That user does not have a banner").queue();
                return;
            }
            String accentBanner = event.getConfig().getImageWebserverUrl("colour") + "?colour=" + accent + "&w=1024&h=205";
            EmbedBuilder embed = new EmbedBuilder().setImage(accentBanner).setColor(accent).setAuthor(user.getAsTag(), accentBanner, user.getEffectiveAvatarUrl());
            event.reply(embed.build()).queue();
            return;
        }
        Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("median-colour")).addQuery("image", banner).build(event.getConfig().getImageWebserver());
        event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
            if (!response.isSuccessful()) {
                ImageUtility.getErrorMessage(event.getTextChannel(), response.code(), response.body().string()).queue();
                return;
            }
            Document data = Document.parse(response.body().string());
            String sizedAvatar = banner + "?size=1024";
            EmbedBuilder embed = new EmbedBuilder().setImage(sizedAvatar).setColor(data.getInteger("colour")).setAuthor(user.getAsTag(), sizedAvatar, user.getEffectiveAvatarUrl());
            event.reply(embed.build()).queue();
        });
    });
}
Also used : Document(org.bson.Document) ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Member(net.dv8tion.jda.api.entities.Member) Argument(com.jockie.bot.core.argument.Argument) User(net.dv8tion.jda.api.entities.User) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Document(org.bson.Document)

Example 95 with Argument

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

the class UserInfoCommand method onCommand.

public void onCommand(Sx4CommandEvent event, @Argument(value = "user", nullDefault = true) @UserId long userId) {
    RestAction<User> action = userId == 0L ? new CompletedRestAction<>(event.getJDA(), event.getAuthor()) : event.getJDA().retrieveUserById(userId);
    action.flatMap(user -> {
        EmbedBuilder embed = new EmbedBuilder().setDescription(event.getConfig().getUserFlagEmotes(user.getFlags())).setAuthor(user.getAsTag(), user.getEffectiveAvatarUrl(), user.getEffectiveAvatarUrl()).setThumbnail(user.getEffectiveAvatarUrl()).addField("Joined Discord", user.getTimeCreated().format(TimeUtility.DEFAULT_FORMATTER), true).addField("User ID", user.getId(), true).addField("Bot", user.isBot() ? "Yes" : "No", false);
        return event.reply(embed.build());
    }).onErrorFlatMap(exception -> {
        if (exception instanceof ErrorResponseException && ((ErrorResponseException) exception).getErrorResponse() == ErrorResponse.UNKNOWN_USER) {
            return event.replyFailure("I could not find that user");
        }
        return null;
    }).queue();
}
Also used : UserId(com.sx4.bot.annotations.argument.UserId) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException) CompletedRestAction(net.dv8tion.jda.internal.requests.CompletedRestAction) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ErrorResponse(net.dv8tion.jda.api.requests.ErrorResponse) User(net.dv8tion.jda.api.entities.User) ModuleCategory(com.sx4.bot.category.ModuleCategory) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) RestAction(net.dv8tion.jda.api.requests.RestAction) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) ErrorResponseException(net.dv8tion.jda.api.exceptions.ErrorResponseException)

Aggregations

Argument (com.jockie.bot.core.argument.Argument)109 ModuleCategory (com.sx4.bot.category.ModuleCategory)109 Sx4Command (com.sx4.bot.core.Sx4Command)109 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)109 Permission (net.dv8tion.jda.api.Permission)96 Document (org.bson.Document)67 PagedResult (com.sx4.bot.paged.PagedResult)57 HttpCallback (com.sx4.bot.http.HttpCallback)54 Request (okhttp3.Request)53 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)50 Command (com.jockie.bot.core.command.Command)48 List (java.util.List)47 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)42 Bson (org.bson.conversions.Bson)42 Operators (com.sx4.bot.database.mongo.model.Operators)40 User (net.dv8tion.jda.api.entities.User)40 CommandId (com.sx4.bot.annotations.command.CommandId)39 Examples (com.sx4.bot.annotations.command.Examples)39 Alternative (com.sx4.bot.entities.argument.Alternative)37 AlternativeOptions (com.sx4.bot.annotations.argument.AlternativeOptions)36