Search in sources :

Example 21 with EmbedBuilder

use of net.dv8tion.jda.api.EmbedBuilder in project c0debaseBot by Biospheere.

the class HelpCommand method execute.

@Override
public void execute(final String[] args, final Message message) {
    final EmbedBuilder embedBuilder = getEmbed(message.getGuild(), message.getAuthor());
    final Collection<Command> commandCollection = bot.getCommandManager().getAvailableCommands();
    if (args.length == 0) {
        embedBuilder.setTitle("Command Übersicht");
        appendCommandOverview(commandCollection, embedBuilder);
    } else {
        addCommandDescription(args[0], commandCollection, embedBuilder);
    }
    message.getTextChannel().sendMessage(embedBuilder.build()).queue();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Command(de.c0debase.bot.commands.Command)

Example 22 with EmbedBuilder

use of net.dv8tion.jda.api.EmbedBuilder in project c0debaseBot by Biospheere.

the class RoleCommand method execute.

@Override
public void execute(final String[] args, final Message message) {
    if (args.length == 0) {
        final EmbedBuilder embedBuilder = getEmbed(message.getGuild(), message.getAuthor());
        embedBuilder.setFooter("!role Java,Go,Javascript", message.getMember().getUser().getEffectiveAvatarUrl());
        embedBuilder.appendDescription("__**Es gibt diese Rollen:**__\n\n");
        appendRoles(embedBuilder, message.getGuild());
        appendColors(embedBuilder, message.getGuild());
        message.getTextChannel().sendMessage(embedBuilder.build()).queue();
    } else {
        changeRole(String.join(" ", args).replaceAll(",", " "), message);
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder)

Example 23 with EmbedBuilder

use of net.dv8tion.jda.api.EmbedBuilder in project Saber-Bot by notem.

the class ListCommand method action.

@Override
public void action(String prefix, String[] args, MessageReceivedEvent event) {
    int index = 0;
    Integer entryId = ParsingUtilities.encodeIDToInt(args[index++]);
    ScheduleEntry se = Main.getEntryManager().getEntryFromGuild(entryId, event.getGuild().getId());
    String titleUrl = se.getTitleUrl() == null ? "https://nnmathe.ws/saber" : se.getTitleUrl();
    String title = se.getTitle() + " [" + ParsingUtilities.intToEncodedID(entryId) + "]";
    String content = "";
    List<String> userFilters = new ArrayList<>();
    List<String> roleFilters = new ArrayList<>();
    boolean filterByType = false;
    Set<String> typeFilters = new HashSet<>();
    boolean mobileFlag = false;
    boolean IdFlag = false;
    for (; index < args.length; index++) {
        if (args[index].equalsIgnoreCase("mobile") || args[index].equalsIgnoreCase("m")) {
            mobileFlag = true;
            continue;
        }
        if (args[index].equalsIgnoreCase("id") || args[index].equalsIgnoreCase("i")) {
            IdFlag = true;
            continue;
        }
        String filterType = args[index].split(":")[0].toLowerCase().trim();
        String filterValue = args[index].split(":")[1].trim();
        switch(filterType.toLowerCase()) {
            case "r":
            case "role":
                roleFilters.add(filterValue.replace("<@&", "").replace(">", ""));
                break;
            case "u":
            case "user":
                userFilters.add(filterValue.replace("<@", "").replace(">", ""));
                break;
            case "t":
            case "type":
                filterByType = true;
                typeFilters.add(filterValue);
                break;
        }
    }
    // maximum number of characters before creating a new message
    int lengthCap = 1900;
    // maximum number of lines until new message, in mobile mode
    int mobileLineCap = 25;
    Set<String> uniqueMembers = new HashSet<>();
    Map<String, String> options = Main.getScheduleManager().getRSVPOptions(se.getChannelId());
    for (String type : options.values()) {
        if (!filterByType || typeFilters.contains(type)) {
            content += "**\"" + type + "\"\n======================**\n";
            Set<String> members = se.getRsvpMembersOfType(type);
            for (String id : members) {
                // if the message is nearing maximum length, or if in mobile mode and the max lines have been reached
                if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
                    // build and send the embedded message object
                    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
                    MessageUtilities.sendMsg(message, event.getChannel(), null);
                    // clear the content sting
                    content = "*continued. . .* \n";
                }
                if (id.matches("\\d+")) {
                    // cases in which the id is most likely a valid discord user's ID
                    Member member = event.getGuild().getMemberById(id);
                    if (checkMember(member, userFilters, roleFilters)) {
                        // if the user is still a member of the guild, add to the list
                        uniqueMembers.add(member.getUser().getId());
                        content += this.getNameDisplay(mobileFlag, IdFlag, member);
                    } else // otherwise, remove the member from the event and update
                    {
                        Set<String> tmp = se.getRsvpMembersOfType(type);
                        tmp.remove(id);
                        se.getRsvpMembersOfType(type).remove(id);
                        Main.getEntryManager().updateEntry(se, false);
                    }
                } else {
                    // handles cases in which a non-discord user was added by an admin
                    uniqueMembers.add(id);
                    content += "*" + id + "*\n";
                }
            }
        }
        content += "\n";
    }
    if (!filterByType || typeFilters.contains("no-input")) {
        // generate a list of all members of the guild who pass the filter and map to their ID
        List<String> noInput = event.getGuild().getMembers().stream().filter(member -> checkMember(member, userFilters, roleFilters)).map(member -> member.getUser().getId()).collect(Collectors.toList());
        for (String type : options.values()) {
            noInput.removeAll(se.getRsvpMembersOfType(type));
        }
        content += "**No input\n======================\n**";
        if (!filterByType & noInput.size() > 10) {
            content += " Too many users to show: " + noInput.size() + " users with no rsvp\n";
        } else
            for (String id : noInput) {
                if (content.length() > lengthCap || (mobileFlag && StringUtils.countMatches(content, "\n") > mobileLineCap)) {
                    // build and send the embedded message object
                    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).build()).build();
                    MessageUtilities.sendMsg(message, event.getChannel(), null);
                    // clear the content sting
                    content = "*continued. . .* \n";
                }
                Member member = event.getGuild().getMemberById(id);
                content += this.getNameDisplay(mobileFlag, IdFlag, member);
            }
    }
    String footer = uniqueMembers.size() + " unique member(s) appear in this search";
    // build and send the embedded message object
    Message message = (new MessageBuilder()).setEmbed((new EmbedBuilder()).setDescription(content).setTitle(title, titleUrl).setFooter(footer, null).build()).build();
    MessageUtilities.sendMsg(message, event.getChannel(), null);
}
Also used : Message(net.dv8tion.jda.api.entities.Message) Command(ws.nmathe.saber.commands.Command) java.util(java.util) CommandInfo(ws.nmathe.saber.commands.CommandInfo) ISnowflake(net.dv8tion.jda.api.entities.ISnowflake) Logging(ws.nmathe.saber.utils.Logging) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Member(net.dv8tion.jda.api.entities.Member) StringUtils(org.apache.commons.lang3.StringUtils) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) Collectors(java.util.stream.Collectors) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Role(net.dv8tion.jda.api.entities.Role) MessageUtilities(ws.nmathe.saber.utils.MessageUtilities) Main(ws.nmathe.saber.Main) VerifyUtilities(ws.nmathe.saber.utils.VerifyUtilities) MessageReceivedEvent(net.dv8tion.jda.api.events.message.MessageReceivedEvent) ParsingUtilities(ws.nmathe.saber.utils.ParsingUtilities) Message(net.dv8tion.jda.api.entities.Message) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) ScheduleEntry(ws.nmathe.saber.core.schedule.ScheduleEntry) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Member(net.dv8tion.jda.api.entities.Member)

Example 24 with EmbedBuilder

use of net.dv8tion.jda.api.EmbedBuilder in project Saber-Bot by notem.

the class MessageGenerator method generate.

/**
 * Primary method which generates a complete Discord message object for the event
 * @param se (ScheduleEntry) to generate a message display
 * @return the message to be used to display the event in it's associated Discord channel
 */
public static Message generate(ScheduleEntry se) {
    if (se == null)
        return new MessageBuilder().build();
    // prepare title
    String titleUrl = (se.getTitleUrl() != null && VerifyUtilities.verifyUrl(se.getTitleUrl())) ? se.getTitleUrl() : DEFAULT_URL;
    String titleImage = ICON_URL;
    // generate the footer
    String footerStr = generateFooter(se);
    // determine the embed color
    Color embedColor = generateColor(se);
    // generate the body of the embed
    String bodyContent;
    String style = Main.getScheduleManager().getStyle(se.getChannelId());
    if (style.equalsIgnoreCase("narrow")) {
        bodyContent = generateBodyNarrow(se);
    } else {
        bodyContent = generateBodyFull(se);
    }
    // prepare the embed
    EmbedBuilder builder = new EmbedBuilder();
    builder.setDescription(bodyContent.substring(0, Math.min(bodyContent.length(), 2048))).setColor(embedColor).setAuthor(se.getTitle(), // , titleImage)
    titleUrl).setFooter(footerStr.substring(0, Math.min(footerStr.length(), 2048)), null);
    // add the image and thumbnail url links (if valid)
    if (se.getImageUrl() != null && VerifyUtilities.verifyUrl(se.getImageUrl())) {
        builder.setImage(se.getImageUrl());
    }
    if (se.getThumbnailUrl() != null && VerifyUtilities.verifyUrl(se.getThumbnailUrl())) {
        builder.setThumbnail(se.getThumbnailUrl());
    }
    MessageBuilder msgBuilder = new MessageBuilder().setEmbed(builder.build());
    if (se.getNonEmbededText() != null) {
        String fulltext = ParsingUtilities.processText(se.getNonEmbededText(), se, true);
        msgBuilder.setContent(fulltext);
    }
    // return the fully constructed message
    return msgBuilder.build();
}
Also used : EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder)

Example 25 with EmbedBuilder

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

Aggregations

EmbedBuilder (net.dv8tion.jda.api.EmbedBuilder)47 Member (net.dv8tion.jda.api.entities.Member)8 TimeUnit (java.util.concurrent.TimeUnit)7 Collectors (java.util.stream.Collectors)7 Message (net.dv8tion.jda.api.entities.Message)7 Context (net.kodehawa.mantarobot.core.modules.commands.base.Context)7 MantaroData (net.kodehawa.mantarobot.data.MantaroData)7 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)7 Color (java.awt.Color)6 MessageBuilder (net.dv8tion.jda.api.MessageBuilder)6 MessageEmbed (net.dv8tion.jda.api.entities.MessageEmbed)6 Utils (net.kodehawa.mantarobot.utils.Utils)6 Subscribe (com.google.common.eventbus.Subscribe)5 List (java.util.List)5 Role (net.dv8tion.jda.api.entities.Role)5 CommandCategory (net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory)5 HelpContent (net.kodehawa.mantarobot.core.modules.commands.help.HelpContent)5 I18nContext (net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext)5 LinkedList (java.util.LinkedList)4 Permission (net.dv8tion.jda.api.Permission)4