use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class SteamGameCache method initiateCache.
public void initiateCache() {
this.future = this.executor.scheduleAtFixedRate(() -> {
Request request = new Request.Builder().url("https://api.steampowered.com/ISteamApps/GetAppList/v0002/?key=" + this.bot.getConfig().getSteam() + "&format=json").build();
this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document json = Document.parse(response.body().string());
this.games = json.getEmbedded(List.of("applist", "apps"), Collections.emptyList());
});
}, 0, 15, TimeUnit.MINUTES);
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class YouTubeNotificationCommand method add.
@Command(value = "add", description = "Add a youtube notification to be posted to a specific channel when the user uploads")
@CommandId(158)
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
@Examples({ "youtube notification add videos mrbeast", "youtube notification add mrbeast", "youtube notification add #videos pewdiepie" })
public void add(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) TextChannel channel, @Argument(value = "youtube channel", endless = true) String channelQuery) {
if (!event.getBot().getConnectionHandler().isReady()) {
event.replyFailure("The bot has to be fully started to use this command, try again later").queue();
return;
}
TextChannel effectiveChannel = channel == null ? event.getTextChannel() : channel;
boolean id = this.id.matcher(channelQuery).matches();
boolean search;
String queryName, query;
Matcher matcher = this.url.matcher(channelQuery);
if (!id && matcher.matches()) {
String path = matcher.group(1);
search = false;
queryName = path == null || path.equals("user") ? "forUsername" : "id";
query = matcher.group(2);
} else {
search = !id;
queryName = id ? "id" : "q";
query = channelQuery;
}
Request channelRequest = new Request.Builder().url("https://www.googleapis.com/youtube/v3/" + (search ? "search" : "channels") + "?key=" + event.getConfig().getYouTube() + "&" + queryName + "=" + URLEncoder.encode(query, StandardCharsets.UTF_8) + "&part=snippet&type=channel&maxResults=1").build();
event.getHttpClient().newCall(channelRequest).enqueue((HttpCallback) channelResponse -> {
Document json = Document.parse(channelResponse.body().string());
List<Document> items = json.getList("items", Document.class, Collections.emptyList());
if (items.isEmpty()) {
event.replyFailure("I could not find that youtube channel").queue();
return;
}
Document item = items.get(0);
String channelId = search ? item.getEmbedded(List.of("id", "channelId"), String.class) : item.getString("id");
Document notificationData = new Document("uploaderId", channelId).append("channelId", effectiveChannel.getIdLong()).append("guildId", event.getGuild().getIdLong());
if (!event.getBot().getYouTubeManager().hasExecutor(channelId)) {
RequestBody body = new MultipartBody.Builder().addFormDataPart("hub.mode", "subscribe").addFormDataPart("hub.topic", "https://www.youtube.com/xml/feeds/videos.xml?channel_id=" + channelId).addFormDataPart("hub.callback", event.getConfig().getBaseUrl() + "/api/youtube").addFormDataPart("hub.verify", "sync").addFormDataPart("hub.verify_token", event.getConfig().getYouTube()).setType(MultipartBody.FORM).build();
Request request = new Request.Builder().url("https://pubsubhubbub.appspot.com/subscribe").post(body).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
if (response.isSuccessful()) {
event.getMongo().insertYouTubeNotification(notificationData).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
});
} else {
event.replyFailure("Oops something went wrong there, try again. If this repeats report this to my developer (Message: " + response.body().string() + ")").queue();
}
});
} else {
event.getMongo().insertYouTubeNotification(notificationData).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof MongoWriteException && ((MongoWriteException) cause).getError().getCategory() == ErrorCategory.DUPLICATE_KEY) {
event.replyFailure("You already have a notification setup for that youtube channel in " + effectiveChannel.getAsMention()).queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.replyFormat("Notifications will now be sent in %s when **%s** uploads with id `%s` %s", effectiveChannel.getAsMention(), item.getEmbedded(List.of("snippet", "title"), String.class), result.getInsertedId().asObjectId().getValue().toHexString(), event.getConfig().getSuccessEmote()).queue();
});
}
});
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class SteamCommand method game.
@Command(value = "game", description = "View information about a game on steam")
@CommandId(34)
@Examples({ "steam game Grand Theft Auto", "steam game 1293830", "steam game https://store.steampowered.com/app/1293830/Forza_Horizon_4/" })
@Cooldown(5)
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void game(Sx4CommandEvent event, @Argument(value = "query", endless = true, nullDefault = true) String query, @Option(value = "random", description = "Gets a random game") boolean random) {
if (query == null && !random) {
event.replyHelp().queue();
return;
}
SteamGameCache cache = event.getBot().getSteamGameCache();
if (cache.getGames().isEmpty()) {
event.replyFailure("The steam cache is currently empty, try again").queue();
return;
}
Matcher urlMatcher;
List<Document> games;
if (query == null) {
List<Document> cacheGames = cache.getGames();
games = List.of(cacheGames.get(event.getRandom().nextInt(cacheGames.size())));
} else if (NumberUtility.isNumberUnsigned(query)) {
games = List.of(new Document("appid", Integer.parseInt(query)));
} else if ((urlMatcher = this.gamePattern.matcher(query)).matches()) {
games = List.of(new Document("appid", Integer.parseInt(urlMatcher.group(1))));
} else {
games = cache.getGames(query);
if (games.isEmpty()) {
event.replyFailure("I could not find any games with that query").queue();
return;
}
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), games).setAuthor("Steam Search", null, "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png").setIncreasedIndex(true).setAutoSelect(true).setTimeout(60).setDisplayFunction(game -> game.getString("name"));
paged.onSelect(select -> {
Document game = select.getSelected();
int appId = game.getInteger("appid");
Request request = new Request.Builder().url("https://store.steampowered.com/api/appdetails?cc=gb&appids=" + appId).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document json = Document.parse(response.body().string()).get(String.valueOf(appId), Document.class);
if (!json.getBoolean("success")) {
event.replyFailure("Steam failed to get data for that game").queue();
return;
}
List<MessageEmbed> embeds = new ArrayList<>();
Document gameInfo = json.get("data", Document.class);
String description = Jsoup.parse(gameInfo.getString("short_description")).text();
String price;
if (gameInfo.containsKey("price_overview")) {
Document priceOverview = gameInfo.get("price_overview", Document.class);
double initialPrice = priceOverview.getInteger("initial") / 100D, finalPrice = priceOverview.getInteger("final") / 100D;
price = initialPrice == finalPrice ? String.format("£%,.2f", finalPrice) : String.format("~~£%,.2f~~ £%,.2f (-%d%%)", initialPrice, finalPrice, priceOverview.getInteger("discount_percent"));
} else {
price = gameInfo.getBoolean("is_free") ? "Free" : "Unknown";
}
EmbedBuilder embed = new EmbedBuilder();
embed.setDescription(description);
embed.setTitle(gameInfo.getString("name"), "https://store.steampowered.com/app/" + appId);
embed.setAuthor("Steam", "https://steamcommunity.com", "https://upload.wikimedia.org/wikipedia/commons/thumb/8/83/Steam_icon_logo.svg/2000px-Steam_icon_logo.svg.png");
embed.setImage(gameInfo.getString("header_image"));
embed.addField("Price", price, true);
embed.setFooter("Developed by " + (gameInfo.containsKey("developers") ? String.join(", ", gameInfo.getList("developers", String.class)) : "Unknown"), null);
Document releaseDate = gameInfo.get("release_date", Document.class);
String date = releaseDate.getString("date");
embed.addField("Release Date", String.format("%s%s", date.isBlank() ? "Unknown" : date, releaseDate.getBoolean("coming_soon") ? " (Coming Soon)" : ""), true);
Object age = gameInfo.get("required_age");
embed.addField("Required Age", age instanceof Integer ? ((int) age) == 0 ? "No Age Restriction" : String.valueOf((int) age) : (String) age, true);
embed.addField("Recommendations", String.format("%,d", gameInfo.getEmbedded(List.of("recommendations", "total"), 0)), true);
embed.addField("Supported Languages", gameInfo.containsKey("supported_languages") ? Jsoup.parse(gameInfo.getString("supported_languages")).text() : "Unknown", true);
List<Document> genres = gameInfo.getList("genres", Document.class);
embed.addField("Genres", genres == null ? "None" : genres.stream().map(genre -> genre.getString("description")).collect(Collectors.joining("\n")), true);
embeds.add(embed.build());
gameInfo.getList("screenshots", Document.class).stream().map(d -> d.getString("path_thumbnail")).limit(3).forEach(thumbnail -> {
embeds.add(new MessageEmbed("https://store.steampowered.com/app/" + appId, null, null, EmbedType.RICH, null, Role.DEFAULT_COLOR_RAW, null, null, null, null, null, new MessageEmbed.ImageInfo(thumbnail, null, 0, 0), List.of()));
});
event.getChannel().sendMessageEmbeds(embeds).queue();
});
});
paged.onTimeout(() -> event.reply("Response timed out :stopwatch:").queue());
paged.execute(event);
}
use of com.sx4.bot.http.HttpCallback 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);
}
use of com.sx4.bot.http.HttpCallback 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());
});
}
Aggregations