use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.
the class ChopCommand method onCommand.
public void onCommand(Sx4CommandEvent event) {
EmbedBuilder embed = new EmbedBuilder();
event.getMongo().withTransaction(session -> {
Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.type", ItemType.AXE.getId()));
Document data = event.getMongo().getItems().find(session, filter).first();
if (data == null) {
event.replyFailure("You do not have a axe").queue();
session.abortTransaction();
return;
}
CooldownItemStack<Axe> axeStack = new CooldownItemStack<>(event.getBot().getEconomyManager(), data);
long usableAmount = axeStack.getUsableAmount();
if (usableAmount == 0) {
event.reply("Slow down! You can chop some trees down again in " + TimeUtility.LONG_TIME_FORMATTER.parse(axeStack.getTimeRemaining()) + " :stopwatch:").queue();
session.abortTransaction();
return;
}
Axe axe = axeStack.getItem();
List<ItemStack<Wood>> materialStacks = axe.getWoodYield();
String materials = materialStacks.stream().map(ItemStack::toString).collect(Collectors.joining(", "));
embed.setAuthor(event.getAuthor().getName(), null, event.getAuthor().getEffectiveAvatarUrl()).setColor(event.getMember().getColorRaw()).setDescription(String.format("You chopped down some trees :axe:\nWood found: %s", materialStacks.isEmpty() ? "Nothing" : materials));
if (axe.getDurability() == 2) {
embed.appendDescription("\n\nYour axe will break the next time you use it :warning:");
} else if (axe.getDurability() == 1) {
embed.appendDescription("\n\nYour axe broke in the process");
}
Bson itemFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", axe.getId()));
if (axe.getDurability() == 1) {
event.getMongo().getItems().deleteOne(session, itemFilter);
} else {
List<Bson> update = List.of(EconomyUtility.getResetsUpdate(usableAmount, ChopCommand.COOLDOWN), Operators.set("item.durability", Operators.subtract("$item.durability", 1)));
event.getMongo().getItems().updateOne(session, itemFilter, update);
}
for (ItemStack<?> stack : materialStacks) {
Item item = stack.getItem();
List<Bson> update = List.of(Operators.set("item", item.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), stack.getAmount())));
Bson materialFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", item.getId()));
event.getMongo().getItems().updateOne(session, materialFilter, update, new UpdateOptions().upsert(true));
}
}).whenComplete((updated, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (updated) {
event.reply(embed.build()).queue();
}
});
}
use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.
the class CrateCommand method buy.
@Command(value = "buy", description = "Buy a crate from the `crate shop`")
@CommandId(412)
@Examples({ "crate buy 2 Shoe Crate", "crate buy Shoe Crate", "crate buy 5 Shoe" })
public void buy(Sx4CommandEvent event, @Argument(value = "crates", endless = true) ItemStack<Crate> stack) {
long amount = stack.getAmount();
if (amount < 1) {
event.replyFailure("You need to buy at least 1 crate").queue();
return;
}
long price = stack.getTotalPrice();
Crate crate = stack.getItem();
event.getMongo().withTransaction(session -> {
UpdateResult result = event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(price)));
if (result.getModifiedCount() == 0) {
event.replyFormat("You do not have **$%,d** %s", price, event.getConfig().getFailureEmote()).queue();
session.abortTransaction();
return;
}
Bson filter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", crate.getId()));
List<Bson> update = List.of(Operators.set("item", crate.toData()), Operators.set("amount", Operators.add(Operators.ifNull("$amount", 0L), amount)));
event.getMongo().getItems().updateOne(session, filter, update, new UpdateOptions().upsert(true));
}).whenComplete((updated, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception) || !updated) {
return;
}
event.replyFormat("You just bought `%,d %s` for **$%,d** %s", amount, crate.getName(), price, event.getConfig().getSuccessEmote()).queue();
});
}
use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.
the class RPSCommand method stats.
@Command(value = "stats", description = "View some stats about your personal rps record")
@CommandId(296)
@Examples({ "rps stats", "rps stats @Shea#6653" })
public void stats(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
User user = member == null ? event.getAuthor() : member.getUser();
Bson filter = Filters.and(Filters.eq("userId", user.getIdLong()), Filters.eq("type", GameType.ROCK_PAPER_SCISSORS.getId()));
List<Document> games = event.getMongo().getGames(filter, Projections.include("state")).into(new ArrayList<>());
if (games.isEmpty()) {
event.replyFailure("That user has not played rock paper scissors yet").queue();
return;
}
int wins = 0, draws = 0, losses = 0, total = 0;
for (Document game : games) {
GameState state = GameState.fromId(game.getInteger("state"));
if (state == GameState.WIN) {
wins++;
} else if (state == GameState.DRAW) {
draws++;
} else if (state == GameState.LOSS) {
losses++;
}
total++;
}
EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getAsTag(), null, user.getEffectiveAvatarUrl()).setDescription(String.format("Wins: %,d\nDraws: %,d\nLosses: %,d\n\nWin Percentage: %s%%", wins, draws, losses, NumberUtility.DEFAULT_DECIMAL_FORMAT.format(((double) wins / total) * 100)));
event.reply(embed.build()).queue();
}
use of com.sx4.bot.annotations.argument.UserId in project Sx4 by sx4-discord-bot.
the class SteamEndpoint method getSteam.
@GET
@Path("steam")
@Produces(MediaType.TEXT_HTML)
public void getSteam(@Context UriInfo info, @QueryParam("openid.identity") final String identity, @QueryParam("user_id") final long userId, @QueryParam("timestamp") long timestamp, @QueryParam("signature") String signature, @Suspended final AsyncResponse response) {
Document failureCopy = this.failure.clone();
long timestampNow = Instant.now().getEpochSecond();
if (timestampNow - timestamp >= 300) {
response.resume(Response.status(401).entity(this.setText(failureCopy, "Authorization link timed out")).build());
return;
}
String hash;
try {
hash = HmacUtility.getSignatureHex(this.bot.getConfig().getSteam(), Long.toString(userId) + timestamp, HmacUtility.HMAC_MD5);
} catch (NoSuchAlgorithmException | InvalidKeyException e) {
response.resume(Response.status(500).entity(this.setText(failureCopy, "Something went wrong while authenticating your account")).build());
return;
}
if (!hash.equals(signature)) {
response.resume(Response.status(401).entity(this.setText(failureCopy, "Unauthorized")).build());
}
StringBuilder url = new StringBuilder("https://steamcommunity.com/openid/login");
MultivaluedMap<String, String> parameters = info.getQueryParameters();
boolean first = true;
for (String key : parameters.keySet()) {
if (first) {
url.append("?");
first = false;
} else {
url.append("&");
}
url.append(key).append("=").append(URLEncoder.encode(key.equals("openid.mode") ? "check_authentication" : parameters.get(key).get(0), StandardCharsets.UTF_8));
}
Request request = new Request.Builder().url(url.toString()).build();
this.bot.getHttpClient().newCall(request).enqueue((HttpCallback) steamResponse -> {
String body = steamResponse.body().string();
String[] lines = body.split("\n");
for (String line : lines) {
String[] keyValue = line.split(":");
if (keyValue[0].equals("is_valid") && !keyValue[1].equals("true")) {
response.resume(Response.status(401).entity(this.setText(failureCopy, "Unauthorized")).build());
return;
}
}
long steamId = Long.parseLong(identity.substring(identity.lastIndexOf('/') + 1));
Request steamRequest = new Request.Builder().url("https://steamcommunity.com/profiles/" + steamId + "?xml=1").build();
this.bot.getHttpClient().newCall(steamRequest).enqueue((HttpCallback) profileResponse -> {
JSONObject data = XML.toJSONObject(profileResponse.body().string());
JSONObject profile = data.getJSONObject("profile");
org.bson.Document connection = new org.bson.Document("id", steamId).append("name", profile.getString("steamID"));
List<Bson> update = List.of(Operators.set("connections.steam", Operators.concatArrays(List.of(connection), Operators.filter(Operators.ifNull("$connections.steam", Collections.EMPTY_LIST), Operators.ne("$$this.id", steamId)))));
this.bot.getMongo().updateUserById(userId, update).whenComplete((result, exception) -> {
if (ExceptionUtility.sendErrorMessage(exception)) {
response.resume(Response.status(500).entity(this.setText(failureCopy, "Something went wrong while authenticating your account")).build());
return;
}
Document successCopy = this.success.clone();
response.resume(Response.ok(this.setText(successCopy, "Connected your steam account to Sx4")).build());
});
});
});
}
use of com.sx4.bot.annotations.argument.UserId 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