Search in sources :

Example 6 with IncreasingRateLimiter

use of net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter 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 7 with IncreasingRateLimiter

use of net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter 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

Subscribe (com.google.common.eventbus.Subscribe)7 Context (net.kodehawa.mantarobot.core.modules.commands.base.Context)7 HelpContent (net.kodehawa.mantarobot.core.modules.commands.help.HelpContent)7 IncreasingRateLimiter (net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter)7 List (java.util.List)5 TimeUnit (java.util.concurrent.TimeUnit)5 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)5 Module (net.kodehawa.mantarobot.core.modules.Module)5 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)5 CommandCategory (net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory)5 I18nContext (net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext)5 MantaroData (net.kodehawa.mantarobot.data.MantaroData)5 Utils (net.kodehawa.mantarobot.utils.Utils)5 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)5 RatelimitUtils (net.kodehawa.mantarobot.utils.commands.ratelimit.RatelimitUtils)5 EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)4 User (net.dv8tion.jda.api.entities.User)4 Badge (net.kodehawa.mantarobot.commands.currency.profile.Badge)4 SubCommand (net.kodehawa.mantarobot.core.modules.commands.SubCommand)4 Command (net.kodehawa.mantarobot.core.modules.commands.base.Command)4