Search in sources :

Example 6 with LoadingMessage

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

the class ThisDayCmd method execute.

@Override
public void execute(Context context) {
    LoadingMessage loadingMsg = new LoadingMessage("Loading information...", context.getChannel());
    loadingMsg.send();
    try {
        Document doc = NetUtils.getDoc(HOME_URL);
        String date = doc.getElementsByClass("date-large").first().attr("datetime");
        Elements eventsElmt = doc.getElementsByClass("event-list event-list--with-advert").first().getElementsByClass("event-list__item");
        String events = eventsElmt.stream().map(elmt -> Jsoup.parse(elmt.html().replaceAll("<b>|</b>", "**")).text()).collect(Collectors.joining("\n\n"));
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName(String.format("On This Day (%s)", date)).withAuthorUrl(HOME_URL).withThumbnail("http://icons.iconarchive.com/icons/paomedia/small-n-flat/1024/calendar-icon.png").appendDescription(StringUtils.truncate(events, EmbedBuilder.DESCRIPTION_CONTENT_LIMIT));
        loadingMsg.edit(embed.build());
    } catch (IOException err) {
        loadingMsg.delete();
        Utils.handle("getting events", context, err);
    }
}
Also used : RateLimited(me.shadorc.shadbot.core.command.annotation.RateLimited) HelpBuilder(me.shadorc.shadbot.utils.embed.HelpBuilder) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) IOException(java.io.IOException) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) Collectors(java.util.stream.Collectors) StringUtils(me.shadorc.shadbot.utils.StringUtils) Command(me.shadorc.shadbot.core.command.annotation.Command) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) NetUtils(me.shadorc.shadbot.utils.NetUtils) Context(me.shadorc.shadbot.core.command.Context) Document(org.jsoup.nodes.Document) AbstractCommand(me.shadorc.shadbot.core.command.AbstractCommand) Jsoup(org.jsoup.Jsoup) Elements(org.jsoup.select.Elements) EmbedUtils(me.shadorc.shadbot.utils.embed.EmbedUtils) Utils(me.shadorc.shadbot.utils.Utils) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException) Document(org.jsoup.nodes.Document) Elements(org.jsoup.select.Elements)

Example 7 with LoadingMessage

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

the class CounterStrikeCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException {
    if (!context.hasArg()) {
        throw new MissingArgumentException();
    }
    LoadingMessage loadingMsg = new LoadingMessage("Loading CS:GO stats...", context.getChannel());
    loadingMsg.send();
    try {
        String arg = context.getArg();
        String steamid = null;
        // The user provided an URL that can contains a pseudo or an ID
        if (arg.contains("/")) {
            List<String> splittedURl = StringUtils.split(arg, "/");
            arg = splittedURl.get(splittedURl.size() - 1);
        }
        // The user directly provided the ID
        if (CastUtils.isPositiveLong(arg)) {
            steamid = arg;
        } else // The user provided a pseudo
        {
            String url = String.format("http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key=%s&vanityurl=%s", APIKeys.get(APIKey.STEAM_API_KEY), NetUtils.encode(arg));
            JSONObject mainObj = new JSONObject(NetUtils.getBody(url));
            JSONObject responseObj = mainObj.getJSONObject("response");
            steamid = responseObj.optString("steamid");
        }
        String url = String.format("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=%s&steamids=%s", APIKeys.get(APIKey.STEAM_API_KEY), steamid);
        JSONObject mainUserObj = new JSONObject(NetUtils.getBody(url));
        // Search users matching the steamID
        JSONArray players = mainUserObj.getJSONObject("response").getJSONArray("players");
        if (players.length() == 0) {
            loadingMsg.edit(Emoji.MAGNIFYING_GLASS + " User not found.");
            return;
        }
        JSONObject userObj = players.getJSONObject(0);
        /*
			 * CommunityVisibilityState
			 * 1: Private
			 * 2: FriendsOnly
			 * 3: Public
			 */
        if (userObj.getInt("communityvisibilitystate") != 3) {
            loadingMsg.edit(Emoji.ACCESS_DENIED + " This profile is private.");
            return;
        }
        url = String.format("http://api.steampowered.com/ISteamUserStats/GetUserStatsForGame/v0002/?appid=730&key=%s&steamid=%s", APIKeys.get(APIKey.STEAM_API_KEY), steamid);
        JSONObject mainStatsObj = new JSONObject(NetUtils.getBody(url));
        if (!mainStatsObj.has("playerstats") || !mainStatsObj.getJSONObject("playerstats").has("stats")) {
            loadingMsg.edit(Emoji.MAGNIFYING_GLASS + " This user doesn't play Counter-Strike: Global Offensive.");
            return;
        }
        JSONArray statsArray = mainStatsObj.getJSONObject("playerstats").getJSONArray("stats");
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().setLenient(true).withAuthorName("Counter-Strike: Global Offensive Stats").withAuthorIcon("http://www.icon100.com/up/2841/256/csgo.png").withAuthorUrl("http://steamcommunity.com/profiles/" + steamid).withThumbnail(userObj.getString("avatarfull")).appendDescription(String.format("Stats for **%s**", userObj.getString("personaname"))).appendField("Kills", Integer.toString(this.getValue(statsArray, "total_kills")), true).appendField("Deaths", Integer.toString(this.getValue(statsArray, "total_deaths")), true).appendField("Ratio", String.format("%.2f", (float) this.getValue(statsArray, "total_kills") / this.getValue(statsArray, "total_deaths")), true).appendField("Total wins", Integer.toString(this.getValue(statsArray, "total_wins")), true).appendField("Total MVP", Integer.toString(this.getValue(statsArray, "total_mvps")), true);
        loadingMsg.edit(embed.build());
    } catch (JSONException | IOException err) {
        loadingMsg.delete();
        Utils.handle("getting Counter-Strike: Global Offensive stats", context, err);
    }
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) JSONObject(org.json.JSONObject) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException)

Example 8 with LoadingMessage

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

the class DiabloCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException, IllegalCmdArgumentException {
    if (!context.hasArg()) {
        throw new MissingArgumentException();
    }
    List<String> splitArgs = StringUtils.split(context.getArg(), 2);
    if (splitArgs.size() != 2) {
        throw new MissingArgumentException();
    }
    Region region = Utils.getValueOrNull(Region.class, splitArgs.get(0));
    if (region == null) {
        throw new IllegalCmdArgumentException(String.format("`%s` is not a valid Region. %s", splitArgs.get(0), FormatUtils.formatOptions(Region.class)));
    }
    String battletag = splitArgs.get(1);
    if (!battletag.matches("(\\p{L}*)#[0-9]*")) {
        throw new IllegalCmdArgumentException(String.format("`%s` is not a valid Battletag.", splitArgs.get(1)));
    }
    battletag = battletag.replaceAll("#", "-");
    LoadingMessage loadingMsg = new LoadingMessage("Loading Diablo 3 stats...", context.getChannel());
    loadingMsg.send();
    try {
        String url = String.format("https://%s.api.battle.net/d3/profile/%s/?locale=en_GB&apikey=%s", region, NetUtils.encode(battletag), APIKeys.get(APIKey.BLIZZARD_API_KEY));
        JSONObject playerObj = new JSONObject(NetUtils.getBody(url));
        if (playerObj.has("code") && playerObj.getString("code").equals("NOTFOUND")) {
            loadingMsg.edit(Emoji.MAGNIFYING_GLASS + " This user doesn't play Diablo 3 or doesn't exist.");
            return;
        }
        TreeMap<Double, String> heroesMap = new TreeMap<>(Collections.reverseOrder());
        JSONArray heroesArray = playerObj.getJSONArray("heroes");
        for (int i = 0; i < heroesArray.length(); i++) {
            JSONObject heroObj = heroesArray.getJSONObject(i);
            String name = heroObj.getString("name");
            String heroClass = StringUtils.capitalize(heroObj.getString("class").replace("-", " "));
            url = String.format("https://%s.api.battle.net/d3/profile/%s/hero/%d?locale=en_GB&apikey=%s", region, NetUtils.encode(battletag), heroObj.getLong("id"), APIKeys.get(APIKey.BLIZZARD_API_KEY));
            JSONObject statsHeroObj = new JSONObject(NetUtils.getBody(url));
            Double dps = statsHeroObj.has("code") ? Double.NaN : statsHeroObj.getJSONObject("stats").getDouble("damage");
            heroesMap.put(dps, String.format("**%s** (*%s*)", name, heroClass));
        }
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().setLenient(true).withAuthorName("Diablo 3 Stats").withThumbnail("http://osx.wdfiles.com/local--files/icon:d3/D3.png").appendDescription(String.format("Stats for **%s** (Guild: **%s**)" + "%n%nParangon level: **%s** (*Normal*) / **%s** (*Hardcore*)" + "%nSeason Parangon level: **%s** (*Normal*) / **%s** (*Hardcore*)", playerObj.getString("battleTag"), playerObj.getString("guildName"), playerObj.getInt("paragonLevel"), playerObj.getInt("paragonLevelSeasonHardcore"), playerObj.getInt("paragonLevelSeason"), playerObj.getInt("paragonLevelSeasonHardcore"))).appendField("Heroes", FormatUtils.format(heroesMap.values().stream(), Object::toString, "\n"), true).appendField("Damage", FormatUtils.format(heroesMap.keySet().stream(), dps -> String.format("%s DPS", FormatUtils.formatNum(dps)), "\n"), true);
        loadingMsg.edit(embed.build());
    } catch (FileNotFoundException err) {
        loadingMsg.delete();
        BotUtils.sendMessage(Emoji.MAGNIFYING_GLASS + " This user doesn't play Diablo 3 or doesn't exist.", context.getChannel());
    } catch (JSONException | IOException err) {
        loadingMsg.delete();
        Utils.handle("getting Diablo 3 stats", context, err);
    }
}
Also used : HelpBuilder(me.shadorc.shadbot.utils.embed.HelpBuilder) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) BotUtils(me.shadorc.shadbot.utils.BotUtils) 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) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) Utils(me.shadorc.shadbot.utils.Utils) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) RateLimited(me.shadorc.shadbot.core.command.annotation.RateLimited) APIKeys(me.shadorc.shadbot.data.APIKeys) IOException(java.io.IOException) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) FormatUtils(me.shadorc.shadbot.utils.FormatUtils) FileNotFoundException(java.io.FileNotFoundException) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) List(java.util.List) NetUtils(me.shadorc.shadbot.utils.NetUtils) TreeMap(java.util.TreeMap) Context(me.shadorc.shadbot.core.command.Context) AbstractCommand(me.shadorc.shadbot.core.command.AbstractCommand) Emoji(me.shadorc.shadbot.utils.object.Emoji) APIKey(me.shadorc.shadbot.data.APIKeys.APIKey) EmbedUtils(me.shadorc.shadbot.utils.embed.EmbedUtils) Collections(java.util.Collections) JSONArray(org.json.JSONArray) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) JSONArray(org.json.JSONArray) FileNotFoundException(java.io.FileNotFoundException) JSONException(org.json.JSONException) IOException(java.io.IOException) TreeMap(java.util.TreeMap) IllegalCmdArgumentException(me.shadorc.shadbot.exception.IllegalCmdArgumentException) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) JSONObject(org.json.JSONObject) JSONObject(org.json.JSONObject) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage)

Example 9 with LoadingMessage

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

the class OverwatchCmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException, IllegalCmdArgumentException {
    List<String> splitArgs = StringUtils.split(context.getArg());
    if (!Utils.isInRange(splitArgs.size(), 1, 3)) {
        throw new MissingArgumentException();
    }
    LoadingMessage loadingMsg = new LoadingMessage("Loading Overwatch profile...", context.getChannel());
    try {
        OverwatchPlayer player;
        String username = null;
        Platform platform = null;
        if (splitArgs.size() == 1) {
            username = splitArgs.get(0);
            loadingMsg.send();
            player = new OverwatchPlayer(username);
        } else {
            platform = this.getPlatform(splitArgs.get(0));
            username = splitArgs.get(1);
            loadingMsg.send();
            player = new OverwatchPlayer(username, platform);
        }
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().setLenient(true).withAuthorName("Overwatch Stats").withAuthorIcon("http://vignette4.wikia.nocookie.net/overwatch/images/b/bd/Overwatch_line_art_logo_symbol-only.png").withAuthorUrl(player.getProfileURL()).withThumbnail(player.getIconUrl()).appendDescription(String.format("Stats for user **%s**", player.getName())).appendField("Level", Integer.toString(player.getLevel()), true).appendField("Competitive rank", Integer.toString(player.getRank()), true).appendField("Wins", Integer.toString(player.getWins()), true).appendField("Game time", player.getTimePlayed(), true).appendField("Top hero (Time played)", this.getTopThreeHeroes(player.getList(TopHeroesStats.TIME_PLAYED)), true).appendField("Top hero (Eliminations per life)", this.getTopThreeHeroes(player.getList(TopHeroesStats.ELIMINATIONS_PER_LIFE)), true);
        loadingMsg.edit(embed.build());
    } catch (OverwatchException err) {
        loadingMsg.edit(Emoji.MAGNIFYING_GLASS + " " + err.getMessage());
    } catch (IOException err) {
        loadingMsg.delete();
        Utils.handle("getting information from Overwatch profile", context, err);
    }
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) Platform(net.shadorc.overwatch4j.enums.Platform) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException) OverwatchException(net.shadorc.overwatch4j.exception.OverwatchException) OverwatchPlayer(net.shadorc.overwatch4j.OverwatchPlayer)

Example 10 with LoadingMessage

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

the class Rule34Cmd method execute.

@Override
public void execute(Context context) throws MissingArgumentException {
    if (!context.getChannel().isNSFW()) {
        BotUtils.sendMessage(TextUtils.mustBeNSFW(context.getPrefix()), context.getChannel());
        return;
    }
    if (!context.hasArg()) {
        throw new MissingArgumentException();
    }
    LoadingMessage loadingMsg = new LoadingMessage("Loading image...", context.getChannel());
    loadingMsg.send();
    try {
        String url = String.format("https://rule34.xxx/index.php?page=dapi&s=post&q=index&tags=%s", NetUtils.encode(context.getArg().replace(" ", "_")));
        JSONObject mainObj = XML.toJSONObject(NetUtils.getBody(url));
        JSONObject postsObj = mainObj.getJSONObject("posts");
        if (postsObj.getInt("count") == 0) {
            loadingMsg.edit(TextUtils.noResult(context.getArg()));
            return;
        }
        JSONObject postObj;
        if (postsObj.get("post") instanceof JSONArray) {
            JSONArray postsArray = postsObj.getJSONArray("post");
            postObj = postsArray.getJSONObject(ThreadLocalRandom.current().nextInt(postsArray.length()));
        } else {
            postObj = postsObj.getJSONObject("post");
        }
        List<String> tags = StringUtils.split(postObj.getString("tags"), " ");
        if (postObj.getBoolean("has_children") || tags.stream().anyMatch(tag -> tag.contains("loli") || tag.contains("shota"))) {
            loadingMsg.edit(Emoji.WARNING + " Sorry, I don't display images containing children or tagged with `loli` or `shota`.");
            return;
        }
        String formattedtags = StringUtils.truncate(FormatUtils.format(tags, tag -> String.format("`%s`", tag.toString()), " "), MAX_TAGS_LENGTH);
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().setLenient(true).withAuthorName("Rule34 (Search: " + context.getArg() + ")").withAuthorUrl(postObj.getString("file_url")).withThumbnail("http://rule34.paheal.net/themes/rule34v2/rule34_logo_top.png").appendField("Resolution", String.format("%dx%s", postObj.getInt("width"), postObj.getInt("height")), false).appendField("Tags", formattedtags, false).withImage(postObj.getString("file_url")).withFooterText("If there is no preview, click on the title to see the media (probably a video)");
        String source = postObj.get("source").toString();
        if (!source.isEmpty()) {
            embed.withDescription(String.format("%n[**Source**](%s)", source));
        }
        loadingMsg.edit(embed.build());
    } catch (JSONException | IOException err) {
        loadingMsg.delete();
        Utils.handle("getting an image from Rule34", context, err);
    }
}
Also used : HelpBuilder(me.shadorc.shadbot.utils.embed.HelpBuilder) CommandCategory(me.shadorc.shadbot.core.command.CommandCategory) BotUtils(me.shadorc.shadbot.utils.BotUtils) 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) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) XML(org.json.XML) TextUtils(me.shadorc.shadbot.utils.TextUtils) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Utils(me.shadorc.shadbot.utils.Utils) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) RateLimited(me.shadorc.shadbot.core.command.annotation.RateLimited) IOException(java.io.IOException) EmbedObject(sx.blah.discord.api.internal.json.objects.EmbedObject) FormatUtils(me.shadorc.shadbot.utils.FormatUtils) List(java.util.List) NetUtils(me.shadorc.shadbot.utils.NetUtils) Context(me.shadorc.shadbot.core.command.Context) AbstractCommand(me.shadorc.shadbot.core.command.AbstractCommand) Emoji(me.shadorc.shadbot.utils.object.Emoji) EmbedUtils(me.shadorc.shadbot.utils.embed.EmbedUtils) JSONArray(org.json.JSONArray) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) JSONObject(org.json.JSONObject) MissingArgumentException(me.shadorc.shadbot.exception.MissingArgumentException) JSONArray(org.json.JSONArray) JSONException(org.json.JSONException) LoadingMessage(me.shadorc.shadbot.utils.object.LoadingMessage) IOException(java.io.IOException)

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