use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class ReputationCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true) Member member) {
User user = member.getUser();
if (user.getIdLong() == event.getAuthor().getIdLong()) {
event.replyFailure("You can not give reputation to yourself").queue();
return;
}
if (user.isBot()) {
event.replyFailure("You can not give reputation to bots").queue();
return;
}
event.getMongo().withTransaction(session -> {
List<Bson> update = List.of(Operators.set("reputation.resets", Operators.let(new Document("resets", Operators.ifNull("$reputation.resets", 0L)), Operators.cond(Operators.lt(Operators.nowEpochSecond(), "$$resets"), "$$resets", Operators.add(Operators.nowEpochSecond(), ReputationCommand.COOLDOWN)))));
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(Projections.include("reputation.resets")).returnDocument(ReturnDocument.BEFORE).upsert(true);
Document data = event.getMongo().getUsers().findOneAndUpdate(session, Filters.eq("_id", event.getAuthor().getIdLong()), update, options);
long now = Clock.systemUTC().instant().getEpochSecond(), resets = data == null ? 0L : data.getEmbedded(List.of("reputation", "resets"), 0L);
if (now < resets) {
event.reply("Slow down! You can give out reputation in " + TimeUtility.LONG_TIME_FORMATTER.parse(resets - now) + " :stopwatch:").queue();
session.abortTransaction();
return;
}
event.getMongo().getUsers().updateOne(session, Filters.eq("_id", user.getIdLong()), Updates.inc("reputation.amount", 1), new UpdateOptions().upsert(true));
}).whenComplete((updated, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception) || !updated) {
return;
}
event.replySuccess("**+1**, " + user.getName() + " has gained reputation").queue();
});
}
use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class TTSCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "query", endless = true) @Limit(max = 200) String query) {
Request request = new Request.Builder().url("https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en-gb&q=" + URLEncoder.encode(query, StandardCharsets.UTF_8)).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
event.replyFile(response.body().bytes(), query + ".mp3").queue();
});
}
use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class GameCommand method leaderboard.
@Command(value = "leaderboard", aliases = { "lb" }, description = "View the users who have played/won/lost/drawn the most games")
@CommandId(457)
@Redirects({ "lb games", "leaderboard games", "lb game", "leaderboard game" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void leaderboard(Sx4CommandEvent event, @Argument(value = "games") @Endless(minArguments = 0) GameType[] gameTypes, @Option(value = "server", aliases = { "guild" }, description = "Filters by only users in the current server") boolean guild, @Option(value = "state", description = "Filters whether the leaderboard should be for wins, played, losses or draws") GameState state) {
List<Bson> filters = new ArrayList<>();
if (gameTypes.length > 0) {
filters.add(Filters.in("type", Arrays.stream(gameTypes).map(GameType::getId).collect(Collectors.toList())));
}
if (state != null) {
filters.add(Filters.eq("state", state.getId()));
}
List<Bson> pipeline = List.of(Aggregates.project(Projections.include("state", "type", "userId")), Aggregates.match(filters.isEmpty() ? Filters.empty() : Filters.and(filters)), Aggregates.group("$userId", Accumulators.sum("count", 1L)), Aggregates.sort(Sorts.descending("count")));
event.getMongo().aggregateGames(pipeline).whenComplete((games, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
List<Map.Entry<User, Long>> users = new ArrayList<>();
AtomicInteger userIndex = new AtomicInteger(-1);
int i = 0;
for (Document game : games) {
User user = event.getShardManager().getUserById(game.getLong("_id"));
if (user == null) {
continue;
}
if (!event.getGuild().isMember(user) && guild) {
continue;
}
i++;
users.add(Map.entry(user, game.getLong("count")));
if (user.getIdLong() == event.getAuthor().getIdLong()) {
userIndex.set(i);
}
}
if (users.isEmpty()) {
event.replyFailure("There are no users which fit into this leaderboard").queue();
return;
}
PagedResult<Map.Entry<User, Long>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
int rank = userIndex.get();
EmbedBuilder embed = new EmbedBuilder().setTitle("Games Leaderboard").setFooter(event.getAuthor().getName() + "'s Rank: " + (rank == -1 ? "N/A" : NumberUtility.getSuffixed(rank)) + " | Page " + page.getPage() + "/" + page.getMaxPage(), event.getAuthor().getEffectiveAvatarUrl());
page.forEach((entry, index) -> embed.appendDescription(String.format("%d. `%s` - %,d game%s\n", index + 1, MarkdownSanitizer.escape(entry.getKey().getAsTag()), entry.getValue(), entry.getValue() == 1 ? "" : "s")));
return new MessageBuilder().setEmbeds(embed.build());
});
paged.execute(event);
});
}
use of com.sx4.bot.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class FishCommand 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.ROD.getId()));
Document data = event.getMongo().getItems().find(session, filter).first();
if (data == null) {
event.replyFailure("You do not have a fishing rod").queue();
session.abortTransaction();
return;
}
CooldownItemStack<Rod> rodStack = new CooldownItemStack<>(event.getBot().getEconomyManager(), data);
long usableAmount = rodStack.getUsableAmount();
if (usableAmount == 0) {
event.reply("Slow down! You can go fishing again in " + TimeUtility.LONG_TIME_FORMATTER.parse(rodStack.getTimeRemaining()) + " :stopwatch:").queue();
session.abortTransaction();
return;
}
Rod rod = rodStack.getItem();
long yield = rod.getYield(event.getBot().getEconomyManager());
embed.setAuthor(event.getAuthor().getName(), null, event.getAuthor().getEffectiveAvatarUrl()).setColor(event.getMember().getColorRaw()).setDescription(String.format("You fish for 5 minutes and sell your fish! (**$%,d**) :fish:", yield));
if (rod.getDurability() == 2) {
embed.appendDescription("\n\nYour fishing rod will break the next time you use it :warning:");
} else if (rod.getDurability() == 1) {
embed.appendDescription("\n\nYour fishing rod broke in the process");
}
Bson itemFilter = Filters.and(Filters.eq("userId", event.getAuthor().getIdLong()), Filters.eq("item.id", rod.getId()));
if (rod.getDurability() == 1) {
event.getMongo().getItems().deleteOne(session, itemFilter);
} else {
List<Bson> update = List.of(EconomyUtility.getResetsUpdate(usableAmount, FishCommand.COOLDOWN), Operators.set("item.durability", Operators.subtract("$item.durability", 1)));
event.getMongo().getItems().updateOne(session, itemFilter, update);
}
event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getAuthor().getIdLong()), Updates.inc("economy.balance", yield), 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.core.Sx4CommandEvent in project Sx4 by sx4-discord-bot.
the class FishingRodCommand method info.
@Command(value = "info", aliases = { "information" }, description = "View information on a users fishing rod")
@CommandId(382)
@Examples({ "fishing rod info", "fishing rod info @Shea#6653", "fishing rod info Shea" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void info(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
Member effectiveMember = member == null ? event.getMember() : member;
User user = member == null ? event.getAuthor() : effectiveMember.getUser();
Bson filter = Filters.and(Filters.eq("userId", effectiveMember.getIdLong()), Filters.eq("item.type", ItemType.ROD.getId()));
Document data = event.getMongo().getItem(filter, Projections.include("item"));
if (data == null) {
event.replyFailure("That user does not have a fishing rod").queue();
return;
}
Rod rod = Rod.fromData(event.getBot().getEconomyManager(), data.get("item", Document.class));
EmbedBuilder embed = new EmbedBuilder().setAuthor(user.getName() + "'s " + rod.getName(), null, user.getEffectiveAvatarUrl()).setColor(effectiveMember.getColorRaw()).setThumbnail("https://emojipedia-us.s3.amazonaws.com/thumbs/120/twitter/147/fishing-pole-and-fish_1f3a3.png").addField("Durability", rod.getDurability() + "/" + rod.getMaxDurability(), false).addField("Current Price", String.format("$%,d", rod.getCurrentPrice()), false).addField("Price", String.format("$%,d", rod.getPrice()), false).addField("Yield", String.format("$%,d to $%,d", rod.getMinYield(), rod.getMaxYield()), false);
event.reply(embed.build()).queue();
}
Aggregations