Search in sources :

Example 51 with Argument

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();
    });
}
Also used : Document(org.bson.Document) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Member(net.dv8tion.jda.api.entities.Member) AmountArgument(com.sx4.bot.entities.argument.AmountArgument) User(net.dv8tion.jda.api.entities.User) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) com.mongodb.client.model(com.mongodb.client.model) Argument(com.jockie.bot.core.argument.Argument) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) Document(org.bson.Document)

Example 52 with Argument

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);
    });
}
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 53 with Argument

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());
    });
}
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 54 with Argument

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());
}
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 55 with Argument

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();
    }
}
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

Argument (com.jockie.bot.core.argument.Argument)112 ModuleCategory (com.sx4.bot.category.ModuleCategory)112 Sx4Command (com.sx4.bot.core.Sx4Command)112 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)112 Permission (net.dv8tion.jda.api.Permission)101 Document (org.bson.Document)67 HttpCallback (com.sx4.bot.http.HttpCallback)60 Request (okhttp3.Request)59 PagedResult (com.sx4.bot.paged.PagedResult)58 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)54 Command (com.jockie.bot.core.command.Command)49 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)43 Bson (org.bson.conversions.Bson)42 List (java.util.List)41 Operators (com.sx4.bot.database.mongo.model.Operators)40 CommandId (com.sx4.bot.annotations.command.CommandId)39 Examples (com.sx4.bot.annotations.command.Examples)39 Collectors (java.util.stream.Collectors)38 ImageUrl (com.sx4.bot.annotations.argument.ImageUrl)35 ImageRequest (com.sx4.bot.entities.image.ImageRequest)33