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());
}
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();
}
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);
}
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);
}
}
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);
}
}
Aggregations