use of com.sx4.bot.core.Sx4CommandEvent 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.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class BotListCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "page") @DefaultNumber(1) @Limit(min = 1, max = 50) int page) {
Request request = new Request.Builder().url("https://top.gg/api/bots?sort=server_count&limit=500&fields=username,server_count,id").addHeader("Authorization", event.getConfig().getTopGG()).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
List<Document> results = data.getList("results", Document.class);
PagedResult<Document> paged = new PagedResult<>(event.getBot(), results).setPage(page).setAuthor("Bot List", null, "https://imgur.com/HlfRQ3g.png").setIncreasedIndex(true).setSelect().setDisplayFunction(bot -> String.format("[%s](https://top.gg/bot/%s) - **%,d** servers", bot.getString("username"), bot.getString("id"), bot.getInteger("server_count")));
paged.execute(event);
});
}
use of com.sx4.bot.core.Sx4CommandEvent 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("Referer", 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/cdn-cgi/image/width=512,height=384,fit=pad,format=png,quality=100,background=transparent/images/screenshots/" + d.getInteger("assetId") + "/backside.png");
embeds.add(embed.build());
embed.setImage("https://cdn.skinport.com/cdn-cgi/image/width=512,height=384,fit=pad,format=png,quality=100,background=transparent/images/screenshots/" + d.getInteger("assetId") + "/playside.png");
embeds.add(embed.build());
}
});
return new MessageBuilder().setEmbeds(embeds);
});
skins.execute(event);
});
});
suggestions.execute(event);
});
}
use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class CalculatorCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "expression", endless = true) String expression, @Option(value = "pretty", description = "Puts a comma every 3 digits before the decimal point") boolean pretty) {
CalcLexer lexer = new CalcLexer(CharStreams.fromString(expression));
CalcParser parser = new CalcParser(new CommonTokenStream(lexer));
new CalcEvalVisitor().parse(parser.parse()).orTimeout(100, TimeUnit.MILLISECONDS).whenComplete((result, exception) -> {
Throwable cause = exception instanceof CompletionException ? exception.getCause() : exception;
if (cause instanceof TimeoutException) {
event.reply("That expression took longer than 100ms to execute :stopwatch:").queue();
return;
}
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
DecimalFormat format = new DecimalFormat((pretty ? ",##" : "") + "0.##########");
event.reply(format.format(result)).queue();
});
}
use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class CommandStatsCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Option(value = "group", description = "What to group the data by, default is command") GroupType group, @Option(value = "command", description = "Provide a command filter") Sx4Command command, @Option(value = "server", aliases = { "guild" }, description = "Provide a server filter") Guild guild, @Option(value = "channel", description = "Provide a channel filter") TextChannel channel, @Option(value = "user", description = "Provide a user id argument") long userId, @Option(value = "from", description = "When the data should start in epoch seconds") long from, @Option(value = "to", description = "When the data should end in epoch seconds") long to) {
List<Bson> filters = new ArrayList<>();
if (command != null) {
filters.add(Filters.eq("command.id", command.getId()));
}
if (group == GroupType.CHANNEL) {
filters.add(Filters.eq("guildId", event.getGuild().getIdLong()));
} else if (guild != null) {
filters.add(Filters.eq("guildId", guild.getIdLong()));
}
if (userId != 0L) {
filters.add(Filters.eq("authorId", userId));
}
if (channel != null) {
filters.add(Filters.eq("channelId", channel.getIdLong()));
}
if (from != 0L) {
filters.add(Filters.gte("_id", new ObjectId(Date.from(Instant.ofEpochSecond(from)))));
}
if (to != 0L) {
filters.add(Filters.lte("_id", new ObjectId(Date.from(Instant.ofEpochSecond(to)))));
}
List<Bson> pipeline = List.of(Aggregates.match(filters.isEmpty() ? Filters.empty() : Filters.and(filters)), Aggregates.group("$" + (group == null ? GroupType.COMMAND : group).getField(), Accumulators.sum("count", 1L)), Aggregates.sort(Sorts.descending("count")));
event.getMongo().aggregateCommands(pipeline).whenComplete((commands, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (commands.isEmpty()) {
event.replyFailure("No data was found with those filters").queue();
return;
}
PagedResult<Document> paged = new PagedResult<>(event.getBot(), commands).setIndexed(false).setSelect().setAuthor("Command Stats", null, event.getSelfUser().getEffectiveAvatarUrl()).setDisplayFunction(data -> {
String prefix = null;
if (group == null || group == GroupType.COMMAND) {
prefix = "`" + data.getString("_id") + "`";
} else if (group == GroupType.CHANNEL) {
long id = data.getLong("_id");
GuildMessageChannel messageChannel = event.getGuild().getChannelById(GuildMessageChannel.class, id);
prefix = messageChannel == null ? "#deleted-channel (" + id + ")" : messageChannel.getAsMention();
} else if (group == GroupType.USER) {
long id = data.getLong("_id");
User user = event.getShardManager().getUserById(id);
prefix = "`" + (user == null ? "Anonymous#0000 (" + id + ")" : MarkdownSanitizer.escape(user.getAsTag())) + "`";
} else if (group == GroupType.SERVER) {
Long id = data.getLong("_id");
if (id == null) {
prefix = "`Private Messages`";
} else {
Guild guildGroup = event.getShardManager().getGuildById(id);
prefix = "`" + (guildGroup == null ? "Unknown Server (" + id + ")" : MarkdownSanitizer.escape(guildGroup.getName())) + "`";
}
}
long count = data.getLong("count");
return (prefix == null ? "Unknown" : prefix) + " - " + String.format("%,d", count) + " use" + (count == 1 ? "" : "s");
});
paged.execute(event);
});
}
Aggregations