Search in sources :

Example 6 with PlayerData

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

the class CommandListener method onCommand.

private void onCommand(GuildMessageReceivedEvent event) {
    try {
        Member self = event.getGuild().getSelfMember();
        if (!self.getPermissions(event.getChannel()).contains(Permission.MESSAGE_WRITE) && !self.hasPermission(Permission.ADMINISTRATOR))
            return;
        if (commandProcessor.run(event)) {
            commandTotal++;
        } else {
            // Only run experience if no command has been executed, avoids weird race conditions when saving player status.
            try {
                // Only run experience if the user is not rate limited (clears every 30 seconds)
                if (random.nextInt(15) > 7 && !event.getAuthor().isBot() && experienceRatelimiter.process(event.getAuthor())) {
                    if (event.getMember() == null)
                        return;
                    // some nasty race conditions involving player save.
                    if (InteractiveOperations.get(event.getChannel()) != null)
                        return;
                    Player player = MantaroData.db().getPlayer(event.getAuthor());
                    PlayerData data = player.getData();
                    DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
                    GuildData guildData = dbGuild.getData();
                    if (player.isLocked())
                        return;
                    // Set level to 1 if level is zero.
                    if (player.getLevel() == 0)
                        player.setLevel(1);
                    // Set player experience to a random number between 1 and 5.
                    data.setExperience(data.getExperience() + Math.round(random.nextInt(5)));
                    // Apply some black magic.
                    if (data.getExperience() > (player.getLevel() * Math.log10(player.getLevel()) * 1000) + (50 * player.getLevel() / 2)) {
                        player.setLevel(player.getLevel() + 1);
                        // Check if the member is not null, just to be sure it happened in-between.
                        if (player.getLevel() > 1 && event.getGuild().getMemberById(player.getUserId()) != null) {
                            if (guildData.isEnabledLevelUpMessages()) {
                                String levelUpChannel = guildData.getLevelUpChannel();
                                String levelUpMessage = guildData.getLevelUpMessage();
                                // Player has leveled up!
                                if (levelUpMessage != null && levelUpChannel != null) {
                                    processMessage(String.valueOf(player.getLevel()), levelUpMessage, levelUpChannel, event);
                                }
                            }
                        }
                    }
                    // This time, actually remember to save the player so you don't have to restart 102 shards to fix it.
                    player.saveAsync();
                }
            } catch (Exception ignored) {
            }
        }
    } catch (IndexOutOfBoundsException e) {
        event.getChannel().sendMessage(EmoteReference.ERROR + "Your query returned no results or you used the incorrect arguments, seemingly. Just in case, check command help!").queue();
    } catch (PermissionException e) {
        if (e.getPermission() != Permission.UNKNOWN) {
            event.getChannel().sendMessage(String.format("%sI don't have permission to do this :<, I need the permission: **%s**%s", EmoteReference.ERROR, e.getPermission().getName(), e.getMessage() != null ? String.format(" | Message: %s", e.getMessage()) : "")).queue();
        } else {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot perform this action due to the lack of permission! Is the role I might be trying to assign" + " higher than my role? Do I have the correct permissions/hierarchy to perform this action?").queue();
        }
    } catch (IllegalArgumentException e) {
        // NumberFormatException == IllegalArgumentException
        String id = Snow64.toSnow64(event.getMessage().getIdLong());
        event.getChannel().sendMessage(String.format("%sI think you forgot something on the floor. (Maybe we threw it there? [Error ID: %s]... I hope we didn't)\n" + "- Incorrect type arguments or the message I'm trying to send exceeds 2048 characters, Just in case, check command help!", EmoteReference.ERROR, id)).queue();
        log.warn("Exception caught and alternate message sent. We should look into this, anyway (ID: {})", id, e);
    } catch (ReqlError e) {
        // So much just went wrong...
        e.printStackTrace();
        SentryHelper.captureExceptionContext("Something seems to have broken in the db! Check this out!", e, this.getClass(), "Database");
    } catch (RedisException e) {
        // So much just went wrong but on another side of the db...
        e.printStackTrace();
        SentryHelper.captureExceptionContext("Something seems to have broken in the db! Check this out!", e, this.getClass(), "Redis Database");
    } catch (Exception e) {
        String id = Snow64.toSnow64(event.getMessage().getIdLong());
        Player player = MantaroData.db().getPlayer(event.getAuthor());
        event.getChannel().sendMessage(String.format("%s%s\n(Error ID: `%s`)\n" + "If you want, join our **support guild** (Link on `~>about`), or check out our GitHub page (/Mantaro/MantaroBot). " + "Please tell them to quit exploding me and please don't forget the Error ID when reporting!", EmoteReference.ERROR, boomQuotes[rand.nextInt(boomQuotes.length)], id)).queue();
        if (player.getData().addBadgeIfAbsent(Badge.FIRE))
            player.saveAsync();
        SentryHelper.captureException(String.format("Unexpected Exception on Command: %s | (Error ID: ``%s``)", event.getMessage().getContentRaw(), id), e, this.getClass());
        log.error("Error happened with id: {} (Error ID: {})", event.getMessage().getContentRaw(), id, e);
    }
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Player(net.kodehawa.mantarobot.db.entities.Player) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) ReqlError(com.rethinkdb.gen.exc.ReqlError) RedisException(org.redisson.client.RedisException) Member(net.dv8tion.jda.core.entities.Member) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) RedisException(org.redisson.client.RedisException) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException)

Example 7 with PlayerData

use of net.kodehawa.mantarobot.db.entities.helpers.PlayerData 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)

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