Search in sources :

Example 86 with EmbedBuilder

use of sx.blah.discord.util.EmbedBuilder in project Shadbot by Shadorc.

the class AudioLoadResultListener method playlistLoaded.

@Override
public void playlistLoaded(AudioPlaylist playlist) {
    List<AudioTrack> tracks = playlist.getTracks();
    // SoundCloud returns an empty playlist when it has not found any results
    if (tracks.isEmpty()) {
        this.onNoMatches();
        return;
    }
    if (identifier.startsWith(YT_SEARCH) || identifier.startsWith(SC_SEARCH)) {
        guildMusic.setDj(userDj);
        guildMusic.setWaiting(true);
        String choices = FormatUtils.numberedList(5, tracks.size(), count -> String.format("\t**%d.** %s", count, FormatUtils.formatTrackName(tracks.get(count - 1).getInfo())));
        EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName("Music results").withAuthorIcon(guildMusic.getDj().getAvatarURL()).withThumbnail("http://icons.iconarchive.com/icons/dtafalonso/yosemite-flat/512/Music-icon.png").appendDescription("**Select a music by typing the corresponding number.**" + "\nYou can choose several musics by separating them with a comma." + "\nExample: 1,3,4" + "\n\n" + choices).withFooterText(String.format("Use %scancel to cancel the selection (Automatically canceled in %ds).", Database.getDBGuild(guildMusic.getChannel().getGuild()).getPrefix(), CHOICE_DURATION));
        BotUtils.sendMessage(embed.build(), guildMusic.getChannel());
        stopWaitingTask = Shadbot.getScheduler().schedule(() -> this.stopWaiting(), CHOICE_DURATION, TimeUnit.SECONDS);
        resultsTracks = new ArrayList<>(tracks);
        MessageManager.addListener(guildMusic.getChannel(), this);
        return;
    }
    guildMusic.joinVoiceChannel(userVoiceChannel);
    int musicsAdded = 0;
    for (AudioTrack track : tracks) {
        guildMusic.getScheduler().startOrQueue(track, putFirst);
        musicsAdded++;
        if (guildMusic.getScheduler().getPlaylist().size() >= Config.MAX_PLAYLIST_SIZE - 1 && !PremiumManager.isPremium(guildMusic.getChannel().getGuild(), userDj)) {
            BotUtils.sendMessage(TextUtils.PLAYLIST_LIMIT_REACHED, guildMusic.getChannel());
            break;
        }
    }
    BotUtils.sendMessage(String.format(Emoji.MUSICAL_NOTE + " %d musics have been added to the playlist.", musicsAdded), guildMusic.getChannel());
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack)

Example 87 with EmbedBuilder

use of sx.blah.discord.util.EmbedBuilder in project Shadbot by Shadorc.

the class LogBuilder method build.

public EmbedObject build() {
    EmbedBuilder embed = EmbedUtils.getDefaultEmbed().setLenient(true).withAuthorName(String.format("%s (Version: %s)", StringUtils.capitalize(type.toString()), Shadbot.VERSION)).withDescription(message);
    switch(type) {
        case ERROR:
            embed.withColor(Color.RED);
            break;
        case WARN:
            embed.withColor(Color.ORANGE);
            break;
        case INFO:
            embed.withColor(Color.GREEN);
            break;
    }
    if (err != null) {
        embed.appendField("Error type", err.getClass().getSimpleName(), false);
        embed.appendField("Error message", err.getMessage(), false);
    }
    if (input != null) {
        embed.appendField("Input", input, false);
    }
    return embed.build();
}
Also used : EmbedBuilder(sx.blah.discord.util.EmbedBuilder)

Example 88 with EmbedBuilder

use of sx.blah.discord.util.EmbedBuilder in project Shadbot by Shadorc.

the class TriviaManager method start.

// Trivia API doc : https://opentdb.com/api_config.php
@Override
public void start() throws JSONException, IOException, ParseException {
    String url = String.format("https://opentdb.com/api.php?amount=1&category=%s", categoryID == null ? "" : categoryID.toString());
    String jsonStr = NetUtils.getBody(url);
    if (jsonStr.isEmpty()) {
        throw new ParseException("Body is empty.");
    }
    JSONObject resultObj = new JSONObject(jsonStr).getJSONArray("results").getJSONObject(0);
    String questionType = resultObj.getString("type");
    correctAnswer = Jsoup.parse(resultObj.getString("correct_answer")).text();
    if ("multiple".equals(questionType)) {
        answers = Utils.toList(resultObj.getJSONArray("incorrect_answers"), String.class);
        answers.add(ThreadLocalRandom.current().nextInt(answers.size()), correctAnswer);
    } else {
        answers = List.of("True", "False");
    }
    String description = String.format("**%s**%n%s", Jsoup.parse(resultObj.getString("question")).text(), FormatUtils.numberedList(answers.size(), answers.size(), count -> "\t**" + count + "**. " + Jsoup.parse(answers.get(count - 1)).text()));
    EmbedBuilder embed = EmbedUtils.getDefaultEmbed().withAuthorName("Trivia").appendDescription(description).appendField("Category", String.format("`%s`", resultObj.getString("category")), true).appendField("Type", String.format("`%s`", questionType), true).appendField("Difficulty", String.format("`%s`", resultObj.getString("difficulty")), true).withFooterText(String.format("You have %d seconds to answer.", LIMITED_TIME));
    BotUtils.sendMessage(embed.build(), this.getChannel());
    MessageManager.addListener(this.getChannel(), this);
    startTime = System.currentTimeMillis();
    this.schedule(() -> {
        BotUtils.sendMessage(String.format(Emoji.HOURGLASS + " Time elapsed, the correct answer was **%s**.", correctAnswer), this.getChannel());
        this.stop();
    }, LIMITED_TIME, TimeUnit.SECONDS);
}
Also used : MoneyEnum(me.shadorc.shadbot.data.stats.MoneyStatsManager.MoneyEnum) BotUtils(me.shadorc.shadbot.utils.BotUtils) TimeUtils(me.shadorc.shadbot.utils.TimeUtils) IMessage(sx.blah.discord.handle.obj.IMessage) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) JSONException(org.json.JSONException) IUser(sx.blah.discord.handle.obj.IUser) JSONObject(org.json.JSONObject) AbstractGameManager(me.shadorc.shadbot.core.game.AbstractGameManager) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Utils(me.shadorc.shadbot.utils.Utils) ParseException(org.apache.http.ParseException) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) IOException(java.io.IOException) FormatUtils(me.shadorc.shadbot.utils.FormatUtils) MessageListener(me.shadorc.shadbot.message.MessageListener) TimeUnit(java.util.concurrent.TimeUnit) CastUtils(me.shadorc.shadbot.utils.CastUtils) MoneyStatsManager(me.shadorc.shadbot.data.stats.MoneyStatsManager) List(java.util.List) NetUtils(me.shadorc.shadbot.utils.NetUtils) AbstractCommand(me.shadorc.shadbot.core.command.AbstractCommand) Database(me.shadorc.shadbot.data.db.Database) IChannel(sx.blah.discord.handle.obj.IChannel) Emoji(me.shadorc.shadbot.utils.object.Emoji) Jsoup(org.jsoup.Jsoup) EmbedUtils(me.shadorc.shadbot.utils.embed.EmbedUtils) MessageManager(me.shadorc.shadbot.message.MessageManager) EmbedBuilder(sx.blah.discord.util.EmbedBuilder) JSONObject(org.json.JSONObject) ParseException(org.apache.http.ParseException)

Example 89 with EmbedBuilder

use of sx.blah.discord.util.EmbedBuilder 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 90 with EmbedBuilder

use of sx.blah.discord.util.EmbedBuilder 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)

Aggregations

EmbedBuilder (sx.blah.discord.util.EmbedBuilder)103 IOException (java.io.IOException)19 Random (java.util.Random)17 IUser (sx.blah.discord.handle.obj.IUser)14 MissingArgumentException (me.shadorc.shadbot.exception.MissingArgumentException)13 LoadingMessage (me.shadorc.shadbot.utils.object.LoadingMessage)13 EmbedObject (sx.blah.discord.api.internal.json.objects.EmbedObject)12 JSONObject (org.json.JSONObject)11 IMessage (sx.blah.discord.handle.obj.IMessage)10 List (java.util.List)9 AbstractCommand (me.shadorc.shadbot.core.command.AbstractCommand)9 EmbedUtils (me.shadorc.shadbot.utils.embed.EmbedUtils)9 JSONException (org.json.JSONException)9 EventColor (com.cloudcraftgaming.discal.api.enums.event.EventColor)8 Utils (me.shadorc.shadbot.utils.Utils)8 IChannel (sx.blah.discord.handle.obj.IChannel)8 EventData (com.cloudcraftgaming.discal.api.object.event.EventData)7 FormatUtils (me.shadorc.shadbot.utils.FormatUtils)7 File (java.io.File)6 CommandCategory (me.shadorc.shadbot.core.command.CommandCategory)6