use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class CSGOSkinCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "skin name", endless = true) String query, @Option(value = "sort", description = "You can sort by `price`, `age`, `deal`, `popularity`, `wear or `discount`") Sort sort, @Option(value = "reverse", description = "Reverse the order of the sorting") boolean reverse, @Option(value = "wear", description = "What wear you would like to filter by, options are `fn`, `mw`, `ft`, `ww` and `bs`") Wear wear, @Option(value = "phase", description = "Filter by phase of a knife") @Lowercase String phase, @Option(value = "currency", description = "What currency to use for the prices of items") @Uppercase @DefaultString("GBP") String currency) {
SkinPortManager manager = event.getBot().getSkinPortManager();
String cookie = manager.getCSRFCookie();
double rate = manager.getCurrencyRate(currency);
if (rate == -1D) {
event.replyFailure("SkinPort does not support that currency").queue();
return;
}
FormBody body = new FormBody.Builder().add("prefix", query).add("_csrf", manager.getCSRFToken()).build();
Request suggestionRequest = new Request.Builder().url("https://skinport.com/api/suggestions/730").post(body).addHeader("Content-Type", "application/x-www-form-urlencoded").addHeader("Cookie", cookie).build();
event.getHttpClient().newCall(suggestionRequest).enqueue((HttpCallback) suggestionResponse -> {
Document data = Document.parse(suggestionResponse.body().string());
List<Document> variants = data.getList("suggestions", Document.class);
if (variants.isEmpty()) {
event.replyFailure("I could not find any skins from that query").queue();
return;
}
PagedResult<Document> suggestions = new PagedResult<>(event.getBot(), variants).setAuthor("SkinPort", null, "https://skinport.com/static/favicon-32x32.png").setDisplayFunction(suggestion -> {
String type = suggestion.getString("type");
return (type == null ? "" : type + " | ") + suggestion.getString("item");
}).setIndexed(true).setAutoSelect(true);
suggestions.onSelect(select -> {
Document selected = select.getSelected();
String type = selected.getString("type");
StringBuilder url = new StringBuilder("https://skinport.com/api/browse/730?cat=" + URLEncoder.encode(selected.getString("category"), StandardCharsets.UTF_8) + (type != null ? "&type=" + URLEncoder.encode(type, StandardCharsets.UTF_8) : "") + "&item=" + URLEncoder.encode(selected.getString("item"), StandardCharsets.UTF_8));
if (wear != null) {
url.append("&exterior=").append(wear.getId());
}
if (sort != null) {
url.append("&sort=").append(sort.getIdentifier()).append("&order=").append(reverse ? "desc" : "asc");
}
if (phase != null) {
int phaseId = this.phases.getOrDefault(phase, -1);
if (phaseId != -1) {
url.append("&phase=").append(phaseId);
}
}
Request request = new Request.Builder().url(url.toString()).addHeader("Cookie", cookie).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document skinData = Document.parse(response.body().string());
List<Document> items = skinData.getList("items", Document.class);
if (items.isEmpty()) {
event.replyFailure("There are no skins listed with those filters").queue();
return;
}
PagedResult<Document> skins = new PagedResult<>(event.getBot(), items).setPerPage(1).setSelect().setCustomFunction(page -> {
List<MessageEmbed> embeds = new ArrayList<>();
EmbedBuilder embed = new EmbedBuilder();
embed.setFooter("Skin " + page.getPage() + "/" + page.getMaxPage());
page.forEach((d, index) -> {
double steamPrice = (d.getInteger("suggestedPrice") / 100D) * rate;
double price = (d.getInteger("salePrice") / 100D) * rate;
double increase = steamPrice - price;
embed.setTitle(d.getString("marketName"), "https://skinport.com/item/" + d.getString("url") + "/" + d.getInteger("saleId"));
embed.setImage("https://community.cloudflare.steamstatic.com/economy/image/" + d.getString("image"));
embed.addField("Price", String.format("~~%,.2f %s~~ %,.2f %2$s (%s%.2f%%)", steamPrice, currency, price, increase > 0 ? "-" : "+", Math.abs((increase / steamPrice) * 100D)), true);
String exterior = d.getString("exterior");
if (exterior != null) {
embed.addField("Wear", exterior, true);
embed.addField("Float", String.format("%.3f", d.get("wear", Number.class).doubleValue()), true);
}
String lock = d.getString("lock");
embed.addField("Trade Locked", lock == null ? "No" : this.formatter.parse(Duration.between(OffsetDateTime.now(ZoneOffset.UTC), OffsetDateTime.parse(lock))), true);
embeds.add(embed.build());
if (d.getBoolean("canHaveScreenshots")) {
embed.setImage("https://cdn.skinport.com/images/screenshots/" + d.getInteger("assetId") + "/backside_512x384.png");
embeds.add(embed.build());
embed.setImage("https://cdn.skinport.com/images/screenshots/" + d.getInteger("assetId") + "/playside_512x384.png");
embeds.add(embed.build());
}
});
return new MessageBuilder().setEmbeds(embeds);
});
skins.execute(event);
});
});
suggestions.execute(event);
});
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class ConvertCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "amount") @DefaultNumber(1) double amount, @Argument(value = "currency from") @Uppercase String from, @Argument(value = "currency to") @Uppercase String to) {
if (to.equals(from)) {
event.replyFormat("**%,.2f** %s \\➡ **%,.2f** %s", amount, from, amount, to).queue();
return;
}
Request request = new Request.Builder().url(String.format("https://free.currconv.com/api/v7/convert?q=%s_%s&apiKey=%s&compact=y", from, to, event.getConfig().getCurrencyConvertor())).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
if (!response.isSuccessful()) {
event.replyFailure("Failed to convert, try again if this repeats it's likely due to the API being down").queue();
return;
}
Document json = Document.parse(response.body().string());
Document result = json.get(from + "_" + to, Document.class);
if (result == null) {
event.replyFailure("I could not find one or both of those currencies").queue();
return;
}
event.replyFormat("**%,.2f** %s \\➡ **%,.2f** %s", amount, from, amount * result.getDouble("val"), to).queue();
});
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class DictionaryCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) String query) {
Request request = new Request.Builder().url(event.getConfig().getSearchWebserverUrl("dictionary") + "?q=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document document = Document.parse(response.body().string());
if (!response.isSuccessful()) {
StringBuilder builder = new StringBuilder("Command failed with status " + response.code());
if (document.containsKey("message")) {
builder.append(" with message `").append(document.getString("message")).append("`");
}
event.replyFailure(builder.toString()).queue();
return;
}
List<Document> definitions = document.getList("definitions", Document.class);
if (definitions.isEmpty()) {
event.replyFailure("I could not find a definition for that word").queue();
return;
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), definitions).setPerPage(1).setCustomFunction(page -> {
EmbedBuilder embed = new EmbedBuilder();
embed.setAuthor(StringUtility.title(query) + " (" + document.getString("type") + ")", document.getString("url"), null);
embed.setTitle("Page " + page.getPage() + "/" + page.getMaxPage());
embed.setFooter(PagedResult.DEFAULT_FOOTER_TEXT);
page.forEach((data, index) -> {
StringBuilder definition = new StringBuilder();
for (Document node : data.getList("nodes", Document.class)) {
if (node.containsKey("url")) {
definition.append("[").append(node.getString("text")).append("](").append(node.getString("url")).append(")");
} else {
definition.append(node.getString("text"));
}
}
List<String> examples = data.getList("examples", String.class);
embed.addField("Definition", definition + (examples.isEmpty() ? "" : "\n\n*" + String.join("*\n*", examples.subList(0, Math.min(3, examples.size()))) + "*"), false);
});
if (document.containsKey("pronunciation")) {
embed.addField("Pronunciation", String.format("[Listen Here](%s)", document.getString("pronunciation")), false);
}
return new MessageBuilder().setEmbeds(embed.build());
});
paged.execute(event);
});
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class CannyCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "image url", endless = true, acceptEmpty = true) @ImageUrl String imageUrl) {
Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("canny")).addQuery("image", imageUrl).build(event.getConfig().getImageWebserver());
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
}
use of com.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class ChristmasCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "image url", endless = true, acceptEmpty = true) @ImageUrl String imageUrl) {
Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("christmas")).addQuery("image", imageUrl).build(event.getConfig().getImageWebserver());
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
}
Aggregations