use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class GiveCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user") Member member, @Argument(value = "amount") AmountArgument amount) {
User user = member == null ? event.getAuthor() : member.getUser();
if (user.isBot() && user.getIdLong() != event.getSelfUser().getIdLong()) {
event.replyFailure("You can not give money to bots").queue();
return;
}
boolean tax = user.getIdLong() == event.getSelfUser().getIdLong();
event.getMongo().withTransaction(session -> {
FindOneAndUpdateOptions options = new FindOneAndUpdateOptions().projection(Projections.include("economy.balance")).returnDocument(ReturnDocument.BEFORE);
Document authorData = event.getMongo().getUsers().findOneAndUpdate(session, Filters.eq("_id", event.getAuthor().getIdLong()), List.of(EconomyUtility.decreaseBalanceUpdate(amount)), options);
if (authorData == null) {
event.replyFailure("You do not have any money").queue();
session.abortTransaction();
return null;
}
long authorBalance = authorData.getEmbedded(List.of("economy", "balance"), 0L);
if (authorBalance == 0L) {
event.replyFailure("You do not have any money").queue();
session.abortTransaction();
return null;
}
long effectiveAmount = amount.getEffectiveAmount(authorBalance);
if (authorBalance < effectiveAmount) {
event.replyFailure(String.format("You do not have **$%,d**", authorBalance)).queue();
session.abortTransaction();
return null;
}
long amountGiven = tax ? effectiveAmount : (long) (effectiveAmount * 0.95D), taxAmount = tax ? effectiveAmount : (long) Math.ceil(effectiveAmount * 0.05D);
Document userData;
if (tax) {
userData = event.getMongo().getUsers().findOneAndUpdate(session, Filters.eq("_id", event.getSelfUser().getIdLong()), Updates.inc("economy.balance", amountGiven), options);
} else {
userData = event.getMongo().getUsers().findOneAndUpdate(session, Filters.eq("_id", user.getIdLong()), Updates.inc("economy.balance", amountGiven), options.upsert(true));
event.getMongo().getUsers().updateOne(session, Filters.eq("_id", event.getSelfUser().getIdLong()), Updates.inc("economy.balance", taxAmount));
}
long userBalance = userData == null ? 0L : userData.getEmbedded(List.of("economy", "balance"), 0L);
EmbedBuilder embed = new EmbedBuilder().setAuthor(event.getAuthor().getName() + " → " + user.getName(), null, "https://cdn0.iconfinder.com/data/icons/social-messaging-ui-color-shapes/128/money-circle-green-3-512.png").setColor(event.getMember().getColor()).setDescription(String.format("You have gifted **$%,d** to **%s**\n\n%s's new balance: **$%,d**\n%s's new balance: **$%,d**", amountGiven, user.getName(), event.getAuthor().getName(), authorBalance - effectiveAmount, user.getName(), userBalance + amountGiven)).setFooter(String.format("$%,d (%d%%) tax was taken", taxAmount, Math.round((double) taxAmount / effectiveAmount * 100)), null);
return embed.build();
}).whenComplete((embed, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
if (embed == null) {
return;
}
event.reply(embed).queue();
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class LeaderboardCommand method votes.
@Command(value = "votes", description = "View the leaderboard for the votes of users")
@CommandId(374)
@Examples({ "leaderboard votes", "leaderboard votes December", "leaderboard votes July --server" })
@BotPermissions(permissions = { Permission.MESSAGE_EMBED_LINKS })
public void votes(Sx4CommandEvent event, @Argument(value = "month", nullDefault = true) Month month, @Option(value = "server", aliases = { "guild" }, description = "View the leaderboard with a server filter") boolean guild) {
StringBuilder url = new StringBuilder(event.getConfig().getVoteWebserverUrl("votesCount"));
int year;
if (month != null) {
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
year = month.getValue() > now.getMonthValue() ? now.getYear() - 1 : now.getYear();
OffsetDateTime monthStart = OffsetDateTime.of(year, month.getValue(), 1, 0, 0, 0, 0, ZoneOffset.UTC);
url.append("?after=").append(monthStart.toInstant().getEpochSecond()).append("&before=").append(monthStart.plusMonths(1).toInstant().getEpochSecond());
} else {
year = 0;
}
Request request = new Request.Builder().url(url.toString()).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
List<Document> votes = data.getList("votes", Document.class);
List<Map.Entry<User, Integer>> users = new ArrayList<>();
AtomicInteger userIndex = new AtomicInteger(-1);
int i = 0;
for (Document vote : votes) {
User user = event.getShardManager().getUserById(vote.getString("id"));
if (user == null) {
continue;
}
if (!event.getGuild().isMember(user) && guild) {
continue;
}
i++;
users.add(Map.entry(user, vote.getInteger("count")));
if (user.getIdLong() == event.getAuthor().getIdLong()) {
userIndex.set(i);
}
}
PagedResult<Map.Entry<User, Integer>> paged = new PagedResult<>(event.getBot(), users).setPerPage(10).setCustomFunction(page -> {
int rank = userIndex.get();
EmbedBuilder embed = new EmbedBuilder().setTitle("Votes Leaderboard" + (month == null ? "" : " for " + month.getDisplayName(TextStyle.FULL, Locale.UK) + " " + year)).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 vote%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.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class ProfileCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "user", endless = true, nullDefault = true) Member member) {
User user = member == null ? event.getAuthor() : member.getUser();
long expiry = event.getMongoMain().getUserById(Filters.eq("_id", user.getIdLong()), Projections.include("premium.endAt")).getEmbedded(List.of("premium", "endAt"), 0L);
List<Bson> gamePipeline = List.of(Aggregates.match(Filters.eq("userId", user.getIdLong())), Aggregates.group(null, Accumulators.sum("gamesPlayed", 1L), Accumulators.sum("gamesWon", Operators.cond(Operators.eq("$state", GameState.WIN.getId()), 1L, 0L))));
List<Bson> commandPipeline = List.of(Aggregates.match(Filters.eq("authorId", user.getIdLong())), Aggregates.count("commands"));
List<Bson> marriagePipeline = List.of(Aggregates.project(Projections.include("proposerId", "partnerId")), Aggregates.match(Filters.or(Filters.eq("proposerId", user.getIdLong()), Filters.eq("partnerId", user.getIdLong()))), Aggregates.group(null, Accumulators.push("marriages", Operators.ROOT)));
List<Bson> pipeline = List.of(Aggregates.project(Projections.fields(Projections.computed("balance", "$economy.balance"), Projections.include("profile"), Projections.computed("reputation", "$reputation.amount"), Projections.computed("premium", Operators.lt(Operators.nowEpochSecond(), Operators.ifNull("$premium.endAt", 0L))))), Aggregates.match(Filters.eq("_id", user.getIdLong())), Aggregates.unionWith("marriages", marriagePipeline), Aggregates.unionWith("commands", commandPipeline), Aggregates.unionWith("games", gamePipeline), Aggregates.group(null, Accumulators.max("balance", "$balance"), Accumulators.max("reputation", "$reputation"), Accumulators.max("marriages", "$marriages"), Accumulators.max("profile", "$profile"), Accumulators.max("gamesPlayed", "$gamesPlayed"), Accumulators.max("gamesWon", "$gamesWon"), Accumulators.max("commands", "$commands"), Accumulators.max("premium", Operators.ifNull("$premium", false))));
event.getMongo().aggregateUsers(pipeline).thenApply(documents -> {
Document data = documents.isEmpty() ? MongoDatabase.EMPTY_DOCUMENT : documents.get(0);
List<Document> marriages = data.getList("marriages", Document.class, Collections.emptyList());
List<String> partners = new ArrayList<>();
for (Document marriage : marriages) {
long partnerId = marriage.getLong("partnerId");
long otherId = partnerId == user.getIdLong() ? marriage.getLong("proposerId") : partnerId;
User other = event.getShardManager().getUserById(otherId);
if (other != null) {
partners.add(other.getName());
}
}
Document profileData = data.get("profile", MongoDatabase.EMPTY_DOCUMENT);
Document birthdayData = profileData.get("birthday", Document.class);
String birthday = null;
boolean isBirthday = false;
if (birthdayData != null) {
LocalDate date = LocalDate.now(ZoneOffset.UTC);
int day = birthdayData.getInteger("day"), month = birthdayData.getInteger("month");
isBirthday = date.getDayOfMonth() == day && date.getMonthValue() == month;
birthday = NumberUtility.getZeroPrefixedNumber(day) + "/" + NumberUtility.getZeroPrefixedNumber(month) + (birthdayData.containsKey("year") ? "/" + birthdayData.getInteger("year") : "");
}
return new ImageRequest(event.getConfig().getImageWebserverUrl("profile")).addField("birthday", birthday == null ? "Not set" : birthday).addField("is_birthday", isBirthday).addField("description", profileData.get("description", "Nothing to see here")).addField("height", profileData.get("height", 0)).addField("balance", NumberUtility.getNumberReadable(data.get("balance", 0L))).addField("reputation", data.get("reputation", 0)).addField("married_users", partners).addField("commands", data.get("commands", 0L)).addField("games_played", data.get("gamesPlayed", 0L)).addField("games_won", data.get("gamesWon", 0L)).addField("banner_id", profileData.getString("bannerId")).addField("directory", event.getConfig().isCanary() ? "sx4-canary" : "sx4-main").addField("name", user.getAsTag()).addField("gif", Clock.systemUTC().instant().getEpochSecond() < expiry).addField("avatar", user.getEffectiveAvatarUrl()).addField("colour", profileData.getInteger("colour")).build(event.getConfig().getImageWebserver());
}).whenComplete((request, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
});
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class ScrollCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "text", endless = true) @Limit(max = 45) String text) {
Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("scroll")).addQuery("text", text).build(event.getConfig().getImageWebserver());
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> ImageUtility.getImageMessage(event, response).queue());
}
use of com.jockie.bot.core.argument.Argument in project Sx4 by sx4-discord-bot.
the class ShipCommand method onCommand.
public void onCommand(Sx4CommandEvent event, @Argument(value = "first user") Member firstMember, @Argument(value = "second user", endless = true, nullDefault = true) Member secondMember) {
User firstUser = firstMember.getUser();
User secondUser = secondMember == null ? event.getAuthor() : secondMember.getUser();
this.random.setSeed(firstUser.getIdLong() + secondUser.getIdLong());
int percent = this.random.nextInt(100) + 1;
String firstName = firstUser.getName(), secondName = secondUser.getName();
String shipName = firstName.substring(0, (int) Math.ceil((double) firstName.length() / 2)) + secondName.substring((int) Math.ceil((double) secondName.length() / 2));
String message = String.format("Ship Name: **%s**\nLove Percentage: **%d%%**", shipName, percent);
Request request = new ImageRequest(event.getConfig().getImageWebserverUrl("ship")).addQuery("first_image", firstUser.getEffectiveAvatarUrl()).addQuery("second_image", secondUser.getEffectiveAvatarUrl()).addQuery("percent", percent).build(event.getConfig().getImageWebserver());
if (event.getSelfMember().hasPermission(event.getGuildChannel(), Permission.MESSAGE_ATTACH_FILES)) {
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
MessageAction action = ImageUtility.getImageMessage(event, response);
if (response.isSuccessful()) {
action.content(message);
}
action.queue();
});
} else {
event.reply(message).queue();
}
}
Aggregations