Search in sources :

Example 1 with PlayerData

use of net.kodehawa.mantarobot.db.entities.helpers.PlayerData in project MantaroBot by Mantaro.

the class ModLog method log.

public static void log(Member author, User target, String reason, ModAction action, long caseN, String... time) {
    DBGuild guildDB = db.getGuild(author.getGuild());
    Player player = db.getPlayer(author);
    PlayerData playerData = player.getData();
    EmbedBuilder embedBuilder = new EmbedBuilder();
    embedBuilder.addField("Responsible Moderator", author.getEffectiveName(), true);
    if (target != null)
        embedBuilder.addField("Member", target.getName(), true);
    embedBuilder.addField("Reason", reason, false);
    if (target != null) {
        embedBuilder.setThumbnail(target.getEffectiveAvatarUrl());
    } else {
        embedBuilder.setThumbnail(author.getUser().getEffectiveAvatarUrl());
    }
    switch(action) {
        case BAN:
            embedBuilder.setAuthor("Ban | Case #" + caseN, null, author.getUser().getEffectiveAvatarUrl());
            break;
        case TEMP_BAN:
            embedBuilder.setAuthor("Temp Ban | Case #" + caseN, null, author.getUser().getEffectiveAvatarUrl()).addField("Time", time[0], true);
            break;
        case KICK:
            embedBuilder.setAuthor("Kick | Case #" + caseN, null, author.getUser().getEffectiveAvatarUrl());
            break;
        case MUTE:
            embedBuilder.setAuthor("Mute | Case #" + caseN, null, author.getUser().getEffectiveAvatarUrl());
            break;
        case UNMUTE:
            embedBuilder.setAuthor("Un-mute | Case #" + caseN, null, author.getUser().getEffectiveAvatarUrl());
            break;
        case PRUNE:
            embedBuilder.setAuthor("Prune | Case #" + caseN, null, author.getUser().getEffectiveAvatarUrl());
            break;
        case WARN:
            embedBuilder.setAuthor("Warn | Case #" + caseN, null, author.getUser().getEffectiveAvatarUrl());
            break;
    }
    if (!playerData.hasBadge(Badge.POWER_USER)) {
        playerData.addBadgeIfAbsent(Badge.POWER_USER);
        player.saveAsync();
    }
    if (guildDB.getData().getGuildLogChannel() != null) {
        if (MantaroBot.getInstance().getTextChannelById(guildDB.getData().getGuildLogChannel()) != null) {
            MantaroBot.getInstance().getTextChannelById(guildDB.getData().getGuildLogChannel()).sendMessage(embedBuilder.build()).queue();
        }
    }
}
Also used : Player(net.kodehawa.mantarobot.db.entities.Player) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData)

Example 2 with PlayerData

use of net.kodehawa.mantarobot.db.entities.helpers.PlayerData in project MantaroBot by Mantaro.

the class ItemHelper method setItemActions.

public static void setItemActions() {
    log.info("Registering item actions...");
    ItemReference.MOP.setAction(((ctx, season) -> {
        Player player = ctx.getPlayer();
        PlayerData playerData = player.getData();
        DBUser dbUser = ctx.getDBUser();
        UserData userData = dbUser.getData();
        Inventory playerInventory = player.getInventory();
        if (!playerInventory.containsItem(ItemReference.MOP))
            return false;
        if (userData.getDustLevel() >= 5) {
            playerData.setTimesMopped(playerData.getTimesMopped() + 1);
            ctx.sendLocalized("general.misc_item_usage.mop", EmoteReference.DUST);
            if (userData.getDustLevel() == 100) {
                playerData.addBadgeIfAbsent(Badge.DUSTY);
            }
            playerInventory.process(new ItemStack(ItemReference.MOP, -1));
            userData.setDustLevel(0);
            player.save();
            dbUser.save();
        } else {
            ctx.sendLocalized("general.misc_item_usage.mop_not_enough", EmoteReference.DUST);
            return false;
        }
        return true;
    }));
    ItemReference.POTION_CLEAN.setAction((ctx, season) -> {
        Player player = ctx.getPlayer();
        DBUser dbUser = ctx.getDBUser();
        UserData userData = dbUser.getData();
        Inventory playerInventory = player.getInventory();
        userData.getEquippedItems().resetEffect(PlayerEquipment.EquipmentType.POTION);
        playerInventory.process(new ItemStack(ItemReference.POTION_CLEAN, -1));
        player.save();
        dbUser.save();
        ctx.sendLocalized("general.misc_item_usage.milk", EmoteReference.CORRECT);
        return true;
    });
    // This tends to be an issue: the name doesn't match the emoji name.
    // I don't want to match all of them by emoji name, as that can lead to bad results and conflicts,
    // so alias them to the emoji name, so people can open them more easily.
    ItemReference.MINE_CRATE.registerItemAlias("mine lootbox");
    ItemReference.FISH_CRATE.registerItemAlias("fish lootbox");
    ItemReference.CHOP_CRATE.registerItemAlias("chop lootbox");
    ItemReference.MINE_PREMIUM_CRATE.registerItemAlias("premium mine lootbox");
    ItemReference.FISH_PREMIUM_CRATE.registerItemAlias("premium fish lootbox");
    ItemReference.CHOP_PREMIUM_CRATE.registerItemAlias("premium chop lootbox");
}
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) SeasonPlayer(net.kodehawa.mantarobot.commands.currency.seasons.SeasonPlayer) Player(net.kodehawa.mantarobot.db.entities.Player) UserData(net.kodehawa.mantarobot.db.entities.helpers.UserData) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) Inventory(net.kodehawa.mantarobot.db.entities.helpers.Inventory)

Example 3 with PlayerData

use of net.kodehawa.mantarobot.db.entities.helpers.PlayerData in project MantaroBot by Mantaro.

the class PlayerCmds method badges.

@Subscribe
public void badges(CommandRegistry cr) {
    final Random r = new Random();
    ITreeCommand badgeCommand = cr.register("badges", 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, "brief");
                    // Lambdas strike again.
                    var contentFinal = content;
                    ctx.findMember(content, members -> {
                        var member = CustomFinderUtil.findMemberDefault(contentFinal, members, ctx, ctx.getMember());
                        if (member == null) {
                            return;
                        }
                        var toLookup = member.getUser();
                        Player player = ctx.getPlayer(toLookup);
                        PlayerData playerData = player.getData();
                        DBUser dbUser = ctx.getDBUser();
                        if (!optionalArguments.isEmpty() && optionalArguments.containsKey("brief")) {
                            ctx.sendLocalized("commands.badges.brief_success", member.getEffectiveName(), playerData.getBadges().stream().sorted().map(Badge::getDisplay).collect(Collectors.joining(", ")));
                            return;
                        }
                        var badges = playerData.getBadges();
                        Collections.sort(badges);
                        var embed = new EmbedBuilder().setAuthor(String.format(languageContext.get("commands.badges.header"), toLookup.getName())).setColor(ctx.getMemberColor()).setThumbnail(toLookup.getEffectiveAvatarUrl());
                        List<MessageEmbed.Field> fields = new LinkedList<>();
                        for (var b : badges) {
                            // God DAMNIT discord, I want it to look cute, stop trimming my spaces.
                            fields.add(new MessageEmbed.Field(b.toString(), "**\u2009\u2009\u2009\u2009- " + b.description + "**", false));
                        }
                        if (badges.isEmpty()) {
                            embed.setDescription(languageContext.get("commands.badges.no_badges"));
                            ctx.send(embed.build());
                            return;
                        }
                        var common = languageContext.get("commands.badges.profile_notice") + languageContext.get("commands.badges.info_notice") + ((r.nextInt(2) == 0 && !dbUser.isPremium() ? languageContext.get("commands.badges.donate_notice") : "\n") + String.format(languageContext.get("commands.badges.total_badges"), badges.size()));
                        DiscordUtils.sendPaginatedEmbed(ctx, embed, DiscordUtils.divideFields(6, fields), common);
                    });
                }
            };
        }

        @Override
        public HelpContent help() {
            return new HelpContent.Builder().setDescription("Shows your (or another person)'s badges.").setUsage("If you want to check out the badges of another person just mention them.\n" + "You can use `~>badges -brief` to get a brief versions of the badge showcase.").build();
        }
    });
    badgeCommand.addSubCommand("info", new SubCommand() {

        @Override
        public String description() {
            return "Shows info about a badge.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            if (content.isEmpty()) {
                ctx.sendLocalized("commands.badges.info.not_specified", EmoteReference.ERROR);
                return;
            }
            var badge = Badge.lookupFromString(content);
            if (badge == null || badge == Badge.DJ) {
                ctx.sendLocalized("commands.badges.info.not_found", EmoteReference.ERROR);
                return;
            }
            var player = ctx.getPlayer();
            var message = new MessageBuilder().setEmbeds(new EmbedBuilder().setAuthor(String.format(languageContext.get("commands.badges.info.header"), badge.display)).setDescription(String.join("\n", EmoteReference.BLUE_SMALL_MARKER + "**" + languageContext.get("general.name") + ":** " + badge.display, EmoteReference.BLUE_SMALL_MARKER + "**" + languageContext.get("general.description") + ":** " + badge.description, EmoteReference.BLUE_SMALL_MARKER + "**" + languageContext.get("commands.badges.info.achieved") + ":** " + player.getData().getBadges().stream().anyMatch(b -> b == badge))).setThumbnail("attachment://icon.png").setColor(Color.CYAN).build()).build();
            ctx.getChannel().sendMessage(message).addFile(badge.icon, "icon.png").queue();
        }
    });
    badgeCommand.addSubCommand("list", new SubCommand() {

        @Override
        public String description() {
            return "Lists all the obtainable badges.";
        }

        @Override
        protected void call(Context ctx, I18nContext languageContext, String content) {
            var badges = Badge.values();
            var builder = new EmbedBuilder().setAuthor(languageContext.get("commands.badges.ls.header"), null, ctx.getAuthor().getEffectiveAvatarUrl()).setColor(Color.PINK).setFooter(languageContext.get("general.requested_by").formatted(ctx.getMember().getEffectiveName()), null);
            var player = ctx.getPlayer();
            List<MessageEmbed.Field> fields = new LinkedList<>();
            for (Badge badge : badges) {
                if (!badge.isObtainable()) {
                    continue;
                }
                fields.add(new MessageEmbed.Field("%s\u2009\u2009\u2009%s".formatted(badge.unicode, badge.display), badge.getDescription() + "\n" + String.format(languageContext.get("commands.badges.ls.obtained"), player.getData().hasBadge(badge)), false));
            }
            DiscordUtils.sendPaginatedEmbed(ctx, builder, DiscordUtils.divideFields(7, fields), languageContext.get("commands.badges.ls.desc"));
        }
    });
    badgeCommand.createSubCommandAlias("list", "ls");
    badgeCommand.createSubCommandAlias("list", "1ist");
    badgeCommand.createSubCommandAlias("list", "Is");
    badgeCommand.createSubCommandAlias("list", "is");
    badgeCommand.createSubCommandAlias("list", "1s");
    cr.registerAlias("badges", "badge");
}
Also used : Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Color(java.awt.Color) Module(net.kodehawa.mantarobot.core.modules.Module) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) Utils(net.kodehawa.mantarobot.utils.Utils) Random(java.util.Random) User(net.dv8tion.jda.api.entities.User) InteractiveOperation(net.kodehawa.mantarobot.core.listeners.operations.core.InteractiveOperation) CustomFinderUtil(net.kodehawa.mantarobot.utils.commands.CustomFinderUtil) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) PlayerEquipment(net.kodehawa.mantarobot.commands.currency.item.PlayerEquipment) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) Context(net.kodehawa.mantarobot.core.modules.commands.base.Context) LinkedList(java.util.LinkedList) ItemHelper(net.kodehawa.mantarobot.commands.currency.item.ItemHelper) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) DiscordUtils(net.kodehawa.mantarobot.utils.commands.DiscordUtils) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) ItemReference(net.kodehawa.mantarobot.commands.currency.item.ItemReference) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) Predicate(java.util.function.Predicate) IncreasingRateLimiter(net.kodehawa.mantarobot.utils.commands.ratelimit.IncreasingRateLimiter) UnifiedPlayer(net.kodehawa.mantarobot.commands.currency.seasons.helpers.UnifiedPlayer) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Collectors(java.util.stream.Collectors) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) 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) OffsetDateTime(java.time.OffsetDateTime) ChronoUnit(java.time.temporal.ChronoUnit) CommandCategory(net.kodehawa.mantarobot.core.modules.commands.base.CommandCategory) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) Collections(java.util.Collections) Player(net.kodehawa.mantarobot.db.entities.Player) UnifiedPlayer(net.kodehawa.mantarobot.commands.currency.seasons.helpers.UnifiedPlayer) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) MessageEmbed(net.dv8tion.jda.api.entities.MessageEmbed) HelpContent(net.kodehawa.mantarobot.core.modules.commands.help.HelpContent) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) EmbedBuilder(net.dv8tion.jda.api.EmbedBuilder) Random(java.util.Random) MessageBuilder(net.dv8tion.jda.api.MessageBuilder) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) LinkedList(java.util.LinkedList) List(java.util.List) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) I18nContext(net.kodehawa.mantarobot.core.modules.commands.i18n.I18nContext) Subscribe(com.google.common.eventbus.Subscribe)

Example 4 with PlayerData

use of net.kodehawa.mantarobot.db.entities.helpers.PlayerData in project MantaroBot by Mantaro.

the class PlayerCmds method profile.

@Subscribe
public void profile(CommandRegistry cr) {
    ITreeCommand profileCommand = (TreeCommand) cr.register("profile", new TreeCommand(Category.CURRENCY) {

        @Override
        public Command defaultTrigger(GuildMessageReceivedEvent event, String mainCommand, String commandName) {
            return new SubCommand() {

                @Override
                protected void call(GuildMessageReceivedEvent event, String content) {
                    User userLooked = event.getAuthor();
                    Player player = MantaroData.db().getPlayer(userLooked);
                    UserData user = MantaroData.db().getUser(event.getMember()).getData();
                    Member memberLooked = event.getMember();
                    List<Member> found = FinderUtil.findMembers(content, event.getGuild());
                    if (found.isEmpty() && !content.isEmpty()) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "Didn't find any member with your search criteria :(").queue();
                        return;
                    }
                    if (found.size() > 1 && !content.isEmpty()) {
                        event.getChannel().sendMessage(EmoteReference.THINKING + "Too many members found, maybe refine your search? (ex. use name#discriminator)\n" + "**Members found:** " + found.stream().map(m -> m.getUser().getName() + "#" + m.getUser().getDiscriminator()).collect(Collectors.joining(", "))).queue();
                        return;
                    }
                    if (found.size() == 1 && !content.isEmpty()) {
                        userLooked = found.get(0).getUser();
                        memberLooked = found.get(0);
                        if (userLooked.isBot()) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "Bots don't have profiles.").queue();
                            return;
                        }
                        user = MantaroData.db().getUser(userLooked).getData();
                        player = MantaroData.db().getPlayer(memberLooked);
                    }
                    User marriedTo = (player.getData().getMarriedWith() == null || player.getData().getMarriedWith().isEmpty()) ? null : MantaroBot.getInstance().getUserById(player.getData().getMarriedWith());
                    PlayerData playerData = player.getData();
                    Inventory inv = player.getInventory();
                    // start of badge assigning
                    Guild mh = MantaroBot.getInstance().getGuildById("213468583252983809");
                    Member mhMember = mh == null ? null : mh.getMemberById(memberLooked.getUser().getId());
                    boolean saveAfter = false;
                    if (player.getMoney() > 7526527671L && playerData.addBadgeIfAbsent(Badge.ALTERNATIVE_WORLD))
                        saveAfter = true;
                    if (MantaroData.config().get().isOwner(userLooked) && playerData.addBadgeIfAbsent(Badge.DEVELOPER))
                        saveAfter = true;
                    if (inv.asList().stream().anyMatch(stack -> stack.getAmount() == 5000) && playerData.addBadgeIfAbsent(Badge.SHOPPER))
                        saveAfter = true;
                    if (inv.asList().stream().anyMatch(stack -> stack.getItem().equals(Items.CHRISTMAS_TREE_SPECIAL) || stack.getItem().equals(Items.BELL_SPECIAL)) && playerData.addBadgeIfAbsent(Badge.CHRISTMAS))
                        saveAfter = true;
                    if (MantaroBot.getInstance().getShardedMantaro().getDiscordBotsUpvoters().contains(userLooked.getIdLong()) && playerData.addBadgeIfAbsent(Badge.UPVOTER))
                        saveAfter = true;
                    if (player.getLevel() >= 10 && playerData.addBadgeIfAbsent(Badge.WALKER))
                        saveAfter = true;
                    if (player.getLevel() >= 50 && playerData.addBadgeIfAbsent(Badge.RUNNER))
                        saveAfter = true;
                    if (player.getLevel() >= 100 && playerData.addBadgeIfAbsent(Badge.FAST_RUNNER))
                        saveAfter = true;
                    if (player.getLevel() >= 150 && playerData.addBadgeIfAbsent(Badge.MARATHON_RUNNER))
                        saveAfter = true;
                    if (player.getLevel() >= 200 && playerData.addBadgeIfAbsent(Badge.MARATHON_WINNER))
                        saveAfter = true;
                    if (playerData.getMarketUsed() > 1000 && playerData.addBadgeIfAbsent(Badge.COMPULSIVE_BUYER))
                        saveAfter = true;
                    if (mhMember != null && mhMember.getRoles().stream().anyMatch(r -> r.getIdLong() == 406920476259123201L) && playerData.addBadgeIfAbsent(Badge.HELPER_2))
                        saveAfter = true;
                    if (mhMember != null && mhMember.getRoles().stream().anyMatch(r -> r.getIdLong() == 290257037072531466L || r.getIdLong() == 290902183300431872L) && playerData.addBadgeIfAbsent(Badge.DONATOR_2))
                        saveAfter = true;
                    if (saveAfter)
                        player.saveAsync();
                    // end of badge assigning
                    List<Badge> badges = playerData.getBadges();
                    Collections.sort(badges);
                    String displayBadges = badges.stream().map(Badge::getUnicode).limit(5).collect(Collectors.joining("  "));
                    applyBadge(event.getChannel(), badges.isEmpty() ? null : (playerData.getMainBadge() == null ? badges.get(0) : playerData.getMainBadge()), userLooked, baseEmbed(event, (marriedTo == null || !player.getInventory().containsItem(Items.RING) ? "" : EmoteReference.RING) + memberLooked.getEffectiveName() + "'s Profile", userLooked.getEffectiveAvatarUrl()).setThumbnail(userLooked.getEffectiveAvatarUrl()).setDescription((player.getData().isShowBadge() ? (badges.isEmpty() ? "" : String.format("**%s**\n", (playerData.getMainBadge() == null ? badges.get(0) : playerData.getMainBadge()))) : "") + (player.getData().getDescription() == null ? "No description set" : player.getData().getDescription())).addField(EmoteReference.DOLLAR + "Credits", "$ " + player.getMoney(), true).addField(EmoteReference.ZAP + "Level", player.getLevel() + " (Experience: " + player.getData().getExperience() + ")", true).addField(EmoteReference.REP + "Reputation", String.valueOf(player.getReputation()), true).addField(EmoteReference.POPPER + "Birthday", user.getBirthday() != null ? user.getBirthday().substring(0, 5) : "Not specified.", true).addField(EmoteReference.HEART + "Married with", marriedTo == null ? "Nobody." : marriedTo.getName() + "#" + marriedTo.getDiscriminator(), false).addField(EmoteReference.POUCH + "Inventory", ItemStack.toString(inv.asList()), false).addField(EmoteReference.HEART + "Top 5 Badges", displayBadges.isEmpty() ? "No badges (yet!)" : displayBadges, false).setFooter("User's timezone: " + (user.getTimezone() == null ? "No timezone set." : user.getTimezone()) + " | " + "Requested by " + event.getAuthor().getName(), null));
                }
            };
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Profile command.").setDescription("**Retrieves your current user profile.**").addField("Usage", "- To retrieve your profile, `~>profile`\n" + "- To change your description do `~>profile description set <description>`\n" + "  -- To clear it, just do `~>profile description clear`\n" + "- To set your timezone do `~>profile timezone <timezone>`\n" + "- To set your display badge use `~>profile displaybadge` and `~>profile displaybadge reset` to reset it.\n" + "  -- You can also use `~>profile displaybadge none` to display no badge on your profile.\n" + "**The profile only shows the 5 most important badges!.** Use `~>badges` to get a complete list.", false).build();
        }
    });
    profileCommand.addSubCommand("timezone", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            DBUser dbUser = MantaroData.db().getUser(event.getAuthor());
            String[] args = content.split(" ");
            if (args.length < 1) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the timezone.").queue();
                return;
            }
            String timezone = args[0];
            if (timezone.equalsIgnoreCase("reset")) {
                dbUser.getData().setTimezone(null);
                dbUser.saveAsync();
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Reset timezone.").queue();
                return;
            }
            if (!Utils.isValidTimeZone(timezone)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid timezone.").queue();
                return;
            }
            try {
                UtilsCmds.dateGMT(event.getGuild(), timezone);
            } catch (Exception e) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid timezone.").queue();
                return;
            }
            dbUser.getData().setTimezone(timezone);
            dbUser.saveAsync();
            event.getChannel().sendMessage(String.format("%sSaved timezone, your profile timezone is now: **%s**", EmoteReference.CORRECT, timezone)).queue();
        }
    });
    profileCommand.addSubCommand("description", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            User author = event.getAuthor();
            Player player = MantaroData.db().getPlayer(author);
            if (args.length == 0) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to provide an argument! (set or remove)\n" + "for example, ~>profile description set Hi there!").queue();
                return;
            }
            if (args[0].equals("set")) {
                int MAX_LENGTH = 300;
                if (MantaroData.db().getUser(author).isPremium())
                    MAX_LENGTH = 500;
                String content1 = SPLIT_PATTERN.split(content, 2)[1];
                if (content1.length() > MAX_LENGTH) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "The description is too long! `(Limit of 300 characters for everyone and 500 for premium users)`").queue();
                    return;
                }
                player.getData().setDescription(content1);
                event.getChannel().sendMessage(EmoteReference.POPPER + "Set description to: **" + content1 + "**\n" + "Check your shiny new profile with `~>profile`").queue();
                player.save();
                return;
            }
            if (args[1].equals("clear")) {
                player.getData().setDescription(null);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully cleared description.").queue();
                player.save();
            }
        }
    });
    profileCommand.addSubCommand("displaybadge", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            if (args.length == 0) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify your main badge!").queue();
                return;
            }
            Player player = MantaroData.db().getPlayer(event.getAuthor());
            PlayerData data = player.getData();
            if (args[0].equalsIgnoreCase("none")) {
                data.setShowBadge(false);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "No badge will show on the top of your profile now!").queue();
                player.saveAsync();
                return;
            }
            if (args[0].equalsIgnoreCase("reset")) {
                data.setMainBadge(null);
                data.setShowBadge(true);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Your display badge is now the most important one.").queue();
                player.saveAsync();
                return;
            }
            Badge badge = Badge.lookupFromString(content);
            if (badge == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "There's no such badge...\n" + "Your available badges: " + player.getData().getBadges().stream().map(Badge::getDisplay).collect(Collectors.joining(", "))).queue();
                return;
            }
            if (!data.getBadges().contains(badge)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You don't have that badge.\n" + "Your available badges: " + player.getData().getBadges().stream().map(Badge::getDisplay).collect(Collectors.joining(", "))).queue();
                return;
            }
            data.setShowBadge(true);
            data.setMainBadge(badge);
            player.saveAsync();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Your display badge is now: **" + badge.display + "**").queue();
        }
    });
}
Also used : Items(net.kodehawa.mantarobot.commands.currency.item.Items) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) MantaroInfo(net.kodehawa.mantarobot.MantaroInfo) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) Utils(net.kodehawa.mantarobot.utils.Utils) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) MantaroBot(net.kodehawa.mantarobot.MantaroBot) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.handleDefaultRatelimit(net.kodehawa.mantarobot.utils.Utils.handleDefaultRatelimit) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Inventory(net.kodehawa.mantarobot.db.entities.helpers.Inventory) Response(okhttp3.Response) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) ResponseBody(okhttp3.ResponseBody) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Request(okhttp3.Request) UserData(net.kodehawa.mantarobot.db.entities.helpers.UserData) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) FinderUtil(com.jagrosh.jdautilities.utils.FinderUtil) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) UserData(net.kodehawa.mantarobot.db.entities.helpers.UserData) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) IOException(java.io.IOException) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Inventory(net.kodehawa.mantarobot.db.entities.helpers.Inventory) Subscribe(com.google.common.eventbus.Subscribe)

Example 5 with PlayerData

use of net.kodehawa.mantarobot.db.entities.helpers.PlayerData in project MantaroBot by Mantaro.

the class ImageboardUtils method getImage.

public static void getImage(ImageBoard<?> api, ImageRequestType type, boolean nsfwOnly, String imageboard, String[] args, String content, GuildMessageReceivedEvent event) {
    Rating rating = Rating.SAFE;
    boolean needRating = args.length >= 3;
    final TextChannel channel = event.getChannel();
    final Player player = MantaroData.db().getPlayer(event.getAuthor());
    final PlayerData playerData = player.getData();
    if (needRating && !nsfwOnly)
        rating = Rating.lookupFromString(args[2]);
    if (nsfwOnly)
        rating = Rating.EXPLICIT;
    if (rating == null) {
        channel.sendMessage(EmoteReference.ERROR + "You provided an invalid rating (Available types: questionable, explicit, safe)!").queue();
        return;
    }
    final Rating finalRating = rating;
    if (!nsfwCheck(event, nsfwOnly, false, finalRating)) {
        channel.sendMessage(EmoteReference.ERROR + "Cannot send a NSFW image in a non-nsfw channel :(").queue();
        return;
    }
    int page = Math.max(1, r.nextInt(25));
    String queryRating = nsfwOnly ? null : rating.getLongName();
    switch(type) {
        case GET:
            try {
                String arguments = content.replace("get ", "");
                String[] argumentsSplit = arguments.split(" ");
                api.get(page, queryRating).async(requestedImages -> {
                    if (isListNull(requestedImages, event))
                        return;
                    try {
                        int number;
                        List<BoardImage> images = (List<BoardImage>) requestedImages;
                        if (!nsfwOnly)
                            images = requestedImages.stream().filter(data -> data.getRating().equals(finalRating)).collect(Collectors.toList());
                        if (images.isEmpty()) {
                            channel.sendMessage(EmoteReference.SAD + "There are no images matching your search criteria...").queue();
                            return;
                        }
                        try {
                            number = Integer.parseInt(argumentsSplit[0]);
                        } catch (Exception e) {
                            number = r.nextInt(images.size());
                        }
                        BoardImage image = images.get(number);
                        String tags = image.getTags().stream().collect(Collectors.joining(", "));
                        if (foundMinorTags(event, tags, image.getRating())) {
                            return;
                        }
                        imageEmbed(image.getURL(), String.valueOf(image.getWidth()), String.valueOf(image.getHeight()), tags, image.getRating(), imageboard, channel);
                        if (image.getRating().equals(Rating.EXPLICIT)) {
                            if (playerData.addBadgeIfAbsent(Badge.LEWDIE)) {
                                player.saveAsync();
                            }
                            TextChannelGround.of(event).dropItemWithChance(13, 3);
                        }
                    } catch (Exception e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "**There aren't any more images or no results found**! Please try with a lower " + "number or another search.").queue();
                    }
                }, failure -> event.getChannel().sendMessage(EmoteReference.SAD + "There was an error while looking for an image...").queue());
            } catch (NumberFormatException ne) {
                channel.sendMessage(EmoteReference.ERROR + "Wrong argument type. Check ~>help " + imageboard).queue(message -> message.delete().queueAfter(10, TimeUnit.SECONDS));
            } catch (Exception e) {
                event.getChannel().sendMessage(EmoteReference.SAD + "There was an error while looking an image...").queue();
            }
            break;
        case TAGS:
            try {
                String sNoArgs = content.replace("tags ", "");
                String[] arguments = sNoArgs.split(" ");
                String tags = arguments[0];
                DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
                if (dbGuild.getData().getBlackListedImageTags().contains(tags.toLowerCase())) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "This image tag has been blacklisted here by an administrator.").queue();
                    return;
                }
                api.search(tags, queryRating).async(requestedImages -> {
                    // account for this
                    if (isListNull(requestedImages, event))
                        return;
                    try {
                        List<BoardImage> filter = (List<BoardImage>) requestedImages;
                        if (!nsfwOnly)
                            filter = requestedImages.stream().filter(data -> data.getRating().equals(finalRating)).collect(Collectors.toList());
                        if (filter.isEmpty()) {
                            channel.sendMessage(EmoteReference.SAD + "There are no images matching your search criteria...").queue();
                            return;
                        }
                        int number;
                        try {
                            number = Integer.parseInt(arguments[1]);
                        } catch (Exception e) {
                            number = r.nextInt(filter.size() > 0 ? filter.size() - 1 : filter.size());
                        }
                        BoardImage image = filter.get(number);
                        String imageTags = image.getTags().stream().collect(Collectors.joining(", "));
                        if (foundMinorTags(event, imageTags, image.getRating())) {
                            return;
                        }
                        imageEmbed(image.getURL(), String.valueOf(image.getWidth()), String.valueOf(image.getHeight()), imageTags, image.getRating(), imageboard, channel);
                        if (image.getRating().equals(Rating.EXPLICIT)) {
                            if (playerData.addBadgeIfAbsent(Badge.LEWDIE)) {
                                player.saveAsync();
                            }
                            TextChannelGround.of(event).dropItemWithChance(13, 3);
                        }
                    } catch (Exception e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "**There aren't any more images or no results found**! Please try with a lower " + "number or another search.").queue();
                    }
                }, failure -> event.getChannel().sendMessage(EmoteReference.SAD + "There was an error while looking for this tag...").queue());
            } catch (NumberFormatException numberEx) {
                channel.sendMessage(EmoteReference.ERROR + "Wrong argument type. Check ~>help " + imageboard).queue(message -> message.delete().queueAfter(10, TimeUnit.SECONDS));
            } catch (Exception exception) {
                event.getChannel().sendMessage(EmoteReference.SAD + "There was an error while looking for this tag...").queue();
            }
            break;
        case RANDOM:
            api.get(page, queryRating).async(requestedImages -> {
                try {
                    if (isListNull(requestedImages, event))
                        return;
                    List<BoardImage> filter = (List<BoardImage>) requestedImages;
                    if (!nsfwOnly)
                        filter = requestedImages.stream().filter(data -> data.getRating().equals(finalRating)).collect(Collectors.toList());
                    if (filter.isEmpty()) {
                        channel.sendMessage(EmoteReference.SAD + "There are no images matching your search criteria...").queue();
                        return;
                    }
                    int number = r.nextInt(filter.size());
                    BoardImage image = filter.get(number);
                    String tags = image.getTags().stream().collect(Collectors.joining(", "));
                    imageEmbed(image.getURL(), String.valueOf(image.getWidth()), String.valueOf(image.getHeight()), tags, image.getRating(), imageboard, channel);
                    if (image.getRating().equals(Rating.EXPLICIT)) {
                        if (playerData.addBadgeIfAbsent(Badge.LEWDIE)) {
                            player.saveAsync();
                        }
                        TextChannelGround.of(event).dropItemWithChance(13, 3);
                    }
                } catch (Exception e) {
                    event.getChannel().sendMessage(EmoteReference.SAD + "There was an unknown error while looking for a random image...").queue();
                }
            }, failure -> event.getChannel().sendMessage(EmoteReference.SAD + "There was an error while looking for a random image...").queue());
            break;
    }
}
Also used : Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Player(net.kodehawa.mantarobot.db.entities.Player) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Random(java.util.Random) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TimeUnit(java.util.concurrent.TimeUnit) ImageBoard(net.kodehawa.lib.imageboards.ImageBoard) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) List(java.util.List) Rating(net.kodehawa.lib.imageboards.entities.Rating) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) BoardImage(net.kodehawa.lib.imageboards.entities.BoardImage) MantaroData(net.kodehawa.mantarobot.data.MantaroData) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) Player(net.kodehawa.mantarobot.db.entities.Player) BoardImage(net.kodehawa.lib.imageboards.entities.BoardImage) Rating(net.kodehawa.lib.imageboards.entities.Rating) TextChannel(net.dv8tion.jda.core.entities.TextChannel) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) List(java.util.List) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData)

Aggregations

Player (net.kodehawa.mantarobot.db.entities.Player)7 PlayerData (net.kodehawa.mantarobot.db.entities.helpers.PlayerData)7 TimeUnit (java.util.concurrent.TimeUnit)5 Collectors (java.util.stream.Collectors)5 Badge (net.kodehawa.mantarobot.commands.currency.profile.Badge)5 MantaroData (net.kodehawa.mantarobot.data.MantaroData)5 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)5 DBUser (net.kodehawa.mantarobot.db.entities.DBUser)4 java.util (java.util)3 List (java.util.List)3 Predicate (java.util.function.Predicate)3 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)3 Subscribe (com.google.common.eventbus.Subscribe)2 SecureRandom (java.security.SecureRandom)2 Random (java.util.Random)2 Stream (java.util.stream.Stream)2 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)2 ItemStack (net.kodehawa.mantarobot.commands.currency.item.ItemStack)2 Broken (net.kodehawa.mantarobot.commands.currency.item.special.Broken)2 Potion (net.kodehawa.mantarobot.commands.currency.item.special.Potion)2