use of com.sx4.bot.http.HttpCallback 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.sx4.bot.http.HttpCallback in project Sx4 by sx4-discord-bot.
the class VoteCommand method onCommand.
public void onCommand(Sx4CommandEvent event) {
Request request = new Request.Builder().url(event.getConfig().getVoteWebserverUrl("440996323156819968/votes/user/" + event.getAuthor().getId() + "/unused/use")).addHeader("Authorization", event.getConfig().getVoteApi(true)).build();
event.getHttpClient().newCall(request).enqueue((HttpCallback) response -> {
Document data = Document.parse(response.body().string());
if (!data.getBoolean("success")) {
Request latest = new Request.Builder().url(event.getConfig().getVoteWebserverUrl("440996323156819968/votes/user/" + event.getAuthor().getId() + "/latest")).addHeader("Authorization", event.getConfig().getVoteApi(true)).build();
event.getHttpClient().newCall(latest).enqueue((HttpCallback) latestResponse -> {
Document latestVote = Document.parse(latestResponse.body().string());
OffsetDateTime now = OffsetDateTime.now(ZoneOffset.UTC);
boolean weekend = now.getDayOfWeek() == DayOfWeek.FRIDAY || now.getDayOfWeek() == DayOfWeek.SATURDAY || now.getDayOfWeek() == DayOfWeek.SUNDAY;
EmbedBuilder embed = new EmbedBuilder().setAuthor("Vote Bonus", null, event.getAuthor().getEffectiveAvatarUrl());
long timeRemaining = 0;
Document vote = latestVote.get("vote", Document.class);
if (vote != null && latestVote.getBoolean("success")) {
timeRemaining = vote.get("time", Number.class).longValue() - Clock.systemUTC().instant().getEpochSecond() + VoteCommand.COOLDOWN;
}
if (timeRemaining > 0) {
embed.addField("Sx4", "**[You have voted recently you can vote for the bot again in " + TimeUtility.LONG_TIME_FORMATTER.parse(timeRemaining) + "](https://top.gg/bot/440996323156819968/vote)**", false);
} else {
embed.addField("Sx4", "**[You can vote for Sx4 for an extra $" + (weekend ? 1600 : 800) + "](https://top.gg/bot/440996323156819968/vote)**", false);
}
event.reply(embed.build()).queue();
});
return;
}
List<Document> votes = data.getList("votes", Document.class, Collections.emptyList());
Map<User, Long> referrers = new HashMap<>();
long money = 0L;
for (Document vote : votes) {
boolean weekend = vote.getBoolean("weekend");
money += weekend ? 1600 : 800;
Document query = vote.get("query", Document.class);
if (query == null) {
continue;
}
Object referral = query.get("referral");
if (referral == null) {
continue;
}
String id = referral instanceof List ? (String) ((List<?>) referral).get(0) : (String) referral;
User user;
try {
user = event.getShardManager().getUserById(id);
} catch (NumberFormatException e) {
continue;
}
if (user == null || user.getIdLong() == event.getAuthor().getIdLong() || user.isBot()) {
continue;
}
long amount = weekend ? 500 : 250;
referrers.compute(user, (key, value) -> value == null ? amount : value + amount);
}
List<WriteModel<Document>> bulkData = new ArrayList<>();
UpdateOptions options = new UpdateOptions().upsert(true);
StringJoiner content = new StringJoiner(", ");
referrers.forEach((user, amount) -> {
content.add(String.format("%s (**$%,d**)", user.getAsTag(), amount));
bulkData.add(new UpdateOneModel<>(Filters.eq("_id", user.getIdLong()), Updates.inc("economy.balance", amount), options));
});
bulkData.add(new UpdateOneModel<>(Filters.eq("_id", event.getAuthor().getIdLong()), Updates.inc("economy.balance", money), options));
String message = String.format("You have voted for the bot **%,d** time%s since you last used the command gathering you a total of **$%,d**, Vote for the bots again in 12 hours for more money.%s", votes.size(), votes.size() == 1 ? "" : "s", money, content.length() == 0 ? "" : "Referred users: " + content);
event.getMongo().bulkWriteUsers(bulkData).whenComplete((result, exception) -> {
if (ExceptionUtility.sendExceptionally(event, exception)) {
return;
}
event.reply(message).queue();
});
});
}
use of com.sx4.bot.http.HttpCallback 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.sx4.bot.http.HttpCallback 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.sx4.bot.http.HttpCallback 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