use of com.sx4.bot.annotations.command.Examples in project Sx4 by sx4-discord-bot.
the class SteamCommand method inventory.
@Command(value = "inventory", description = "Look at your steam inventory for a game")
@CommandId(505)
@Examples({ "steam inventory Intruder", "steam inventory Counter-Strike" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void inventory(Sx4CommandEvent event, @Argument(value = "game", endless = true) String query) {
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 (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> gamePaged = 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"));
gamePaged.onSelect(gameSelect -> {
int game = gameSelect.getSelected().getInteger("appid");
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;
}
List<Document> profiles = connections.stream().map(data -> data.append("url", "https://steamcommunity.com/profiles/" + data.getLong("id") + "/")).collect(Collectors.toList());
PagedResult<Document> profilePaged = 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") + ")");
profilePaged.onSelect(profileSelect -> {
long id = profileSelect.getSelected().getLong("id");
Request request = new Request.Builder().url("https://steamcommunity.com/inventory/" + id + "/" + game + "/2?l=english&count=5000").build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
String body = response.body().string();
if (body.equals("null")) {
event.replyFailure("Your inventory is set to private").queue();
return;
}
Document json = Document.parse(body);
if (json.containsKey("error")) {
event.replyFailure("That game does not have inventory items").queue();
return;
}
int totalCount = json.getInteger("total_inventory_count");
if (totalCount == 0) {
event.replyFailure("You do not have any inventory items for this game").queue();
return;
}
List<Document> items = json.getList("descriptions", Document.class);
List<Document> assets = json.getList("assets", Document.class);
PagedResult<Document> itemPaged = new PagedResult<>(event.getBot(), items).setSelect().setPerPage(1).cachePages(true).setAsyncFunction((page, message) -> {
EmbedBuilder embed = new EmbedBuilder();
embed.setFooter("Item " + page.getPage() + "/" + page.getMaxPage());
page.forEach((item, index) -> {
Document asset = assets.stream().filter(d -> d.getString("classid").equals(item.getString("classid"))).findFirst().orElse(null);
List<Document> descriptions = item.getList("descriptions", Document.class);
StringJoiner joiner = new StringJoiner("\n");
for (Document description : descriptions) {
String value = description.getString("value");
if (value.isBlank()) {
continue;
}
Element element = Jsoup.parse(value.replace("*", "\\*"));
for (Element italicElement : element.getElementsByTag("i")) {
italicElement.replaceWith(new TextNode("*" + italicElement.text() + "*"));
}
for (Element boldElement : element.getElementsByTag("b")) {
boldElement.replaceWith(new TextNode("**" + boldElement.text() + "**"));
}
joiner.add(element.text());
}
String inspect = item.getList("actions", Document.class, Collections.emptyList()).stream().filter(d -> d.getString("name").equals("Inspect in Game...")).map(d -> d.getString("link")).findFirst().orElse(null);
embed.setDescription(joiner.toString());
embed.setTitle(item.getString("market_name"), "https://steamcommunity.com/profiles/" + id + "/inventory/#" + game + (asset == null ? "" : "_2_" + asset.getString("assetid")));
embed.setImage("https://community.cloudflare.steamstatic.com/economy/image/" + item.getString("icon_url"));
if (inspect != null) {
embed.addField("Inspect In Game", "<" + inspect + ">", false);
}
Request itemRequest = new Request.Builder().url("https://steamcommunity.com/market/priceoverview/?appid=" + game + "¤cy=2&market_hash_name=" + URLEncoder.encode(item.getString("market_hash_name"), StandardCharsets.UTF_8)).build();
event.getHttpClient().newCall(itemRequest).enqueue((HttpCallback) itemResponse -> {
String itemBody = itemResponse.body().string();
if (itemBody.equals("null")) {
message.accept(new MessageBuilder().setEmbeds(embed.build()));
return;
}
Document priceData = Document.parse(itemBody);
if (priceData.getBoolean("success") && priceData.containsKey("lowest_price")) {
embed.addField("Lowest Price", priceData.getString("lowest_price"), false);
}
message.accept(new MessageBuilder().setEmbeds(embed.build()));
});
});
});
itemPaged.execute(event);
});
});
profilePaged.execute(event);
});
gamePaged.execute(event);
}
use of com.sx4.bot.annotations.command.Examples in project Sx4 by sx4-discord-bot.
the class SteamCommand method connect.
@Command(value = "connect", description = "Connect your steam account with Sx4")
@CommandId(488)
@Examples({ "steam connect" })
public void connect(Sx4CommandEvent event) {
String id = event.getAuthor().getId();
long timestamp = Instant.now().getEpochSecond();
String signature;
try {
signature = HmacUtility.getSignatureHex(event.getConfig().getSteam(), id + timestamp, HmacUtility.HMAC_MD5);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
event.replyFailure("Something went wrong there, try again").queue();
return;
}
String redirectUrl = URLEncoder.encode(event.getConfig().getBaseUrl() + "/redirect/steam?user_id=" + id + "×tamp=" + timestamp + "&signature=" + signature, StandardCharsets.UTF_8);
MessageEmbed embed = new EmbedBuilder().setAuthor("Steam Authorization").setDescription("The link below will allow you to link your steam account on Sx4\n**:warning: Do not give this link to anyone :warning:**\n\n[Authorize](https://sx4.dev/connect/steam?redirect_url=" + redirectUrl + ")").setColor(event.getConfig().getOrange()).setFooter("The authorization link will expire in 5 minutes").build();
event.getAuthor().openPrivateChannel().flatMap(channel -> channel.sendMessageEmbeds(embed)).flatMap($ -> event.replySuccess("I sent you a message containing your authorization link")).onErrorFlatMap($ -> event.replyFailure("I failed to send you your authorization link, make sure to have your dms open")).queue();
}
use of com.sx4.bot.annotations.command.Examples 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.annotations.command.Examples in project Sx4 by sx4-discord-bot.
the class FreeGamesCommand method preview.
@Command(value = "preview", description = "Preview your free game notification message")
@CommandId(481)
@Examples({ "free games preview" })
public void preview(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true) BaseGuildMessageChannel channel) {
MessageChannel messageChannel = event.getChannel();
if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
event.replyFailure("You cannot use this channel type").queue();
return;
}
BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
Document data = event.getMongo().getFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), Projections.include("message"));
if (data == null) {
event.replyFailure("You don't have a free game channel setup").queue();
return;
}
FreeGameUtility.retrieveFreeGames(event.getHttpClient(), freeGames -> {
Formatter<Document> formatter = new JsonFormatter(data.get("message", FreeGameManager.DEFAULT_MESSAGE)).addVariable("game", freeGames.get(0));
MessageUtility.fromWebhookMessage(event.getChannel(), MessageUtility.fromJson(formatter.parse()).build()).queue();
});
}
use of com.sx4.bot.annotations.command.Examples in project Sx4 by sx4-discord-bot.
the class FreeGamesCommand method remove.
@Command(value = "remove", description = "Remove a channel from getting free game notifications from Epic Games")
@CommandId(475)
@Examples({ "free games remove", "free games remove #channel" })
@AuthorPermissions(permissions = { Permission.MANAGE_SERVER })
public void remove(Sx4CommandEvent event, @Argument(value = "channel", nullDefault = true, endless = true) BaseGuildMessageChannel channel) {
MessageChannel messageChannel = event.getChannel();
if (channel == null && !(messageChannel instanceof BaseGuildMessageChannel)) {
event.replyFailure("You cannot use this channel type").queue();
return;
}
BaseGuildMessageChannel effectiveChannel = channel == null ? (BaseGuildMessageChannel) messageChannel : channel;
FindOneAndDeleteOptions options = new FindOneAndDeleteOptions().projection(Projections.include("webhook"));
event.getMongo().findAndDeleteFreeGameChannel(Filters.eq("channelId", effectiveChannel.getIdLong()), options).whenComplete((data, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getBot().getFreeGameManager().removeWebhook(effectiveChannel.getIdLong());
Document webhook = data.get("webhook", Document.class);
if (webhook != null) {
effectiveChannel.deleteWebhookById(Long.toString(webhook.getLong("id"))).queue(null, ErrorResponseException.ignore(ErrorResponse.UNKNOWN_WEBHOOK));
}
event.replySuccess("Free game notifications will no longer be sent in " + effectiveChannel.getAsMention()).queue();
});
}
Aggregations