Search in sources :

Example 21 with Sx4CommandEvent

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();
    });
}
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) Member(net.dv8tion.jda.api.entities.Member) PagedResult(com.sx4.bot.paged.PagedResult) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Bson(org.bson.conversions.Bson) Redirects(com.sx4.bot.annotations.command.Redirects) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Map(java.util.Map) Option(com.jockie.bot.core.option.Option) com.mongodb.client.model(com.mongodb.client.model) BotPermissions(com.sx4.bot.annotations.command.BotPermissions) Argument(com.jockie.bot.core.argument.Argument) Operators(com.sx4.bot.database.mongo.model.Operators) 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) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Clock(java.time.Clock) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) List(java.util.List) Document(org.bson.Document)

Example 22 with Sx4CommandEvent

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();
    });
}
Also used : ModuleCategory(com.sx4.bot.category.ModuleCategory) Request(okhttp3.Request) URLEncoder(java.net.URLEncoder) HttpCallback(com.sx4.bot.http.HttpCallback) Sx4Command(com.sx4.bot.core.Sx4Command) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) Permission(net.dv8tion.jda.api.Permission) StandardCharsets(java.nio.charset.StandardCharsets) Argument(com.jockie.bot.core.argument.Argument) Limit(com.sx4.bot.annotations.argument.Limit) Request(okhttp3.Request)

Example 23 with Sx4CommandEvent

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);
    });
}
Also used : User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) Document(org.bson.Document) Bson(org.bson.conversions.Bson) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) PagedResult(com.sx4.bot.paged.PagedResult) Redirects(com.sx4.bot.annotations.command.Redirects) 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)

Example 24 with Sx4CommandEvent

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();
        }
    });
}
Also used : CooldownItemStack(com.sx4.bot.entities.economy.item.CooldownItemStack) Document(org.bson.Document) Operators(com.sx4.bot.database.mongo.model.Operators) ItemType(com.sx4.bot.entities.economy.item.ItemType) EconomyUtility(com.sx4.bot.utility.EconomyUtility) Sx4Command(com.sx4.bot.core.Sx4Command) Permission(net.dv8tion.jda.api.Permission) Updates(com.mongodb.client.model.Updates) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Filters(com.mongodb.client.model.Filters) Bson(org.bson.conversions.Bson) ModuleCategory(com.sx4.bot.category.ModuleCategory) List(java.util.List) Sx4CommandEvent(com.sx4.bot.core.Sx4CommandEvent) TimeUtility(com.sx4.bot.utility.TimeUtility) Rod(com.sx4.bot.entities.economy.item.Rod) ExceptionUtility(com.sx4.bot.utility.ExceptionUtility) UpdateOptions(com.mongodb.client.model.UpdateOptions) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Rod(com.sx4.bot.entities.economy.item.Rod) List(java.util.List) Document(org.bson.Document) CooldownItemStack(com.sx4.bot.entities.economy.item.CooldownItemStack) UpdateOptions(com.mongodb.client.model.UpdateOptions) Bson(org.bson.conversions.Bson)

Example 25 with Sx4CommandEvent

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();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) User(net.dv8tion.jda.api.entities.User) Rod(com.sx4.bot.entities.economy.item.Rod) Document(org.bson.Document) ReturnDocument(com.mongodb.client.model.ReturnDocument) Member(net.dv8tion.jda.api.entities.Member) Bson(org.bson.conversions.Bson) 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)

Aggregations

Sx4Command (com.sx4.bot.core.Sx4Command)255 Command (com.jockie.bot.core.command.Command)181 Document (org.bson.Document)153 ModuleCategory (com.sx4.bot.category.ModuleCategory)130 Sx4CommandEvent (com.sx4.bot.core.Sx4CommandEvent)130 CommandId (com.sx4.bot.annotations.command.CommandId)121 Argument (com.jockie.bot.core.argument.Argument)119 Examples (com.sx4.bot.annotations.command.Examples)119 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)119 Permission (net.dv8tion.jda.api.Permission)119 Bson (org.bson.conversions.Bson)111 PagedResult (com.sx4.bot.paged.PagedResult)90 HttpCallback (com.sx4.bot.http.HttpCallback)69 Request (okhttp3.Request)68 AuthorPermissions (com.sx4.bot.annotations.command.AuthorPermissions)60 User (net.dv8tion.jda.api.entities.User)57 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)55 ExceptionUtility (com.sx4.bot.utility.ExceptionUtility)54 Operators (com.sx4.bot.database.mongo.model.Operators)50 List (java.util.List)50