Search in sources :

Example 6 with User

use of net.dv8tion.jda.api.entities.User 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)

Example 7 with User

use of net.dv8tion.jda.api.entities.User in project MantaroBot by Mantaro.

the class MoneyCmds method balance.

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

        @Override
        protected void call(Context ctx, String content, String[] args) {
            var optionalArguments = ctx.getOptionalArguments();
            content = Utils.replaceArguments(optionalArguments, content, "season", "s").trim();
            var isSeasonal = optionalArguments.containsKey("season") || optionalArguments.containsKey("s");
            var languageContext = ctx.getLanguageContext();
            // Values on lambdas should be final or effectively final part 9999.
            final var finalContent = content;
            ctx.findMember(content, members -> {
                var user = ctx.getAuthor();
                boolean isExternal = false;
                var found = CustomFinderUtil.findMemberDefault(finalContent, members, ctx, ctx.getMember());
                if (found == null) {
                    return;
                } else if (!finalContent.isEmpty()) {
                    user = found.getUser();
                    isExternal = true;
                }
                if (user.isBot()) {
                    ctx.sendLocalized("commands.balance.bot_notice", EmoteReference.ERROR);
                    return;
                }
                var player = ctx.getPlayer(user);
                var playerData = player.getData();
                var balance = isSeasonal ? ctx.getSeasonPlayer(user).getMoney() : player.getCurrentMoney();
                var extra = "";
                if (!playerData.isResetWarning() && !ctx.getConfig().isPremiumBot() && ctx.getPlayer().getOldMoney() > 10_000) {
                    extra = languageContext.get("commands.balance.reset_notice");
                    playerData.setResetWarning(true);
                    player.saveUpdating();
                }
                if (balance < 300 && playerData.getExperience() < 3400 && !playerData.isNewPlayerNotice()) {
                    extra += (extra.isEmpty() ? "" : "\n") + languageContext.get("commands.balance.new_player");
                    playerData.setNewPlayerNotice(true);
                    player.saveUpdating();
                }
                var message = String.format(Utils.getLocaleFromLanguage(ctx.getLanguageContext()), languageContext.withRoot("commands", "balance.own_balance"), balance, extra);
                if (isExternal) {
                    message = String.format(Utils.getLocaleFromLanguage(ctx.getLanguageContext()), languageContext.withRoot("commands", "balance.external_balance"), user.getName(), balance);
                }
                ctx.send(EmoteReference.CREDITCARD + message);
            });
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Shows your current balance or another person's balance.").setUsage("`~>balance [@user]`").addParameter("@user", "The user to check the balance of. This is optional.").setSeasonal(true).build();
        }
    });
    cr.registerAlias("balance", "credits");
    cr.registerAlias("balance", "bal");
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Module(net.kodehawa.mantarobot.core.modules.Module) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) Utils(net.kodehawa.mantarobot.utils.Utils) Random(java.util.Random) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) SecureRandom(java.security.SecureRandom) CustomFinderUtil(net.kodehawa.mantarobot.utils.commands.CustomFinderUtil) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Button(net.dv8tion.jda.api.interactions.components.Button) Campaign(net.kodehawa.mantarobot.utils.commands.campaign.Campaign) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) ItemReference(net.kodehawa.mantarobot.commands.currency.item.ItemReference) Month(java.time.Month) IncreasingRateLimiter(net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter) UnifiedPlayer(net.kodehawa.mantarobot.commands.currency.seasons.helpers.UnifiedPlayer) ZoneId(java.time.ZoneId) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) RatelimitUtils(net.kodehawa.mantarobot.utils.commands.ratelimit.RatelimitUtils) CommandCategory(net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) LocalDate(java.time.LocalDate) MantaroData(net.kodehawa.mantarobot.data.MantaroData) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) Subscribe(com.google.common.eventbus.Subscribe)

Example 8 with User

use of net.dv8tion.jda.api.entities.User in project MantaroBot by Mantaro.

the class LogUtils method spambot.

public static void spambot(User user, String guildId, String channelId, String messageId, SpamType type) {
    if (SPAMBOT_WEBHOOK == null) {
        log.warn("---- Spambot detected! ID: {}, Reason: {}", user.getId(), type);
        return;
    }
    try {
        List<WebhookEmbed.EmbedField> fields = new ArrayList<>();
        fields.add(new WebhookEmbed.EmbedField(false, "Tag", String.format("%#s", user)));
        fields.add(new WebhookEmbed.EmbedField(true, "ID", user.getId()));
        fields.add(new WebhookEmbed.EmbedField(true, "Guild ID", guildId));
        fields.add(new WebhookEmbed.EmbedField(true, "Channel ID", channelId));
        fields.add(new WebhookEmbed.EmbedField(true, "Message ID", messageId));
        fields.add(new WebhookEmbed.EmbedField(true, "Account Creation", user.getTimeCreated().toString()));
        fields.add(new WebhookEmbed.EmbedField(true, "Mutual Guilds", user.getMutualGuilds().stream().map(g -> g.getId() + ": " + g.getMemberCount() + " members").collect(Collectors.joining("\n"))));
        fields.add(new WebhookEmbed.EmbedField(false, "Type", type.toString()));
        if (type == SpamType.BLATANT) {
            var mantaroData = MantaroData.db().getMantaroData();
            mantaroData.getBlackListedUsers().add(user.getId());
            mantaroData.save();
            fields.add(new WebhookEmbed.EmbedField(false, "Info", "User has been blacklisted automatically. " + "For more information use the investigate command."));
        }
        SPAMBOT_WEBHOOK.send(new WebhookEmbed(null, Color.PINK.getRGB(), null, user.getEffectiveAvatarUrl(), null, new WebhookEmbed.EmbedFooter(Utils.formatDate(OffsetDateTime.now()), ICON_URL), new WebhookEmbed.EmbedTitle("Possible spambot detected", null), null, fields));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : Color(java.awt.Color) Logger(org.slf4j.Logger) WebhookClient(club.minnced.discord.webhook.WebhookClient) Utils(net.kodehawa.mantarobot.utils.Utils) LoggerFactory(org.slf4j.LoggerFactory) Collectors(java.util.stream.Collectors) User(net.dv8tion.jda.api.entities.User) ArrayList(java.util.ArrayList) List(java.util.List) OffsetDateTime(java.time.OffsetDateTime) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) MantaroData(net.kodehawa.mantarobot.data.MantaroData) WebhookClientBuilder(club.minnced.discord.webhook.WebhookClientBuilder) WebhookEmbed(club.minnced.discord.webhook.send.WebhookEmbed) ArrayList(java.util.ArrayList)

Example 9 with User

use of net.dv8tion.jda.api.entities.User in project MantaroBot by Mantaro.

the class CachedMessage method getAuthor.

public User getAuthor() {
    var guild = MantaroBot.getInstance().getShardManager().getGuildById(guildId);
    User user = null;
    if (guild != null) {
        user = guild.retrieveMemberById(author).complete().getUser();
    }
    return user;
}
Also used : User(net.dv8tion.jda.api.entities.User)

Aggregations

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