Search in sources :

Example 1 with LoadingMessage

use of me.shadorc.shadbot.utils.object.LoadingMessage in project Shadbot by Shadorc.

the class WeatherCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException {
    if (!context.hasArg()) {
        throw new MissingArgumentException();
    }
    LoadingMessage loadingMsg = new LoadingMessage("Loading weather information...", context.getChannel());
    loadingMsg.send();
    try {
        OpenWeatherMap owm = new OpenWeatherMap(Units.METRIC, APIKeys.get(APIKey.OPENWEATHERMAP_API_KEY));
        CurrentWeather weather = owm.currentWeatherByCityName(context.getArg());
        if (!weather.isValid()) {
            loadingMsg.edit(TextUtils.noResult(context.getArg()));
            return;
        }
        String clouds = StringUtils.capitalize(weather.getWeatherInstance(0).getWeatherDescription());
        float windSpeed = weather.getWindInstance().getWindSpeed() * 3.6f;
        String windDesc = this.getWindDesc(windSpeed);
        String rain = weather.hasRainInstance() ? String.format("%.1f mm/h", weather.getRainInstance().getRain3h()) : "None";
        float humidity = weather.getMainInstance().getHumidity();
        float temperature = weather.getMainInstance().getTemperature();
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName("Weather for: " + weather.getCityName()).withThumbnail("https://image.flaticon.com/icons/svg/494/494472.svg").withAuthorUrl("http://openweathermap.org/city/" + weather.getCityCode()).appendDescription("Last updated " + dateFormatter.format(weather.getDateTime())).appendField(Emoji.CLOUD + " Clouds", clouds, true).appendField(Emoji.WIND + " Wind", String.format("%s%n%.1f km/h", windDesc, windSpeed), true).appendField(Emoji.RAIN + " Rain", rain, true).appendField(Emoji.DROPLET + " Humidity", String.format("%.1f%%", humidity), true).appendField(Emoji.THERMOMETER + " Temperature", String.format("%.1f°C", temperature), true);
        loadingMsg.edit(embed.build());
    } catch (IOException err) {
        loadingMsg.delete();
        Utils.handle("getting weather information", context, err);
    }
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) CurrentWeather(net.aksingh.owmjapis.CurrentWeather) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) OpenWeatherMap(net.aksingh.owmjapis.OpenWeatherMap) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException)

Example 2 with LoadingMessage

use of me.shadorc.shadbot.utils.object.LoadingMessage in project Shadbot by Shadorc.

the class LyricsCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException {
    List<String> args = StringUtils.split(context.getArg(), 2, "-");
    if (args.size() != 2) {
        throw new MissingArgumentException();
    }
    LoadingMessage loadingMsg = new LoadingMessage("Loading lyrics...", context.getChannel());
    loadingMsg.send();
    try {
        String artistSrch = NetUtils.encode(args.get(0).replaceAll("[^A-Za-z0-9]", "-"));
        String titleSrch = NetUtils.encode(args.get(1).replaceAll("[^A-Za-z0-9]", "-"));
        // Make a direct search with the artist and the title
        String url = String.format("%s/lyrics/%s/%s", HOME_URL, artistSrch, titleSrch);
        Response response = NetUtils.getResponse(url);
        Document doc = NetUtils.getResponse(url).parse().outputSettings(PRESERVE_FORMAT);
        // If the direct search found nothing
        if (response.statusCode() == 404 || response.parse().text().contains("Oops! We couldn't find that page.")) {
            url = String.format("%s/search/%s-%s?", HOME_URL, artistSrch, titleSrch);
            // Make a search request on the site
            Document searchDoc = NetUtils.getDoc(url);
            Element trackListElement = searchDoc.getElementsByClass("tracks list").first();
            if (trackListElement == null) {
                loadingMsg.edit(TextUtils.noResult(context.getArg()));
                return;
            }
            // Find the first element containing "title" (generally the best result) and get its URL
            url = HOME_URL + trackListElement.getElementsByClass("title").attr("href");
            doc = NetUtils.getDoc(url).outputSettings(PRESERVE_FORMAT);
        }
        String artist = doc.getElementsByClass("mxm-track-title__artist").html();
        String title = StringUtils.remove(doc.getElementsByClass("mxm-track-title__track ").text(), "Lyrics");
        String albumImg = "https:" + doc.getElementsByClass("banner-album-image").select("img").first().attr("src");
        String lyrics = StringUtils.truncate(doc.getElementsByClass("mxm-lyrics__content ").html(), MAX_LYRICS_LENGTH);
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().setLenient(true).withAuthorName(String.format("Lyrics (%s - %s)", artist, title)).withAuthorUrl(url).withThumbnail(albumImg).appendDescription(url + "\n\n" + lyrics);
        loadingMsg.edit(embed.build());
    } catch (IOException err) {
        loadingMsg.delete();
        Utils.handle("getting lyrics", context, err);
    }
}
Also used : Response(org.jsoup.Connection.Response) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) Element(org.jsoup.nodes.Element) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException) Document(org.jsoup.nodes.Document)

Example 3 with LoadingMessage

use of me.shadorc.shadbot.utils.object.LoadingMessage in project Shadbot by Shadorc.

the class GifCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException {
    LoadingMessage loadingMsg = new LoadingMessage("Loading gif...", context.getChannel());
    loadingMsg.send();
    try {
        String url = String.format("https://api.giphy.com/v1/gifs/random?api_key=%s&tag=%s", APIKeys.get(APIKey.GIPHY_API_KEY), NetUtils.encode(context.getArg()));
        String bodyText = NetUtils.getBody(url);
        // If the body is HTML, Giphy did not returned JSON
        if (bodyText.charAt(0) != '{') {
            throw new HttpStatusException("Giphy did not return valid JSON.", 503, url);
        }
        JSONObject mainObj = new JSONObject(bodyText);
        if (!mainObj.has("data")) {
            throw new HttpStatusException("Giphy did not return valid JSON.", 503, url);
        }
        if (mainObj.get("data") instanceof JSONArray) {
            loadingMsg.edit(TextUtils.noResult(context.getArg()));
            return;
        }
        EmbedBuilder embed = new EmbedBuilder().withColor(Config.BOT_COLOR).withImage(mainObj.getJSONObject("data").getString("image_url"));
        loadingMsg.edit(embed.build());
    } catch (JSONException | IOException err) {
        loadingMsg.delete();
        Utils.handle("getting a gif", context, err);
    }
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) HttpStatusException(org.jsoup.HttpStatusException) JSONException(org.json.JSONException) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException)

Example 4 with LoadingMessage

use of me.shadorc.shadbot.utils.object.LoadingMessage in project Shadbot by Shadorc.

the class ImageCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException {
    if (!context.hasArg()) {
        throw new MissingArgumentException();
    }
    LoadingMessage loadingMsg = new LoadingMessage("Loading image...", context.getChannel());
    loadingMsg.send();
    try {
        JSONObject resultObj = this.getRandomPopularResult(NetUtils.encode(context.getArg()));
        if (resultObj == null) {
            loadingMsg.edit(TextUtils.noResult(context.getArg()));
            return;
        }
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName("DeviantArt (Search: " + context.getArg() + ")").withAuthorUrl(resultObj.getString("url")).withThumbnail("http://www.pngall.com/wp-content/uploads/2016/04/Deviantart-Logo-Transparent.png").appendField("Title", resultObj.getString("title"), false).appendField("Author", resultObj.getJSONObject("author").getString("username"), false).appendField("Category", resultObj.getString("category_path"), false).withImage(resultObj.getJSONObject("content").getString("src"));
        loadingMsg.edit(embed.build());
    } catch (JSONException | IOException err) {
        loadingMsg.delete();
        Utils.handle("getting an image", context, err);
    }
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) JSONObject(org.json.JSONObject) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) JSONException(org.json.JSONException) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException)

Example 5 with LoadingMessage

use of me.shadorc.shadbot.utils.object.LoadingMessage in project Shadbot by Shadorc.

the class WallpaperCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException, IllegalCmdArgumentException {
    LoadingMessage loadingMsg = new LoadingMessage("Loading wallpaper...", context.getChannel());
    loadingMsg.send();
    if (wallhaven == null) {
        wallhaven = new Wallhaven(APIKeys.get(APIKey.WALLHAVEN_LOGIN), APIKeys.get(APIKey.WALLHAVEN_PASSWORD));
    }
    Options options = new Options();
    options.addOption("p", PURITY, true, FormatUtils.format(Purity.values(), purity -> purity.toString().toLowerCase(), ", "));
    options.addOption("c", CATEGORY, true, FormatUtils.format(Category.values(), cat -> cat.toString().toLowerCase(), ", "));
    Option ratioOpt = new Option("rat", RATIO, true, "image ratio");
    ratioOpt.setValueSeparator('x');
    options.addOption(ratioOpt);
    Option resOpt = new Option("res", RESOLUTION, true, "image resolution");
    resOpt.setValueSeparator('x');
    options.addOption(resOpt);
    Option keyOpt = new Option("k", KEYWORD, true, KEYWORD);
    keyOpt.setValueSeparator(',');
    options.addOption(keyOpt);
    CommandLine cmdLine;
    try {
        List<String> args = StringUtils.split(context.getArg());
        cmdLine = new DefaultParser().parse(options, args.toArray(new String[args.size()]));
    } catch (UnrecognizedOptionException | org.apache.commons.cli.MissingArgumentException err) {
        loadingMsg.delete();
        throw new IllegalCmdArgumentException(String.format("%s. Use `%shelp %s` for more information.", err.getMessage(), context.getPrefix(), this.getName()));
    } catch (ParseException err) {
        loadingMsg.delete();
        Utils.handle("getting a wallpaper", context, err);
        return;
    }
    Purity purity = this.parseEnum(loadingMsg, context, Purity.class, PURITY, cmdLine.getOptionValue(PURITY, Purity.SFW.toString()));
    if ((purity.equals(Purity.NSFW) || purity.equals(Purity.SKETCHY)) && !context.getChannel().isNSFW()) {
        loadingMsg.edit(TextUtils.mustBeNSFW(context.getPrefix()));
        return;
    }
    SearchQueryBuilder queryBuilder = new SearchQueryBuilder();
    queryBuilder.purity(purity);
    if (cmdLine.hasOption(CATEGORY)) {
        queryBuilder.categories(this.parseEnum(loadingMsg, context, Category.class, CATEGORY, cmdLine.getOptionValue(CATEGORY)));
    }
    if (cmdLine.hasOption(RATIO)) {
        Dimension dim = this.parseDim(loadingMsg, context, RATIO, cmdLine.getOptionValues(RATIO));
        queryBuilder.ratios(new Ratio((int) dim.getWidth(), (int) dim.getHeight()));
    }
    if (cmdLine.hasOption(RESOLUTION)) {
        Dimension dim = this.parseDim(loadingMsg, context, RESOLUTION, cmdLine.getOptionValues(RESOLUTION));
        queryBuilder.resolutions(new Resolution((int) dim.getWidth(), (int) dim.getHeight()));
    }
    if (cmdLine.hasOption(KEYWORD)) {
        queryBuilder.keywords(cmdLine.getOptionValues(KEYWORD));
    }
    try {
        List<Wallpaper> wallpapers = wallhaven.search(queryBuilder.pages(1).build());
        if (wallpapers.isEmpty()) {
            loadingMsg.edit(TextUtils.noResult(context.getMessage().getContent()));
            return;
        }
        Wallpaper wallpaper = wallpapers.get(ThreadLocalRandom.current().nextInt(wallpapers.size()));
        String tags = FormatUtils.format(wallpaper.getTags(), tag -> String.format("`%s`", StringUtils.remove(tag.toString(), "#")), " ");
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName("Wallpaper").withAuthorUrl(wallpaper.getUrl()).withImage(wallpaper.getImageUrl()).appendField("Resolution", wallpaper.getResolution().toString(), false).appendField("Tags", tags, false);
        loadingMsg.edit(embed.build());
    } catch (ConnectionException err) {
        loadingMsg.delete();
        Utils.handle("getting a wallpaper", context, err.getCause());
    }
}
Also used : HelpBuilder(me.shadorc.shadbot.utils.embed.HelpBuilder) Wallhaven(com.ivkos.wallhaven4j.Wallhaven) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) Options(org.apache.commons.cli.Options) Ratio(com.ivkos.wallhaven4j.models.misc.Ratio) Category(com.ivkos.wallhaven4j.models.misc.enums.Category) Purity(com.ivkos.wallhaven4j.models.misc.enums.Purity) DefaultParser(org.apache.commons.cli.DefaultParser) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) StringUtils(me.shadorc.shadbot.utils.StringUtils) Command(me.shadorc.shadbot.core.command.annotation.Command) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) TextUtils(me.shadorc.shadbot.utils.TextUtils) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) CommandLine(org.apache.commons.cli.CommandLine) Option(org.apache.commons.cli.Option) Utils(me.shadorc.shadbot.utils.Utils) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) Resolution(com.ivkos.wallhaven4j.models.misc.Resolution) RateLimited(me.shadorc.shadbot.core.command.annotation.RateLimited) UnrecognizedOptionException(org.apache.commons.cli.UnrecognizedOptionException) SearchQueryBuilder(com.ivkos.wallhaven4j.util.searchquery.SearchQueryBuilder) APIKeys(me.shadorc.shadbot.data.APIKeys) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) FormatUtils(me.shadorc.shadbot.utils.FormatUtils) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) CastUtils(me.shadorc.shadbot.utils.CastUtils) ConnectionException(com.ivkos.wallhaven4j.util.exceptions.ConnectionException) Dimension(java.awt.Dimension) List(java.util.List) Context(me.shadorc.shadbot.core.command.Context) ParseException(org.apache.commons.cli.ParseException) AbstractCommand(me.shadorc.shadbot.core.command.AbstractCommand) APIKey(me.shadorc.shadbot.data.APIKeys.APIKey) EmbedUtils(me.shadorc.shadbot.utils.embed.EmbedUtils) Wallpaper(com.ivkos.wallhaven4j.models.wallpaper.Wallpaper) Options(org.apache.commons.cli.Options) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) Category(com.ivkos.wallhaven4j.models.misc.enums.Category) Purity(com.ivkos.wallhaven4j.models.misc.enums.Purity) UnrecognizedOptionException(org.apache.commons.cli.UnrecognizedOptionException) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) Ratio(com.ivkos.wallhaven4j.models.misc.Ratio) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) DefaultParser(org.apache.commons.cli.DefaultParser) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) Dimension(java.awt.Dimension) CommandLine(org.apache.commons.cli.CommandLine) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) SearchQueryBuilder(com.ivkos.wallhaven4j.util.searchquery.SearchQueryBuilder) Option(org.apache.commons.cli.Option) Wallpaper(com.ivkos.wallhaven4j.models.wallpaper.Wallpaper) Wallhaven(com.ivkos.wallhaven4j.Wallhaven) ParseException(org.apache.commons.cli.ParseException) ConnectionException(com.ivkos.wallhaven4j.util.exceptions.ConnectionException) Resolution(com.ivkos.wallhaven4j.models.misc.Resolution)

Aggregations

LoadingMessage (me.shadorc.shadbot.utils.object.LoadingMessage)15 IOException (java.io.IOException)13 EmbedBuilder (sx.blah.discord.util.EmbedBuilder)13 MissingArgumentException (me.shadorc.shadbot.exception.MissingArgumentException)10 JSONException (org.json.JSONException)7 JSONObject (org.json.JSONObject)6 AbstractCommand (me.shadorc.shadbot.core.command.AbstractCommand)5 CommandCategory (me.shadorc.shadbot.core.command.CommandCategory)5 Context (me.shadorc.shadbot.core.command.Context)5 Command (me.shadorc.shadbot.core.command.annotation.Command)5 RateLimited (me.shadorc.shadbot.core.command.annotation.RateLimited)5 Utils (me.shadorc.shadbot.utils.Utils)5 EmbedUtils (me.shadorc.shadbot.utils.embed.EmbedUtils)5 HelpBuilder (me.shadorc.shadbot.utils.embed.HelpBuilder)5 EmbedObject (sx.blah.discord.api.internal.json.objects.EmbedObject)5 List (java.util.List)4 IllegalCmdArgumentException (me.shadorc.shadbot.exception.IllegalCmdArgumentException)4 FormatUtils (me.shadorc.shadbot.utils.FormatUtils)4 NetUtils (me.shadorc.shadbot.utils.NetUtils)4 StringUtils (me.shadorc.shadbot.utils.StringUtils)4