Search in sources :

Example 11 with Context

use of net.kodehawa.mantarobot.core.modules.commands.base.Context in project MantaroBot by Mantaro.

the class AnimeCmds method character.

@Subscribe
public void character(CommandRegistry cr) {
    cr.register("character", new SimpleCommand(CommandCategory.FUN) {

        @Override
        public void call(Context ctx, String content, String[] args) {
            try {
                if (content.isEmpty()) {
                    ctx.sendLocalized("commands.character.no_args", EmoteReference.ERROR);
                    return;
                }
                var characters = KitsuRetriever.searchCharacters(content);
                if (characters.isEmpty()) {
                    ctx.sendLocalized("commands.anime.no_results", EmoteReference.ERROR);
                    return;
                }
                var languageContext = ctx.getLanguageContext();
                if (characters.size() == 1) {
                    characterData(ctx.getEvent(), languageContext, characters.get(0));
                    return;
                }
                Function<CharacterData, String> format = character -> {
                    if (character.getAttributes().getNames().getJa_jp() == null) {
                        return "%s **[%s](%s)**".formatted(EmoteReference.BLUE_SMALL_MARKER, character.getAttributes().getName(), character.getURL());
                    } else {
                        return "%s **[%s](%s)** (%s)".formatted(EmoteReference.BLUE_SMALL_MARKER, character.getAttributes().getName(), character.getURL(), character.getAttributes().getNames().getJa_jp());
                    }
                };
                DiscordUtils.selectList(ctx.getEvent(), characters.stream().limit(5).collect(Collectors.toList()), format, s -> baseEmbed(ctx.getEvent(), languageContext.get("commands.anime.information_footer")).setDescription(s).setColor(Color.PINK).setThumbnail("https://i.imgur.com/VwlGqdk.png").setFooter(languageContext.get("commands.anime.information_footer"), ctx.getAuthor().getAvatarUrl()).build(), character -> characterData(ctx.getEvent(), languageContext, character));
            } catch (JsonProcessingException jex) {
                jex.printStackTrace();
                ctx.sendLocalized("commands.anime.no_results", EmoteReference.ERROR);
            } catch (NullPointerException npe) {
                npe.printStackTrace();
                ctx.sendLocalized("commands.anime.malformed_result", EmoteReference.ERROR);
            } catch (SocketTimeoutException timeout) {
                ctx.sendLocalized("commands.anime.timeout", EmoteReference.ERROR);
            } catch (Exception ex) {
                ctx.sendLocalized("commands.anime.error", EmoteReference.ERROR, ex.getClass().getSimpleName());
            }
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Get character info from Kitsu (For anime use `~>anime`).").setUsage("`~>character <name>` - Retrieve information of a charactrer based on the name").addParameter("name", "The name of the character you are looking for.").build();
        }
    });
    cr.registerAlias("character", "char");
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Color(java.awt.Color) Module(net.kodehawa.mantarobot.core.modules.Module) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) StringUtils(net.kodehawa.mantarobot.utils.StringUtils) CharacterData(net.kodehawa.mantarobot.commands.anime.CharacterData) Utils(net.kodehawa.mantarobot.utils.Utils) Function(java.util.function.Function) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Button(net.dv8tion.jda.api.interactions.components.Button) SocketTimeoutException(java.net.SocketTimeoutException) Subscribe(com.google.common.eventbus.Subscribe) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) DiscordUtils(net.kodehawa.mantarobot.utils.commands.DiscordUtils) GuildMessageReceivedEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent) KitsuRetriever(net.kodehawa.mantarobot.commands.anime.KitsuRetriever) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) APIUtils(net.kodehawa.mantarobot.utils.APIUtils) CommandCategory(net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) AnimeData(net.kodehawa.mantarobot.commands.anime.AnimeData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) SocketTimeoutException(java.net.SocketTimeoutException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Function(java.util.function.Function) SocketTimeoutException(java.net.SocketTimeoutException) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Subscribe(com.google.common.eventbus.Subscribe)

Example 12 with Context

use of net.kodehawa.mantarobot.core.modules.commands.base.Context in project MantaroBot by Mantaro.

the class AnimeCmds method anime.

@Subscribe
public void anime(CommandRegistry cr) {
    cr.register("anime", new SimpleCommand(CommandCategory.FUN) {

        @Override
        public void call(Context ctx, String content, String[] args) {
            try {
                if (content.isEmpty()) {
                    ctx.sendLocalized("commands.anime.no_args", EmoteReference.ERROR);
                    return;
                }
                var found = KitsuRetriever.searchAnime(content);
                if (found.isEmpty()) {
                    ctx.sendLocalized("commands.anime.no_results", EmoteReference.ERROR);
                    return;
                }
                var languageContext = ctx.getLanguageContext();
                if (found.size() == 1) {
                    animeData(ctx.getEvent(), languageContext, found.get(0));
                    return;
                }
                Function<AnimeData, String> format = anime -> {
                    if (anime.getAttributes().getTitles().getJa_jp() != null) {
                        return "%s **[%s](%s)** (%s)".formatted(EmoteReference.BLUE_SMALL_MARKER, anime.getAttributes().getCanonicalTitle(), anime.getURL(), anime.getAttributes().getTitles().getJa_jp());
                    } else {
                        return "%s **[%s](%s)**".formatted(EmoteReference.BLUE_SMALL_MARKER, anime.getAttributes().getCanonicalTitle(), anime.getURL());
                    }
                };
                DiscordUtils.selectList(ctx.getEvent(), found.stream().limit(5).collect(Collectors.toList()), format, s -> baseEmbed(ctx.getEvent(), languageContext.get("commands.anime.selection_start")).setDescription(s).setColor(Color.PINK).setThumbnail("https://i.imgur.com/VwlGqdk.png").setFooter(languageContext.get("commands.anime.information_footer"), ctx.getAuthor().getAvatarUrl()).build(), anime -> animeData(ctx.getEvent(), languageContext, anime));
            } catch (JsonProcessingException jex) {
                jex.printStackTrace();
                ctx.sendLocalized("commands.anime.no_results", EmoteReference.ERROR);
            } catch (NullPointerException npe) {
                npe.printStackTrace();
                ctx.sendLocalized("commands.anime.malformed_result", EmoteReference.ERROR);
            } catch (SocketTimeoutException timeout) {
                ctx.sendLocalized("commands.anime.timeout", EmoteReference.ERROR);
            } catch (Exception ex) {
                ex.printStackTrace();
                ctx.sendLocalized("commands.anime.error", EmoteReference.ERROR, ex.getClass().getSimpleName());
            }
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Get anime info from Kitsu (For anime characters use ~>character).").setUsage("`~>anime <name>` - Retrieve information of an anime based on the name").addParameter("name", "The name of the anime you're looking for.").build();
        }
    });
    cr.registerAlias("anime", "animu");
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Color(java.awt.Color) Module(net.kodehawa.mantarobot.core.modules.Module) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) StringUtils(net.kodehawa.mantarobot.utils.StringUtils) CharacterData(net.kodehawa.mantarobot.commands.anime.CharacterData) Utils(net.kodehawa.mantarobot.utils.Utils) Function(java.util.function.Function) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Button(net.dv8tion.jda.api.interactions.components.Button) SocketTimeoutException(java.net.SocketTimeoutException) Subscribe(com.google.common.eventbus.Subscribe) ActionRow(net.dv8tion.jda.api.interactions.components.ActionRow) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) DiscordUtils(net.kodehawa.mantarobot.utils.commands.DiscordUtils) GuildMessageReceivedEvent(net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent) KitsuRetriever(net.kodehawa.mantarobot.commands.anime.KitsuRetriever) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) StringEscapeUtils(org.apache.commons.text.StringEscapeUtils) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) APIUtils(net.kodehawa.mantarobot.utils.APIUtils) CommandCategory(net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) AnimeData(net.kodehawa.mantarobot.commands.anime.AnimeData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) SocketTimeoutException(java.net.SocketTimeoutException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Function(java.util.function.Function) SocketTimeoutException(java.net.SocketTimeoutException) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Subscribe(com.google.common.eventbus.Subscribe)

Example 13 with Context

use of net.kodehawa.mantarobot.core.modules.commands.base.Context in project MantaroBot by Mantaro.

the class DebugCmds method ping.

@Subscribe
public void ping(CommandRegistry cr) {
    final IncreasingRateLimiter rateLimiter = new IncreasingRateLimiter.Builder().limit(1).spamTolerance(2).cooldown(2, TimeUnit.SECONDS).maxCooldown(30, TimeUnit.SECONDS).randomIncrement(true).pool(MantaroData.getDefaultJedisPool()).prefix("ping").build();
    cr.register("ping", new SimpleCommand(CommandCategory.INFO) {

        @Override
        protected void call(Context ctx, String content, String[] args) {
            I18nContext languageContext = ctx.getLanguageContext();
            if (!RatelimitUtils.ratelimit(rateLimiter, ctx, false))
                return;
            long start = System.currentTimeMillis();
            ctx.getChannel().sendMessage("Pinging...").queue(v -> {
                long ping = System.currentTimeMillis() - start;
                // display: show a random quote, translated.
                v.editMessage(String.format(Utils.getLocaleFromLanguage(ctx.getLanguageContext()), languageContext.get("commands.ping.text"), EmoteReference.MEGA, languageContext.get("commands.ping.display"), ping, ctx.getJDA().getGatewayPing())).queue();
            });
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Plays Ping-Pong with Discord and prints out the result.").build();
        }
    });
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) MantaroInfo(net.kodehawa.mantarobot.MantaroInfo) Module(net.kodehawa.mantarobot.core.modules.Module) JDA(net.dv8tion.jda.api.JDA) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) Utils(net.kodehawa.mantarobot.utils.Utils) CommandProcessor(net.kodehawa.mantarobot.core.command.processor.CommandProcessor) JSONException(org.json.JSONException) JSONObject(org.json.JSONObject) LavalinkSocket(lavalink.client.io.LavalinkSocket) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Map(java.util.Map) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) LinkedList(java.util.LinkedList) CommandListener(net.kodehawa.mantarobot.core.listeners.command.CommandListener) DiscordUtils(net.kodehawa.mantarobot.utils.commands.DiscordUtils) IncreasingRateLimiter(net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter) IOException(java.io.IOException) AsyncInfoMonitor(net.kodehawa.mantarobot.commands.info.AsyncInfoMonitor) TimeUnit(java.util.concurrent.TimeUnit) APIUtils(net.kodehawa.mantarobot.utils.APIUtils) List(java.util.List) RatelimitUtils(net.kodehawa.mantarobot.utils.commands.ratelimit.RatelimitUtils) PlayerLibrary(com.sedmelluq.discord.lavaplayer.tools.PlayerLibrary) CommandCategory(net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Jedis(redis.clients.jedis.Jedis) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) JDAInfo(net.dv8tion.jda.api.JDAInfo) PreLoadEvent(net.kodehawa.mantarobot.core.listeners.events.PreLoadEvent) Comparator(java.util.Comparator) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) IncreasingRateLimiter(net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Subscribe(com.google.common.eventbus.Subscribe)

Example 14 with Context

use of net.kodehawa.mantarobot.core.modules.commands.base.Context in project MantaroBot by Mantaro.

the class DebugCmds method info.

@Subscribe
public void info(CommandRegistry cr) {
    cr.register("info", new SimpleCommand(CommandCategory.INFO) {

        @Override
        protected void call(Context ctx, String content, String[] args) {
            var config = ctx.getConfig();
            var bot = ctx.getBot();
            var guilds = 0L;
            var users = 0L;
            var clusterTotal = 0L;
            var players = 0L;
            var totalMemory = 0L;
            var queueSize = 0L;
            var totalThreadCount = 0L;
            var totalCommandCount = 0L;
            String nodeData;
            try (Jedis jedis = ctx.getJedisPool().getResource()) {
                nodeData = jedis.hget("node-stats-" + config.getClientId(), "node-" + bot.getNodeNumber());
            }
            try (Jedis jedis = ctx.getJedisPool().getResource()) {
                var stats = jedis.hgetAll("shardstats-" + config.getClientId());
                for (var shards : stats.entrySet()) {
                    var json = new JSONObject(shards.getValue());
                    guilds += json.getLong("guild_count");
                    users += json.getLong("cached_users");
                }
                var clusters = jedis.hgetAll("node-stats-" + config.getClientId());
                for (var cluster : clusters.entrySet()) {
                    var json = new JSONObject(cluster.getValue());
                    totalMemory += json.getLong("used_memory");
                    queueSize += json.getLong("queue_size");
                    totalThreadCount += json.getLong("thread_count");
                    totalCommandCount += json.getLong("commands_ran");
                }
                clusterTotal = clusters.size();
            }
            // We don't need to account for node stats delay here
            if (config.isPremiumBot()) {
                queueSize = ctx.getBot().getAudioManager().getTotalQueueSize();
            }
            List<LavalinkSocket> lavaLinkSockets = ctx.getBot().getLavaLink().getNodes();
            for (var lavaLink : lavaLinkSockets) {
                if (lavaLink.isAvailable() && lavaLink.getStats() != null) {
                    players += lavaLink.getStats().getPlayingPlayers();
                }
            }
            var responseTotal = bot.getShardManager().getShardCache().stream().mapToLong(JDA::getResponseTotal).sum();
            var mApiRequests = 0;
            try {
                mApiRequests = new JSONObject(APIUtils.getFrom("/mantaroapi/ping")).getInt("requests_served");
            } catch (IOException | JSONException ignored) {
            }
            // Get the master node.
            var node = new JSONObject(nodeData);
            var shardManager = ctx.getShardManager();
            var jda = ctx.getJDA();
            ctx.send("```prolog\n" + " --------- Technical Information --------- \n\n" + "Uptime: " + Utils.formatDuration(ctx.getLanguageContext(), node.getLong("uptime")) + "\n" + "Version: " + MantaroInfo.VERSION + " (Git: " + MantaroInfo.GIT_REVISION + ")\n" + "Libraries: " + "[ JDA: %s, LP: %s ]".formatted(JDAInfo.VERSION, PlayerLibrary.VERSION) + "\n" + "Commands: " + CommandProcessor.REGISTRY.commands().values().stream().filter(command -> command.category() != null).count() + "\n\n --------- Debug Information --------- \n\n" + "Replies: " + "[ Discord: %,d, MAPI: %,d ]".formatted(responseTotal, mApiRequests) + "\n" + "Nodes: " + "%,d (Current: %,d)".formatted(clusterTotal, ctx.getBot().getNodeNumber()) + "\n" + "CPU: " + "%.2f%% (Cores: %,d)".formatted(getInstanceCPUUsage() * 100, getAvailableProcessors()) + "\n" + "Memory: " + Utils.formatMemoryAmount(totalMemory) + " [Node: " + Utils.formatMemoryAmount(getTotalMemory() - getFreeMemory()) + "]" + "\n\n --------- Mantaro Information --------- \n\n" + "Guilds: " + "%,d (Node: %,d)".formatted(guilds, shardManager.getGuildCache().size()) + "\n" + "User Cache: " + "%,d (Node: %,d)".formatted(users, shardManager.getUserCache().size()) + "\n" + "Shards: " + bot.getShardManager().getShardsTotal() + " (This: " + jda.getShardInfo().getShardString() + ")" + "\n" + "Threads: " + "%,d (Node: %,d)".formatted(totalThreadCount, Thread.activeCount()) + "\n" + "Commands Used: " + "%,d (Node: %,d)".formatted(totalCommandCount, CommandListener.getCommandTotal()) + "\n" + "Overall: " + "[ Players: %,d, Queue: %,d ]".formatted(players, queueSize) + "\n" + "```");
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Gets the bot technical information. Nothing all that interesting, but shows cute stats.").build();
        }
    });
    cr.registerAlias("info", "status");
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Jedis(redis.clients.jedis.Jedis) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) JSONObject(org.json.JSONObject) JDA(net.dv8tion.jda.api.JDA) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) LinkedList(java.util.LinkedList) List(java.util.List) Subscribe(com.google.common.eventbus.Subscribe)

Example 15 with Context

use of net.kodehawa.mantarobot.core.modules.commands.base.Context in project MantaroBot by Mantaro.

the class MoneyCmds method daily.

@Subscribe
public void daily(CommandRegistry cr) {
    final IncreasingRateLimiter rateLimiter = new IncreasingRateLimiter.Builder().limit(1).cooldown(24, TimeUnit.HOURS).maxCooldown(24, TimeUnit.HOURS).randomIncrement(false).pool(MantaroData.getDefaultJedisPool()).prefix("daily").build();
    Random r = new Random();
    cr.register("daily", new SimpleCommand(CommandCategory.CURRENCY) {

        @Override
        public void call(Context ctx, String content, String[] args) {
            final var languageContext = ctx.getLanguageContext();
            // Args: Check -check for duration
            if (args.length > 0 && ctx.getMentionedUsers().isEmpty() && args[0].equalsIgnoreCase("-check")) {
                long rl = rateLimiter.getRemaniningCooldown(ctx.getAuthor());
                ctx.sendLocalized("commands.daily.check", EmoteReference.TALKING, (rl) > 0 ? Utils.formatDuration(ctx.getLanguageContext(), rl) : languageContext.get("commands.daily.about_now"));
                return;
            }
            // Determine who gets the money
            var dailyMoney = 150L;
            final var mentionedUsers = ctx.getMentionedUsers();
            final var author = ctx.getAuthor();
            var authorPlayer = ctx.getPlayer();
            var authorPlayerData = authorPlayer.getData();
            final var authorDBUser = ctx.getDBUser();
            final var authorUserData = authorDBUser.getData();
            if (authorPlayer.isLocked()) {
                ctx.sendLocalized("commands.daily.errors.own_locked");
                return;
            }
            UnifiedPlayer toAddMoneyTo = UnifiedPlayer.of(author, ctx.getConfig().getCurrentSeason());
            User otherUser = null;
            boolean targetOther = !mentionedUsers.isEmpty();
            if (targetOther) {
                otherUser = mentionedUsers.get(0);
                // Bot check mentioned authorDBUser
                if (otherUser.isBot()) {
                    ctx.sendLocalized("commands.daily.errors.bot", EmoteReference.ERROR);
                    return;
                }
                if (otherUser.getIdLong() == author.getIdLong()) {
                    ctx.sendLocalized("commands.daily.errors.same_user", EmoteReference.ERROR);
                    return;
                }
                var playerOtherUser = ctx.getPlayer(otherUser);
                if (playerOtherUser.isLocked()) {
                    ctx.sendLocalized("commands.daily.errors.receipt_locked");
                    return;
                }
                if (ctx.isUserBlacklisted(otherUser.getId())) {
                    ctx.sendLocalized("commands.transfer.blacklisted_transfer", EmoteReference.ERROR);
                    return;
                }
                // Why this is here I have no clue;;;
                dailyMoney += r.nextInt(90);
                var mentionedDBUser = ctx.getDBUser(otherUser.getId());
                var mentionedUserData = mentionedDBUser.getData();
                // Marriage bonus
                var marriage = authorUserData.getMarriage();
                if (marriage != null && otherUser.getId().equals(marriage.getOtherPlayer(ctx.getAuthor().getId())) && playerOtherUser.getInventory().containsItem(ItemReference.RING)) {
                    dailyMoney += Math.max(10, r.nextInt(100));
                }
                // Mutual waifu status.
                if (authorUserData.getWaifus().containsKey(otherUser.getId()) && mentionedUserData.getWaifus().containsKey(author.getId())) {
                    dailyMoney += Math.max(5, r.nextInt(100));
                }
                toAddMoneyTo = UnifiedPlayer.of(otherUser, ctx.getConfig().getCurrentSeason());
            } else {
                // This is here so you dont overwrite yourself....
                authorPlayer = toAddMoneyTo.getPlayer();
                authorPlayerData = authorPlayer.getData();
            }
            // Check for rate limit
            if (!RatelimitUtils.ratelimit(rateLimiter, ctx, languageContext.get("commands.daily.ratelimit_message"), false))
                return;
            List<String> returnMessage = new ArrayList<>();
            long currentTime = System.currentTimeMillis();
            int amountStreaksavers = authorPlayer.getInventory().getAmount(ItemReference.MAGIC_WATCH);
            // >=0 -> Valid  <0 -> Invalid
            long currentDailyOffset = DAILY_VALID_PERIOD_MILLIS - (currentTime - authorPlayerData.getLastDailyAt());
            long streak = authorPlayerData.getDailyStreak();
            var removedWatch = false;
            // Not expired?
            if (currentDailyOffset + amountStreaksavers * DAILY_VALID_PERIOD_MILLIS >= 0) {
                streak++;
                if (targetOther)
                    returnMessage.add(languageContext.get("commands.daily.streak.given.up").formatted(streak));
                else
                    returnMessage.add(languageContext.get("commands.daily.streak.up").formatted(streak));
                if (currentDailyOffset < 0) {
                    int streakSaversUsed = -1 * (int) Math.floor((double) currentDailyOffset / (double) DAILY_VALID_PERIOD_MILLIS);
                    authorPlayer.getInventory().process(new ItemStack(ItemReference.MAGIC_WATCH, streakSaversUsed * -1));
                    returnMessage.add(languageContext.get("commands.daily.streak.watch_used").formatted(streakSaversUsed, streakSaversUsed + 1, amountStreaksavers - streakSaversUsed));
                    removedWatch = true;
                }
            } else {
                if (streak == 0) {
                    returnMessage.add(languageContext.get("commands.daily.streak.first_time"));
                } else {
                    if (amountStreaksavers > 0) {
                        returnMessage.add(languageContext.get("commands.daily.streak.lost_streak.watch").formatted(streak));
                        authorPlayer.getInventory().process(new ItemStack(ItemReference.MAGIC_WATCH, authorPlayer.getInventory().getAmount(ItemReference.MAGIC_WATCH) * -1));
                        removedWatch = true;
                    } else {
                        returnMessage.add(languageContext.get("commands.daily.streak.lost_streak.normal").formatted(streak));
                    }
                }
                streak = 1;
            }
            if (streak > 5) {
                // Bonus money
                int bonus = 150;
                if (streak % 50 == 0) {
                    authorPlayer.getInventory().process(new ItemStack(ItemReference.MAGIC_WATCH, 1));
                    returnMessage.add(languageContext.get("commands.daily.watch_get"));
                }
                if (streak > 10) {
                    authorPlayerData.addBadgeIfAbsent(Badge.CLAIMER);
                    if (streak % 20 == 0 && authorPlayer.getInventory().getAmount(ItemReference.LOOT_CRATE) < 5000) {
                        authorPlayer.getInventory().process(new ItemStack(ItemReference.LOOT_CRATE, 1));
                        returnMessage.add(languageContext.get("commands.daily.crate"));
                    }
                    if (streak > 15) {
                        bonus += Math.min(targetOther ? 1700 : 700, Math.floor(150 * streak / (targetOther ? 10D : 15D)));
                        if (streak >= 180) {
                            authorPlayerData.addBadgeIfAbsent(Badge.BIG_CLAIMER);
                        }
                        if (streak >= 365) {
                            authorPlayerData.addBadgeIfAbsent(Badge.YEARLY_CLAIMER);
                        }
                        if (streak >= 730) {
                            authorPlayerData.addBadgeIfAbsent(Badge.BI_YEARLY_CLAIMER);
                        }
                    }
                }
                if (targetOther) {
                    returnMessage.add(languageContext.get("commands.daily.streak.given.bonus").formatted(otherUser.getName(), bonus));
                } else {
                    returnMessage.add(languageContext.get("commands.daily.streak.bonus").formatted(bonus));
                }
                dailyMoney += bonus;
            }
            // If the author is premium, make daily double.
            if (authorDBUser.isPremium()) {
                dailyMoney *= 2;
            }
            // Sellout + this is always a day apart, so we can just send campaign.
            if (r.nextBoolean()) {
                returnMessage.add(Campaign.TWITTER.getStringFromCampaign(languageContext, true));
            } else {
                returnMessage.add(Campaign.PREMIUM_DAILY.getStringFromCampaign(languageContext, authorDBUser.isPremium()));
            }
            // Careful not to overwrite yourself ;P
            // Save streak and items
            authorPlayerData.setLastDailyAt(currentTime);
            authorPlayerData.setDailyStreak(streak);
            // toAdd is the unified player as referenced
            if (targetOther) {
                authorPlayer.save();
            }
            toAddMoneyTo.addMoney(dailyMoney);
            if (removedWatch) {
                toAddMoneyTo.save();
            } else {
                // We can sort of avoid doing a full save here.
                // Since updating the fields is just fine unless we're removing something from a Map.
                // It's still annoying.
                toAddMoneyTo.saveUpdating();
            }
            // Build Message
            var toSend = new StringBuilder((targetOther ? languageContext.get("commands.daily.given_credits").formatted(EmoteReference.CORRECT, dailyMoney, otherUser.getName()) : languageContext.get("commands.daily.credits").formatted(EmoteReference.CORRECT, dailyMoney)) + "\n");
            for (var string : returnMessage) {
                toSend.append("\n").append(string);
            }
            // Send Message
            ctx.send(toSend.toString());
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Gives you $150 credits per day (or between 150 and 180 if you transfer it to another person). " + "Maximum amount it can give is ~2000 credits (a bit more for shared dailies)\n" + "This command gives a reward for claiming it every day (daily streak)").setUsage("`~>daily [@user] [-check]`").addParameterOptional("@user", "The user to give your daily to, without this it gives it to yourself.").addParameterOptional("-check", "Check the time left for you to be able to claim it.").build();
        }
    });
    cr.registerAlias("daily", "dailies");
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) User(net.dv8tion.jda.api.entities.User) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) IncreasingRateLimiter(net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter) UnifiedPlayer(net.kodehawa.mantarobot.commands.currency.seasons.helpers.UnifiedPlayer) Random(java.util.Random) SecureRandom(java.security.SecureRandom) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) ArrayList(java.util.ArrayList) List(java.util.List) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Context (net.kodehawa.mantarobot.core.modules.commands.base.Context)20 HelpContent (net.kodehawa.mantarobot.core.modules.commands.help.HelpContent)18 Subscribe (com.google.common.eventbus.Subscribe)17 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)16 MantaroData (net.kodehawa.mantarobot.data.MantaroData)15 CommandCategory (net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory)14 I18nContext (net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext)14 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)13 Module (net.kodehawa.mantarobot.core.modules.Module)13 Utils (net.kodehawa.mantarobot.utils.Utils)13 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)12 IncreasingRateLimiter (net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter)12 List (java.util.List)11 TimeUnit (java.util.concurrent.TimeUnit)11 Collectors (java.util.stream.Collectors)11 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)11 RatelimitUtils (net.kodehawa.mantarobot.utils.commands.ratelimit.RatelimitUtils)10 Badge (net.kodehawa.mantarobot.commands.currency.profile.Badge)9 DiscordUtils (net.kodehawa.mantarobot.utils.commands.DiscordUtils)9 Color (java.awt.Color)8