Search in sources :

Example 16 with Context

use of net.kodehawa.mantarobot.core.modules.commands.base.Context 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 17 with Context

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

the class MusicUtilCmds method skipahead.

@Subscribe
public void skipahead(CommandRegistry cr) {
    cr.register("forward", new SimpleCommand(CommandCategory.MUSIC) {

        @Override
        protected void call(Context ctx, String content, String[] args) {
            if (args.length == 0) {
                ctx.sendLocalized("commands.skipahead.no_time", EmoteReference.ERROR);
                return;
            }
            var manager = ctx.getAudioManager().getMusicManager(ctx.getGuild());
            var lavalinkPlayer = manager.getLavaLink().getPlayer();
            if (lavalinkPlayer.getPlayingTrack() == null) {
                ctx.sendLocalized("commands.music_general.not_playing", EmoteReference.ERROR);
                return;
            }
            if (isSongOwner(manager.getTrackScheduler(), ctx.getAuthor()) || isDJ(ctx, ctx.getMember())) {
                try {
                    var amt = Utils.parseTime(args[0]);
                    if (amt < 0) {
                        // same as in rewind here
                        ctx.sendLocalized("commands.rewind.negative", EmoteReference.ERROR);
                        return;
                    }
                    if (amt < 1000) {
                        ctx.sendLocalized("commands.rewind.too_little", EmoteReference.ERROR);
                        return;
                    }
                    var track = lavalinkPlayer.getPlayingTrack();
                    var position = lavalinkPlayer.getTrackPosition();
                    if (position + amt > track.getDuration()) {
                        ctx.sendLocalized("commands.skipahead.past_duration", EmoteReference.ERROR);
                        return;
                    }
                    lavalinkPlayer.seekTo(position + amt);
                    ctx.sendLocalized("commands.skipahead.success", EmoteReference.CORRECT, AudioCmdUtils.getDurationMinutes(position + amt));
                } catch (NumberFormatException ex) {
                    ctx.sendLocalized("general.invalid_number", EmoteReference.ERROR);
                }
            } else {
                ctx.sendLocalized("commands.music_general.dj_only", EmoteReference.ERROR);
            }
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Fast forwards the current song a specified amount of time.").setUsage("~>forward <time>").addParameter("time", "The amount of minutes to rewind. Time is in this format: 1m29s (1 minute and 29s), for example.").build();
        }
    });
    cr.registerAlias("forward", "skipahead");
    cr.registerAlias("forward", "seek");
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) Subscribe(com.google.common.eventbus.Subscribe)

Example 18 with Context

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

the class ProfileCmd method profile.

@Subscribe
public void profile(CommandRegistry cr) {
    final var rateLimiter = new IncreasingRateLimiter.Builder().limit(// twice every 10m
    2).spamTolerance(2).cooldown(10, TimeUnit.MINUTES).cooldownPenaltyIncrease(10, TimeUnit.SECONDS).maxCooldown(15, TimeUnit.MINUTES).pool(MantaroData.getDefaultJedisPool()).prefix("profile").build();
    final var config = MantaroData.config().get();
    List<ProfileComponent> defaultOrder;
    if (config.isPremiumBot() || config.isSelfHost()) {
        defaultOrder = createLinkedList(HEADER, CREDITS, LEVEL, REPUTATION, BIRTHDAY, MARRIAGE, INVENTORY, BADGES, PET);
    } else {
        defaultOrder = createLinkedList(HEADER, CREDITS, OLD_CREDITS, LEVEL, REPUTATION, BIRTHDAY, MARRIAGE, INVENTORY, BADGES, PET);
    }
    List<ProfileComponent> noOldOrder = createLinkedList(HEADER, CREDITS, LEVEL, REPUTATION, BIRTHDAY, MARRIAGE, INVENTORY, BADGES, PET);
    TreeCommand profileCommand = cr.register("profile", new TreeCommand(CommandCategory.CURRENCY) {

        @Override
        public Command defaultTrigger(Context ctx, String mainCommand, String commandName) {
            return new SubCommand() {

                @Override
                protected void call(Context ctx, I18nContext languageContext, String content) {
                    var optionalArguments = ctx.getOptionalArguments();
                    content = Utils.replaceArguments(optionalArguments, content, "season", "s").trim();
                    var isSeasonal = ctx.isSeasonal();
                    var finalContent = content;
                    ctx.findMember(content, members -> {
                        SeasonPlayer seasonalPlayer = null;
                        var userLooked = ctx.getAuthor();
                        var memberLooked = ctx.getMember();
                        if (!finalContent.isEmpty()) {
                            var found = CustomFinderUtil.findMember(finalContent, members, ctx);
                            if (found == null) {
                                return;
                            }
                            userLooked = found.getUser();
                            memberLooked = found;
                        }
                        if (userLooked.isBot()) {
                            ctx.sendLocalized("commands.profile.bot_notice", EmoteReference.ERROR);
                            return;
                        }
                        var player = ctx.getPlayer(userLooked);
                        var dbUser = ctx.getDBUser(userLooked);
                        var playerData = player.getData();
                        var userData = dbUser.getData();
                        var inv = player.getInventory();
                        // Cache waifu value.
                        playerData.setWaifuCachedValue(WaifuCmd.calculateWaifuValue(player, userLooked).getFinalValue());
                        // start of badge assigning
                        var mh = MantaroBot.getInstance().getShardManager().getGuildById("213468583252983809");
                        var mhMember = mh == null ? null : ctx.retrieveMemberById(memberLooked.getUser().getId(), false);
                        Badge.assignBadges(player, player.getStats(), dbUser);
                        var christmasBadgeAssign = inv.asList().stream().map(ItemStack::getItem).anyMatch(it -> it.equals(ItemReference.CHRISTMAS_TREE_SPECIAL) || it.equals(ItemReference.BELL_SPECIAL));
                        // Manual badges
                        if (config.isOwner(userLooked)) {
                            playerData.addBadgeIfAbsent(Badge.DEVELOPER);
                        }
                        if (christmasBadgeAssign) {
                            playerData.addBadgeIfAbsent(Badge.CHRISTMAS);
                        }
                        // Requires a valid Member in Mantaro Hub.
                        if (mhMember != null) {
                            // Admin
                            if (containsRole(mhMember, 315910951994130432L, 642089477828902912L)) {
                                playerData.addBadgeIfAbsent(Badge.COMMUNITY_ADMIN);
                            }
                            // Patron - Donator
                            if (containsRole(mhMember, 290902183300431872L, 290257037072531466L)) {
                                playerData.addBadgeIfAbsent(Badge.DONATOR_2);
                            }
                            // Translator
                            if (containsRole(mhMember, 407156441812828162L)) {
                                playerData.addBadgeIfAbsent(Badge.TRANSLATOR);
                            }
                        }
                        // end of badge assigning
                        var badges = playerData.getBadges();
                        Collections.sort(badges);
                        if (isSeasonal) {
                            seasonalPlayer = ctx.getSeasonPlayer(userLooked);
                        }
                        var marriage = ctx.getMarriage(userData);
                        var ringHolder = player.getInventory().containsItem(ItemReference.RING) && marriage != null;
                        var holder = new ProfileComponent.Holder(userLooked, player, seasonalPlayer, dbUser, marriage, badges);
                        var profileBuilder = new EmbedBuilder();
                        var description = languageContext.get("commands.profile.no_desc");
                        if (playerData.getDescription() != null) {
                            description = player.getData().getDescription();
                        }
                        profileBuilder.setAuthor((ringHolder ? EmoteReference.RING : "") + String.format(languageContext.get("commands.profile.header"), memberLooked.getEffectiveName()), null, userLooked.getEffectiveAvatarUrl()).setDescription(description).setThumbnail(userLooked.getEffectiveAvatarUrl()).setColor(ctx.getMemberColor(memberLooked)).setFooter(ProfileComponent.FOOTER.getContent().apply(holder, languageContext), ctx.getAuthor().getEffectiveAvatarUrl());
                        var hasCustomOrder = dbUser.isPremium() && !playerData.getProfileComponents().isEmpty();
                        var usedOrder = hasCustomOrder ? playerData.getProfileComponents() : defaultOrder;
                        if ((!config.isPremiumBot() && player.getOldMoney() < 5000 && !hasCustomOrder) || (playerData.isHiddenLegacy() && !hasCustomOrder)) {
                            usedOrder = noOldOrder;
                        }
                        for (var component : usedOrder) {
                            profileBuilder.addField(component.getTitle(languageContext), component.getContent().apply(holder, languageContext), component.isInline());
                        }
                        ctx.send(profileBuilder.build());
                        // We don't need to update stats if someone else views your profile
                        if (player.getUserId().equals(ctx.getAuthor().getId())) {
                            player.saveUpdating();
                        }
                    });
                }
            };
        }

        // If you wonder why is this so short compared to before, subcommand descriptions will do the trick on telling me what they do.
        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Retrieves your current user profile.").setUsage("To retrieve your profile use `~>profile`. You can also use `~>profile @mention`\n" + "*The profile command only shows the 5 most important badges.* Use `~>badges` to get a complete list!").addParameter("@mention", "A user mention (ping)").setSeasonal(true).build();
        }
    });
    profileCommand.setPredicate(ctx -> {
        if (!ctx.getSelfMember().hasPermission(ctx.getChannel(), Permission.MESSAGE_EMBED_LINKS)) {
            ctx.sendLocalized("general.missing_embed_permissions");
            return false;
        }
        return true;
    });
    profileCommand.addSubCommand("toggleaction", new SubCommand() {

        @Override
        public String description() {
            return "Toggles the ability to do action commands to you.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            final var dbUser = ctx.getDBUser();
            final var userData = dbUser.getData();
            final var isDisabled = userData.isActionsDisabled();
            if (isDisabled) {
                userData.setActionsDisabled(false);
                ctx.sendLocalized("commands.profile.toggleaction.enabled", EmoteReference.CORRECT);
            } else {
                userData.setActionsDisabled(true);
                ctx.sendLocalized("commands.profile.toggleaction.disabled", EmoteReference.CORRECT);
            }
            dbUser.save();
        }
    });
    profileCommand.addSubCommand("claimlock", new SubCommand() {

        @Override
        public String description() {
            return "Locks you from being claimed. Use `remove` to remove it.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            final var player = ctx.getPlayer();
            final var playerData = player.getData();
            if (content.equals("remove")) {
                playerData.setClaimLocked(false);
                ctx.sendLocalized("commands.profile.claimlock.removed", EmoteReference.CORRECT);
                player.saveUpdating();
                return;
            }
            if (playerData.isClaimLocked()) {
                ctx.sendLocalized("commands.profile.claimlock.already_locked", EmoteReference.CORRECT);
                return;
            }
            var inventory = player.getInventory();
            if (!inventory.containsItem(ItemReference.CLAIM_KEY)) {
                ctx.sendLocalized("commands.profile.claimlock.no_key", EmoteReference.ERROR);
                return;
            }
            playerData.setClaimLocked(true);
            ctx.sendLocalized("commands.profile.claimlock.success", EmoteReference.CORRECT);
            inventory.process(new ItemStack(ItemReference.CLAIM_KEY, -1));
            player.saveUpdating();
        }
    });
    if (!config.isPremiumBot()) {
        profileCommand.addSubCommand("togglelegacy", new SubCommand() {

            @Override
            public String description() {
                return "Toggles legacy credit display.";
            }

            @Override
            protected void call(Context ctx, I18nContext languageContext, String content) {
                final var player = ctx.getPlayer();
                final var data = player.getData();
                var toSet = !data.isHiddenLegacy();
                data.setHiddenLegacy(toSet);
                player.saveUpdating();
                ctx.sendLocalized("commands.profile.hidelegacy", EmoteReference.CORRECT, data.isHiddenLegacy());
            }
        });
    }
    profileCommand.addSubCommand("inventorysort", new SubCommand() {

        @Override
        public String description() {
            return "Sort your inventory. Possible values: `VALUE, VALUE_TOTAL, AMOUNT, TYPE, RANDOM`.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            final var type = Utils.lookupEnumString(content, InventorySortType.class);
            if (type == null) {
                ctx.sendLocalized("commands.profile.inventorysort.not_valid", EmoteReference.ERROR, Arrays.stream(InventorySortType.values()).map(b1 -> b1.toString().toLowerCase()).collect(Collectors.joining(", ")));
                return;
            }
            final var player = ctx.getPlayer();
            final var playerData = player.getData();
            playerData.setInventorySortType(type);
            player.saveUpdating();
            ctx.sendLocalized("commands.profile.inventorysort.success", EmoteReference.CORRECT, type.toString().toLowerCase());
        }
    });
    profileCommand.addSubCommand("autoequip", new SubCommand() {

        @Override
        public String description() {
            return "Toggles auto-equipping a new tool on break. Use `disable` to disable it.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var user = ctx.getDBUser();
            var data = user.getData();
            if (content.equals("disable")) {
                data.setAutoEquip(false);
                ctx.sendLocalized("commands.profile.autoequip.disable", EmoteReference.CORRECT);
                user.saveUpdating();
                return;
            }
            data.setAutoEquip(true);
            ctx.sendLocalized("commands.profile.autoequip.success", EmoteReference.CORRECT);
            user.saveUpdating();
        }
    });
    // Hide tags from profile/waifu list.
    profileCommand.addSubCommand("hidetag", new SubCommand() {

        @Override
        public String description() {
            return "Hide or show the member id/tag from profile/waifu ls.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var user = ctx.getDBUser();
            var data = user.getData();
            data.setPrivateTag(!data.isPrivateTag());
            user.saveUpdating();
            ctx.sendLocalized("commands.profile.hide_tag.success", EmoteReference.POPPER, data.isPrivateTag());
        }
    });
    profileCommand.addSubCommand("timezone", new SubCommand() {

        @Override
        public String description() {
            return "Set your profile timezone.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var dbUser = ctx.getDBUser();
            var args = ctx.getArguments();
            if (args.length < 1) {
                ctx.sendLocalized("commands.profile.timezone.not_specified", EmoteReference.ERROR);
                return;
            }
            var timezone = content;
            if (offsetRegex.matcher(timezone).matches()) {
                timezone = content.toUpperCase().replace("UTC", "GMT");
            }
            // EST, EDT, etc...
            if (timezone.length() == 3) {
                timezone = timezone.toUpperCase();
            }
            if (timezone.equalsIgnoreCase("reset")) {
                dbUser.getData().setTimezone(null);
                dbUser.saveAsync();
                ctx.sendLocalized("commands.profile.timezone.reset_success", EmoteReference.CORRECT);
                return;
            }
            if (!Utils.isValidTimeZone(timezone)) {
                ctx.sendLocalized("commands.profile.timezone.invalid", EmoteReference.ERROR);
                return;
            }
            try {
                Utils.formatDate(LocalDateTime.now(Utils.timezoneToZoneID(timezone)), dbUser.getData().getLang());
            } catch (DateTimeException e) {
                ctx.sendLocalized("commands.profile.timezone.invalid", EmoteReference.ERROR);
                return;
            }
            var player = ctx.getPlayer();
            if (player.getData().addBadgeIfAbsent(Badge.CALENDAR)) {
                player.saveUpdating();
            }
            dbUser.getData().setTimezone(timezone);
            dbUser.saveUpdating();
            ctx.sendLocalized("commands.profile.timezone.success", EmoteReference.CORRECT, timezone);
        }
    });
    profileCommand.addSubCommand("description", new SubCommand() {

        @Override
        public String description() {
            return "Set your profile description. Use `reset` to reset it.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            if (!RatelimitUtils.ratelimit(rateLimiter, ctx)) {
                return;
            }
            var args = ctx.getArguments();
            var player = ctx.getPlayer();
            var dbUser = ctx.getDBUser();
            if (args.length == 0) {
                ctx.sendLocalized("commands.profile.description.no_argument", EmoteReference.ERROR);
                return;
            }
            if (args[0].equals("clear") || args[0].equals("remove") || args[0].equals("reset")) {
                player.getData().setDescription(null);
                ctx.sendLocalized("commands.profile.description.clear_success", EmoteReference.CORRECT);
                player.saveUpdating();
                return;
            }
            var split = SPLIT_PATTERN.split(content, 2);
            var desc = content;
            var old = false;
            if (split[0].equals("set")) {
                desc = content.replaceFirst("set ", "");
                old = true;
            }
            var MAX_LENGTH = 300;
            if (dbUser.isPremium()) {
                MAX_LENGTH = 500;
            }
            if (args.length < (old ? 2 : 1)) {
                ctx.sendLocalized("commands.profile.description.no_content", EmoteReference.ERROR);
                return;
            }
            if (desc.length() > MAX_LENGTH) {
                ctx.sendLocalized("commands.profile.description.too_long", EmoteReference.ERROR);
                return;
            }
            desc = Utils.DISCORD_INVITE.matcher(desc).replaceAll("-discord invite link-");
            desc = Utils.DISCORD_INVITE_2.matcher(desc).replaceAll("-discord invite link-");
            player.getData().setDescription(desc);
            ctx.sendStrippedLocalized("commands.profile.description.success", EmoteReference.POPPER);
            player.getData().addBadgeIfAbsent(Badge.WRITER);
            player.saveUpdating();
        }
    });
    profileCommand.addSubCommand("displaybadge", new SubCommand() {

        @Override
        public String description() {
            return "Set your profile badge. Use `reset` to reset and `none` to show no badge.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var args = ctx.getArguments();
            if (args.length == 0) {
                ctx.sendLocalized("commands.profile.displaybadge.not_specified", EmoteReference.ERROR);
                return;
            }
            var player = ctx.getPlayer();
            var data = player.getData();
            var arg = args[0];
            if (arg.equalsIgnoreCase("none")) {
                data.setShowBadge(false);
                ctx.sendLocalized("commands.profile.displaybadge.reset_success", EmoteReference.CORRECT);
                player.saveUpdating();
                return;
            }
            if (arg.equalsIgnoreCase("reset")) {
                data.setMainBadge(null);
                data.setShowBadge(true);
                ctx.sendLocalized("commands.profile.displaybadge.important_success", EmoteReference.CORRECT);
                player.saveUpdating();
                return;
            }
            var badge = Badge.lookupFromString(content);
            if (badge == null) {
                ctx.sendLocalized("commands.profile.displaybadge.no_such_badge", EmoteReference.ERROR, player.getData().getBadges().stream().map(Badge::getDisplay).collect(Collectors.joining(", ")));
                return;
            }
            if (!data.getBadges().contains(badge)) {
                ctx.sendLocalized("commands.profile.displaybadge.player_missing_badge", EmoteReference.ERROR, player.getData().getBadges().stream().map(Badge::getDisplay).collect(Collectors.joining(", ")));
                return;
            }
            data.setShowBadge(true);
            data.setMainBadge(badge);
            player.saveUpdating();
            ctx.sendLocalized("commands.profile.displaybadge.success", EmoteReference.CORRECT, badge.display);
        }
    });
    profileCommand.addSubCommand("language", new SubCommand() {

        @Override
        public String description() {
            return "Set your profile language. Available langs: `~>lang`";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            if (content.isEmpty()) {
                ctx.sendLocalized("commands.profile.lang.nothing_specified", EmoteReference.ERROR);
                return;
            }
            var dbUser = ctx.getDBUser();
            if (content.equalsIgnoreCase("reset")) {
                dbUser.getData().setLang(null);
                dbUser.saveUpdating();
                ctx.sendLocalized("commands.profile.lang.reset_success", EmoteReference.CORRECT);
                return;
            }
            if (I18n.isValidLanguage(content)) {
                dbUser.getData().setLang(content);
                // Create new I18n context based on the new language choice.
                var newContext = new I18nContext(ctx.getDBGuild().getData(), dbUser.getData());
                dbUser.saveUpdating();
                ctx.getChannel().sendMessageFormat(newContext.get("commands.profile.lang.success"), EmoteReference.CORRECT, content).queue();
            } else {
                ctx.sendLocalized("commands.profile.lang.invalid", EmoteReference.ERROR);
            }
        }
    }).createSubCommandAlias("language", "lang");
    profileCommand.addSubCommand("stats", new SubCommand() {

        @Override
        public String description() {
            return "Check profile statistics.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            ctx.findMember(content, members -> {
                var member = CustomFinderUtil.findMemberDefault(content, members, ctx, ctx.getMember());
                if (member == null) {
                    return;
                }
                var toLookup = member.getUser();
                if (toLookup.isBot()) {
                    ctx.sendLocalized("commands.profile.bot_notice", EmoteReference.ERROR);
                    return;
                }
                var player = ctx.getPlayer(toLookup);
                var dbUser = ctx.getDBUser(toLookup);
                List<MessageEmbed.Field> fields = new LinkedList<>();
                for (StatsComponent component : StatsComponent.values()) {
                    fields.add(new MessageEmbed.Field(component.getEmoji() + component.getName(ctx), component.getContent(new StatsComponent.Holder(ctx, languageContext, player, dbUser, toLookup)), false));
                }
                var splitFields = DiscordUtils.divideFields(9, fields);
                var embed = new EmbedBuilder().setThumbnail(toLookup.getEffectiveAvatarUrl()).setAuthor(languageContext.get("commands.profile.stats.header").formatted(toLookup.getName()), null, toLookup.getEffectiveAvatarUrl()).setDescription(String.format(languageContext.get("general.buy_sell_paged_react"), String.format(languageContext.get("general.reaction_timeout"), 200))).setColor(ctx.getMemberColor()).setFooter("Thanks for using Mantaro! %s".formatted(EmoteReference.HEART), ctx.getGuild().getIconUrl());
                DiscordUtils.listButtons(ctx, 200, embed, splitFields);
            });
        }
    });
    profileCommand.addSubCommand("widgets", new SubCommand() {

        @Override
        public String description() {
            return "Set profile widgets and order. Arguments: `widget`, `ls` or `reset`";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var user = ctx.getDBUser();
            if (!user.isPremium()) {
                ctx.sendLocalized("commands.profile.display.not_premium", EmoteReference.ERROR);
                return;
            }
            var player = ctx.getPlayer();
            var playerData = player.getData();
            if (content.equalsIgnoreCase("ls") || content.equalsIgnoreCase("Is")) {
                ctx.sendFormat(languageContext.get("commands.profile.display.ls") + languageContext.get("commands.profile.display.example"), EmoteReference.ZAP, EmoteReference.BLUE_SMALL_MARKER, defaultOrder.stream().map(Enum::name).collect(Collectors.joining(", ")), playerData.getProfileComponents().size() == 0 ? "Not personalized" : playerData.getProfileComponents().stream().map(Enum::name).collect(Collectors.joining(", ")));
                return;
            }
            if (content.equalsIgnoreCase("reset")) {
                playerData.getProfileComponents().clear();
                player.save();
                ctx.sendLocalized("commands.profile.display.reset", EmoteReference.CORRECT);
                return;
            }
            var splitContent = content.replace(",", "").split("\\s+");
            // new list of profile components
            List<ProfileComponent> newComponents = new LinkedList<>();
            for (var cmt : splitContent) {
                var component = ProfileComponent.lookupFromString(cmt);
                if (component != null && component.isAssignable()) {
                    newComponents.add(component);
                }
            }
            if (newComponents.size() < 3) {
                ctx.sendFormat(languageContext.get("commands.profile.display.not_enough") + languageContext.get("commands.profile.display.example"), EmoteReference.WARNING);
                return;
            }
            playerData.setProfileComponents(newComponents);
            player.save();
            ctx.sendLocalized("commands.profile.display.success", EmoteReference.CORRECT, newComponents.stream().map(Enum::name).collect(Collectors.joining(", ")));
        }
    });
    cr.registerAlias("profile", "me");
}
Also used : Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) StatsComponent(net.kodehawa.mantarobot.commands.currency.profile.StatsComponent) Module(net.kodehawa.mantarobot.core.modules.Module) Arrays(java.util.Arrays) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) Permission(net.dv8tion.jda.api.Permission) Utils(net.kodehawa.mantarobot.utils.Utils) LocalDateTime(java.time.LocalDateTime) Member(net.dv8tion.jda.api.entities.Member) SeasonPlayer(net.kodehawa.mantarobot.commands.currency.seasons.SeasonPlayer) MantaroBot(net.kodehawa.mantarobot.MantaroBot) CustomFinderUtil(net.kodehawa.mantarobot.utils.commands.CustomFinderUtil) PlayerEquipment(net.kodehawa.mantarobot.commands.currency.item.PlayerEquipment) Role(net.dv8tion.jda.api.entities.Role) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.createLinkedList(net.kodehawa.mantarobot.utils.Utils.createLinkedList) Subscribe(com.google.common.eventbus.Subscribe) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) LinkedList(java.util.LinkedList) ItemHelper(net.kodehawa.mantarobot.commands.currency.item.ItemHelper) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) DateTimeException(java.time.DateTimeException) DiscordUtils(net.kodehawa.mantarobot.utils.commands.DiscordUtils) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) I18n(net.kodehawa.mantarobot.data.I18n) ItemReference(net.kodehawa.mantarobot.commands.currency.item.ItemReference) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) IncreasingRateLimiter(net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter) ProfileComponent(net.kodehawa.mantarobot.commands.currency.profile.ProfileComponent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) Breakable(net.kodehawa.mantarobot.commands.currency.item.special.helpers.Breakable) List(java.util.List) RatelimitUtils(net.kodehawa.mantarobot.utils.commands.ratelimit.RatelimitUtils) CommandCategory(net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) InventorySortType(net.kodehawa.mantarobot.commands.currency.profile.inventory.InventorySortType) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Pattern(java.util.regex.Pattern) Collections(java.util.Collections) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ProfileComponent(net.kodehawa.mantarobot.commands.currency.profile.ProfileComponent) StatsComponent(net.kodehawa.mantarobot.commands.currency.profile.StatsComponent) DateTimeException(java.time.DateTimeException) Utils.createLinkedList(net.kodehawa.mantarobot.utils.Utils.createLinkedList) LinkedList(java.util.LinkedList) List(java.util.List) SeasonPlayer(net.kodehawa.mantarobot.commands.currency.seasons.SeasonPlayer) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) InventorySortType(net.kodehawa.mantarobot.commands.currency.profile.inventory.InventorySortType) Subscribe(com.google.common.eventbus.Subscribe)

Example 19 with Context

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

the class ItemHelper method openLootBox.

private static void openLootBox(Context ctx, Player player, SeasonPlayer seasonPlayer, ItemType.LootboxType type, Item crate, EmoteReference typeEmote, int bound, boolean seasonal) {
    List<Item> toAdd = selectItems(random.nextInt(bound) + bound, type);
    ArrayList<ItemStack> ita = new ArrayList<>();
    toAdd.forEach(item -> ita.add(new ItemStack(item, 1)));
    PlayerData data = player.getData();
    if ((type == ItemType.LootboxType.MINE || type == ItemType.LootboxType.MINE_PREMIUM) && toAdd.contains(ItemReference.SPARKLE_PICKAXE)) {
        data.addBadgeIfAbsent(Badge.DESTINY_REACHES);
    }
    if ((type == ItemType.LootboxType.FISH || type == ItemType.LootboxType.FISH_PREMIUM) && toAdd.contains(ItemReference.SHARK)) {
        data.addBadgeIfAbsent(Badge.TOO_BIG);
    }
    var toShow = ItemStack.reduce(ita);
    // Tools must only drop one, if any.
    toShow = toShow.stream().map(stack -> {
        var item = stack.getItem();
        if (stack.getAmount() > 1 && ((item instanceof Pickaxe) || (item instanceof FishRod) || (item instanceof Axe))) {
            return new ItemStack(item, 1);
        }
        return stack;
    }).collect(Collectors.toList());
    boolean overflow = seasonal ? seasonPlayer.getInventory().merge(toShow) : player.getInventory().merge(toShow);
    if (seasonal) {
        seasonPlayer.getInventory().process(new ItemStack(ItemReference.LOOT_CRATE_KEY, -1));
        seasonPlayer.getInventory().process(new ItemStack(crate, -1));
    } else {
        player.getInventory().process(new ItemStack(ItemReference.LOOT_CRATE_KEY, -1));
        player.getInventory().process(new ItemStack(crate, -1));
    }
    data.setCratesOpened(data.getCratesOpened() + 1);
    player.save();
    if (seasonal) {
        seasonPlayer.save();
    }
    I18nContext lang = ctx.getLanguageContext();
    var show = toShow.stream().map(itemStack -> "x%,d \u2009%s".formatted(itemStack.getAmount(), itemStack.getItem().toDisplayString())).collect(Collectors.joining(", "));
    var extra = "";
    if (overflow) {
        extra = ". " + lang.get("general.misc_item_usage.crate.overflow");
    }
    var high = toShow.stream().filter(stack -> stack.getItem() instanceof Tiered).filter(stack -> ((Tiered) stack.getItem()).getTier() >= 4).map(stack -> "%s \u2009(%d \u2b50)".formatted(stack.getItem().getEmoji(), ((Tiered) stack.getItem()).getTier())).collect(Collectors.joining(", "));
    if (high.length() >= 1) {
        extra = ".\n\n" + lang.get("general.misc_item_usage.crate.success_high").formatted(EmoteReference.POPPER, high);
    }
    ctx.sendFormat(lang.get("general.misc_item_usage.crate.success"), typeEmote.getDiscordNotation() + " ", show, extra);
}
Also used : Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) java.util(java.util) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) LoggerFactory(org.slf4j.LoggerFactory) SeasonPlayer(net.kodehawa.mantarobot.commands.currency.seasons.SeasonPlayer) SecureRandom(java.security.SecureRandom) Pair(org.apache.commons.lang3.tuple.Pair) FishRod(net.kodehawa.mantarobot.commands.currency.item.special.tools.FishRod) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Inventory(net.kodehawa.mantarobot.db.entities.helpers.Inventory) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) Tiered(net.kodehawa.mantarobot.commands.currency.item.special.helpers.attributes.Tiered) Broken(net.kodehawa.mantarobot.commands.currency.item.special.Broken) Player(net.kodehawa.mantarobot.db.entities.Player) UserData(net.kodehawa.mantarobot.db.entities.helpers.UserData) Logger(org.slf4j.Logger) Potion(net.kodehawa.mantarobot.commands.currency.item.special.Potion) Predicate(java.util.function.Predicate) IncreasingRateLimiter(net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter) Collectors(java.util.stream.Collectors) Axe(net.kodehawa.mantarobot.commands.currency.item.special.tools.Axe) TimeUnit(java.util.concurrent.TimeUnit) Breakable(net.kodehawa.mantarobot.commands.currency.item.special.helpers.Breakable) RatelimitUtils(net.kodehawa.mantarobot.utils.commands.ratelimit.RatelimitUtils) Stream(java.util.stream.Stream) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) RandomCollection(net.kodehawa.mantarobot.utils.RandomCollection) Pickaxe(net.kodehawa.mantarobot.commands.currency.item.special.tools.Pickaxe) Pickaxe(net.kodehawa.mantarobot.commands.currency.item.special.tools.Pickaxe) FishRod(net.kodehawa.mantarobot.commands.currency.item.special.tools.FishRod) Axe(net.kodehawa.mantarobot.commands.currency.item.special.tools.Axe) Tiered(net.kodehawa.mantarobot.commands.currency.item.special.helpers.attributes.Tiered) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext)

Example 20 with Context

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

the class Poll method createPoll.

private void createPoll(Context ctx, Message message, I18nContext languageContext) {
    runningPoll = ReactionOperations.create(message, TimeUnit.MILLISECONDS.toSeconds(timeout), new ReactionOperation() {

        @Override
        public int add(MessageReactionAddEvent e) {
            // always return false anyway lul
            return Operation.IGNORED;
        }

        @Override
        public void onExpire() {
            if (getChannel() == null)
                return;
            var user = ctx.getAuthor();
            var embedBuilder = new EmbedBuilder().setTitle(languageContext.get("commands.poll.result_header")).setDescription(String.format(languageContext.get("commands.poll.result_screen"), user.getName(), name)).setFooter(languageContext.get("commands.poll.thank_note"), null);
            var react = new AtomicInteger(0);
            var counter = new AtomicInteger(0);
            getChannel().retrieveMessageById(message.getIdLong()).queue(message -> {
                var votes = message.getReactions().stream().filter(r -> react.getAndIncrement() <= options.length).map(r -> String.format(languageContext.get("commands.poll.vote_results"), r.getCount() - 1, options[counter.getAndIncrement()])).collect(Collectors.joining("\n"));
                embedBuilder.addField(languageContext.get("commands.poll.results"), "```diff\n" + votes + "```", false);
                getChannel().sendMessageEmbeds(embedBuilder.build()).queue();
            });
            getRunningPolls().remove(getChannel().getId());
        }

        @Override
        public void onCancel() {
            getChannel().sendMessageFormat(languageContext.get("commands.poll.cancelled"), EmoteReference.CORRECT).queue();
            onExpire();
        }
    }, reactions(options.length));
}
Also used : ReactionOperation(net.kodehawa.mantarobot.core.listeners.operations.core.ReactionOperation) Message(net.dv8tion.jda.api.entities.Message) Color(java.awt.Color) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) Permission(net.dv8tion.jda.api.Permission) Utils(net.kodehawa.mantarobot.utils.Utils) HashMap(java.util.HashMap) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) TextChannel(net.dv8tion.jda.api.entities.TextChannel) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) Collectors(java.util.stream.Collectors) ReactionOperations(net.kodehawa.mantarobot.core.listeners.operations.ReactionOperations) Lobby(net.kodehawa.mantarobot.commands.interaction.Lobby) TimeUnit(java.util.concurrent.TimeUnit) Future(java.util.concurrent.Future) Stream(java.util.stream.Stream) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) Map(java.util.Map) MantaroData(net.kodehawa.mantarobot.data.MantaroData) ReactionOperation(net.kodehawa.mantarobot.core.listeners.operations.core.ReactionOperation) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) MessageReactionAddEvent(net.dv8tion.jda.api.events.message.react.MessageReactionAddEvent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) AtomicInteger(java.util.concurrent.atomic.AtomicInteger)

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