Search in sources :

Example 36 with HttpCallback

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);
    });
}
Also used : Document(org.bson.Document) MarkdownSanitizer(net.dv8tion.jda.api.utils.MarkdownSanitizer) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Item(com.sx4.bot.entities.economy.item.Item) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Map(java.util.Map) Option(com.jockie.bot.core.option.Option) com.mongodb.client.model(com.mongodb.client.model) ZoneOffset(java.time.ZoneOffset) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Month(java.time.Month) TextStyle(java.time.format.TextStyle) Sx4Command(com.sx4.bot.core.Sx4Command) NumberUtility(com.sx4.bot.utility.NumberUtility) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) User(net.dv8tion.jda.api.entities.User) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Request(okhttp3.Request) Document(org.bson.Document) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) OffsetDateTime(java.time.OffsetDateTime) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) List(java.util.List) Map(java.util.Map) PagedResult(com.sx4.bot.paged.PagedResult) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Command(com.jockie.bot.core.command.Command) Sx4Command(com.sx4.bot.core.Sx4Command) CommandId(com.sx4.bot.annotations.command.CommandId) Examples(com.sx4.bot.annotations.command.Examples)

Example 37 with HttpCallback

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();
        });
    });
}
Also used : Document(org.bson.Document) Request(okhttp3.Request) java.util(java.util) Command(com.jockie.bot.core.command.Command) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) CommandId(com.sx4.bot.annotations.command.CommandId) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) Redirects(com.sx4.bot.annotations.command.Redirects) ModuleCategory(com.sx4.bot.category.ModuleCategory) Examples(com.sx4.bot.annotations.command.Examples) OffsetDateTime(java.time.OffsetDateTime) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) DayOfWeek(java.time.DayOfWeek) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) com.mongodb.client.model(com.mongodb.client.model) ZoneOffset(java.time.ZoneOffset) Argument(com.jockie.bot.core.argument.Argument) User(net.dv8tion.jda.api.entities.User) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Request(okhttp3.Request) HttpCallback(com.sx4.bot.http.HttpCallback) Document(org.bson.Document) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) OffsetDateTime(java.time.OffsetDateTime)

Example 38 with HttpCallback

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());
    });
}
Also used : Document(org.bson.Document) java.util(java.util) Command(com.jockie.bot.core.command.Command) Permission(net.dv8tion.jda.api.Permission) MongoDatabase(com.sx4.bot.database.mongo.MongoDatabase) Cooldown(com.jockie.bot.core.command.Command.Cooldown) CommandId(com.sx4.bot.annotations.command.CommandId) Member(net.dv8tion.jda.api.entities.Member) Async(com.jockie.bot.core.command.Command.Async) User(net.dv8tion.jda.api.entities.User) Bson(org.bson.conversions.Bson) Alternative(com.sx4.bot.entities.argument.Alternative) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) com.sx4.bot.utility(com.sx4.bot.utility) com.mongodb.client.model(com.mongodb.client.model) ZoneOffset(java.time.ZoneOffset) GameState(com.sx4.bot.entities.games.GameState) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) TextStyle(java.time.format.TextStyle) Sx4Command(com.sx4.bot.core.Sx4Command) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) com.sx4.bot.annotations.argument(com.sx4.bot.annotations.argument) ModuleCategory(com.sx4.bot.category.ModuleCategory) Examples(com.sx4.bot.annotations.command.Examples) LocalDate(java.time.LocalDate) Clock(java.time.Clock) ICooldown(com.jockie.bot.core.cooldown.ICooldown) User(net.dv8tion.jda.api.entities.User) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Document(org.bson.Document) LocalDate(java.time.LocalDate) Bson(org.bson.conversions.Bson)

Example 39 with HttpCallback

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());
}
Also used : ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Permission(net.dv8tion.jda.api.Permission) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) ImageRequest(com.sx4.bot.entities.image.ImageRequest) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest)

Example 40 with HttpCallback

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();
    }
}
Also used : Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest) HttpCallback(com.sx4.bot.http.HttpCallback) ImageUtility(com.sx4.bot.utility.ImageUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) Random(java.util.Random) Member(net.dv8tion.jda.api.entities.Member) User(net.dv8tion.jda.api.entities.User) ModuleCategory(com.sx4.bot.category.ModuleCategory) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) MessageAction(net.dv8tion.jda.api.requests.restaction.MessageAction) Argument(com.jockie.bot.core.argument.Argument) User(net.dv8tion.jda.api.entities.User) ImageRequest(com.sx4.bot.entities.image.ImageRequest) MessageAction(net.dv8tion.jda.api.requests.restaction.MessageAction) Request(okhttp3.Request) ImageRequest(com.sx4.bot.entities.image.ImageRequest)

Aggregations

HttpCallback (com.sx4.bot.http.HttpCallback)85 Request (okhttp3.Request)83 ModuleCategory (com.sx4.bot.category.ModuleCategory)68 Sx4Command (com.sx4.bot.core.Sx4Command)68 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)68 Permission (net.dv8tion.jda.api.Permission)67 Argument (com.jockie.bot.core.argument.Argument)63 Document (org.bson.Document)51 ImageRequest (com.sx4.bot.entities.image.ImageRequest)35 ImageUtility (com.sx4.bot.utility.ImageUtility)33 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)33 ImageUrl (com.sx4.bot.annotations.argument.ImageUrl)28 PagedResult (com.sx4.bot.paged.PagedResult)24 StandardCharsets (java.nio.charset.StandardCharsets)23 URLEncoder (java.net.URLEncoder)22 java.util (java.util)20 OffsetDateTime (java.time.OffsetDateTime)18 Collectors (java.util.stream.Collectors)18 Bson (org.bson.conversions.Bson)17 Command (com.jockie.bot.core.command.Command)16