Search in sources :

Example 1 with Player

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

the class CurrencyCmds method transferItems.

@Subscribe
public void transferItems(CommandRegistry cr) {
    cr.register("itemtransfer", new SimpleCommand(Category.CURRENCY) {

        RateLimiter rl = new RateLimiter(TimeUnit.SECONDS, 10);

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length < 2) {
                onError(event);
                return;
            }
            List<User> mentionedUsers = event.getMessage().getMentionedUsers();
            if (mentionedUsers.size() == 0) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention a user").queue();
            } else {
                User giveTo = mentionedUsers.get(0);
                if (event.getAuthor().getId().equals(giveTo.getId())) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot transfer items to yourself!").queue();
                    return;
                }
                if (giveTo.isBot()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot transfer items to a bot.").queue();
                    return;
                }
                if (!handleDefaultRatelimit(rl, event.getAuthor(), event))
                    return;
                Item item = Items.fromAny(args[1]).orElse(null);
                if (item == null) {
                    event.getChannel().sendMessage("There isn't an item associated with this emoji.").queue();
                } else {
                    Player player = MantaroData.db().getPlayer(event.getAuthor());
                    Player giveToPlayer = MantaroData.db().getPlayer(giveTo);
                    if (player.isLocked()) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot transfer items now.").queue();
                        return;
                    }
                    if (args.length == 2) {
                        if (player.getInventory().containsItem(item)) {
                            if (item.isHidden()) {
                                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot transfer this item!").queue();
                                return;
                            }
                            if (giveToPlayer.getInventory().asMap().getOrDefault(item, new ItemStack(item, 0)).getAmount() >= 5000) {
                                event.getChannel().sendMessage(EmoteReference.ERROR + "This player has the maximum possible amount of this item (5000).").queue();
                                return;
                            }
                            player.getInventory().process(new ItemStack(item, -1));
                            giveToPlayer.getInventory().process(new ItemStack(item, 1));
                            event.getChannel().sendMessage(String.format("%s%s gave 1 **%s** to %s", EmoteReference.OK, event.getMember().getEffectiveName(), item.getName(), event.getGuild().getMember(giveTo).getEffectiveName())).queue();
                        } else {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "You don't have any of these items in your inventory").queue();
                        }
                        player.saveAsync();
                        giveToPlayer.saveAsync();
                        return;
                    }
                    try {
                        int amount = Math.abs(Integer.parseInt(args[2]));
                        if (player.getInventory().containsItem(item) && player.getInventory().getAmount(item) >= amount) {
                            if (item.isHidden()) {
                                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot transfer this item!").queue();
                                return;
                            }
                            if (giveToPlayer.getInventory().asMap().getOrDefault(item, new ItemStack(item, 0)).getAmount() + amount > 5000) {
                                event.getChannel().sendMessage(EmoteReference.ERROR + "This player would exceed the maximum possible amount of this item (5000).").queue();
                                return;
                            }
                            player.getInventory().process(new ItemStack(item, amount * -1));
                            giveToPlayer.getInventory().process(new ItemStack(item, amount));
                            event.getChannel().sendMessage(String.format("%s%s gave %d **%s** to %s", EmoteReference.OK, event.getMember().getEffectiveName(), amount, item.getName(), event.getGuild().getMember(giveTo).getEffectiveName())).queue();
                        } else {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "You don't have enough of this item to do that").queue();
                        }
                    } catch (NumberFormatException nfe) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid number provided").queue();
                    }
                    player.saveAsync();
                    giveToPlayer.saveAsync();
                }
            }
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Transfer Items command").setDescription("**Transfers items from you to another player.**").addField("Usage", "`~>itemtransfer <@user> <item emoji or part of the name> <amount (optional)>` - **Transfers the item to player x**", false).addField("Parameters", "`@user` - user to send the item to\n" + "`item emoji` - write out the emoji of the item you want to send, or you can just use part of its name.\n" + "`amount` - optional, send a specific amount of an item to someone.", false).addField("Important", "You cannot send more items than what you already have", false).build();
        }
    });
    cr.registerAlias("itemtransfer", "transferitems");
}
Also used : Player(net.kodehawa.mantarobot.db.entities.Player) User(net.dv8tion.jda.core.entities.User) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) Item(net.kodehawa.mantarobot.commands.currency.item.Item) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) List(java.util.List) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 2 with Player

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

the class MoneyCmds method slots.

@Subscribe
public void slots(CommandRegistry cr) {
    RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 35);
    String[] emotes = { "\uD83C\uDF52", "\uD83D\uDCB0", "\uD83D\uDCB2", "\uD83E\uDD55", "\uD83C\uDF7F", "\uD83C\uDF75", "\uD83C\uDFB6" };
    Random random = new SecureRandom();
    List<String> winCombinations = new ArrayList<>();
    for (String emote : emotes) {
        winCombinations.add(emote + emote + emote);
    }
    cr.register("slots", new SimpleCommand(Category.CURRENCY) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Map<String, Optional<String>> opts = StringUtils.parse(args);
            long money = 50;
            // 25% raw chance of winning, completely random chance of winning on the other random iteration
            int slotsChance = 25;
            boolean isWin = false;
            boolean coinSelect = false;
            Player player = MantaroData.db().getPlayer(event.getAuthor());
            int amountN = 1;
            if (opts.containsKey("useticket")) {
                coinSelect = true;
            }
            if (opts.containsKey("amount") && opts.get("amount").isPresent()) {
                if (!coinSelect) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot specify how many tickets you're gonna use if you're not using tickets!").queue();
                    return;
                }
                String amount = opts.get("amount").get();
                if (amount.isEmpty()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't specify the amount!").queue();
                    return;
                }
                try {
                    amountN = Integer.parseUnsignedInt(amount);
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "That is not a valid number!").queue();
                }
                if (player.getInventory().getAmount(Items.SLOT_COIN) < amountN) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You don't have enough slots tickets!").queue();
                    return;
                }
                money += 58 * amountN;
            }
            if (args.length == 1 && !coinSelect) {
                try {
                    money = Math.abs(Integer.parseInt(args[0]));
                    if (money < 25) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "The minimum amount is 25!").queue();
                        return;
                    }
                    if (money > SLOTS_MAX_MONEY) {
                        event.getChannel().sendMessage(EmoteReference.WARNING + "This machine cannot dispense that much money!").queue();
                        return;
                    }
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a number!").queue();
                    return;
                }
            }
            if (player.getMoney() < money && !coinSelect) {
                event.getChannel().sendMessage(EmoteReference.SAD + "You don't have enough money to play the slots machine!").queue();
                return;
            }
            if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                return;
            if (coinSelect) {
                if (player.getInventory().containsItem(Items.SLOT_COIN)) {
                    player.getInventory().process(new ItemStack(Items.SLOT_COIN, -amountN));
                    player.saveAsync();
                    slotsChance = slotsChance + 10;
                } else {
                    event.getChannel().sendMessage(EmoteReference.SAD + "You wanted to use tickets but you don't have any :<").queue();
                    return;
                }
            } else {
                player.removeMoney(money);
                player.saveAsync();
            }
            StringBuilder message = new StringBuilder(String.format("%s**You used %s and rolled the slot machine!**\n\n", EmoteReference.DICE, coinSelect ? amountN + " slot ticket(s)" : money + " credits"));
            StringBuilder builder = new StringBuilder();
            for (int i = 0; i < 9; i++) {
                if (i > 1 && i % 3 == 0) {
                    builder.append("\n");
                }
                builder.append(emotes[random.nextInt(emotes.length)]);
            }
            String toSend = builder.toString();
            int gains = 0;
            String[] rows = toSend.split("\\r?\\n");
            if (random.nextInt(100) < slotsChance) {
                rows[1] = winCombinations.get(random.nextInt(winCombinations.size()));
            }
            if (winCombinations.contains(rows[1])) {
                isWin = true;
                gains = random.nextInt((int) Math.round(money * 1.76)) + 14;
            }
            rows[1] = rows[1] + " \u2b05";
            toSend = String.join("\n", rows);
            if (isWin) {
                message.append(toSend).append("\n\n").append(String.format("And you won **%d** credits and got to keep what you bet (%d credits)! Lucky! ", gains, money)).append(EmoteReference.POPPER);
                player.addMoney(gains + money);
                if ((gains + money) > SLOTS_MAX_MONEY) {
                    player.getData().addBadgeIfAbsent(Badge.LUCKY_SEVEN);
                }
                player.saveAsync();
            } else {
                message.append(toSend).append("\n\n").append("And you lost ").append(EmoteReference.SAD).append("\n").append("I hope you do better next time!");
            }
            message.append("\n");
            event.getChannel().sendMessage(message.toString()).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Slots Command").setDescription("**Rolls the slot machine. Requires a default of 50 coins to roll.**").addField("Considerations", "You can gain a maximum of put credits * 1.76 coins from it.\n" + "You can use the `-useticket` argument to use a slot ticket (slightly bigger chance)", false).addField("Usage", "`~>slots` - Default one, 50 coins.\n" + "`~>slots <credits>` - Puts x credits on the slot machine. Max of " + SLOTS_MAX_MONEY + " coins.\n" + "`~>slots -useticket` - Rolls the slot machine with one slot coin.\n" + "You can specify the amount of tickets to use using `-amount` (for example `~>slots -useticket -amount 10`)", false).build();
        }
    });
}
Also used : Player(net.kodehawa.mantarobot.db.entities.Player) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SecureRandom(java.security.SecureRandom) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) SecureRandom(java.security.SecureRandom) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 3 with Player

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

the class MoneyCmds method richest.

@Subscribe
public void richest(CommandRegistry cr) {
    final RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 10);
    final String pattern = ":g$";
    ITreeCommand leaderboards = (ITreeCommand) cr.register("leaderboard", 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) {
                    if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                        return;
                    OrderBy template = r.table("players").orderBy().optArg("index", r.desc("money"));
                    Cursor<Map> c1 = getGlobalRichest(template, pattern);
                    List<Map> c = c1.toList();
                    c1.close();
                    event.getChannel().sendMessage(baseEmbed(event, "Money leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("money").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - $%s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
                }
            };
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Leaderboard").setDescription("**Returns the leaderboard.**").addField("Usage", "`~>leaderboard` - **Returns the money leaderboard.**\n" + "`~>leaderboard rep` - **Returns the reputation leaderboard.**\n" + "`~>leaderboard lvl` - **Returns the level leaderboard.**\n" + "~>leaderboard streak - **Returns the daily streak leaderboard.", false).build();
        }
    });
    leaderboards.addSubCommand("lvl", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                return;
            Cursor<Map> m;
            try (Connection conn = Utils.newDbConnection()) {
                m = r.table("players").orderBy().optArg("index", r.desc("level")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", "level", r.hashMap("data", "experience"))).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
            }
            List<Map> c = m.toList();
            m.close();
            event.getChannel().sendMessage(baseEmbed(event, "Level leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("level").toString() + "\n - Experience: **" + ((Map) map.get("data")).get("experience") + "**")).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
        }
    });
    leaderboards.addSubCommand("rep", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Cursor<Map> m;
            try (Connection conn = Utils.newDbConnection()) {
                m = r.table("players").orderBy().optArg("index", r.desc("reputation")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", "reputation")).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
            }
            List<Map> c = m.toList();
            m.close();
            event.getChannel().sendMessage(baseEmbed(event, "Reputation leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), map.get("reputation").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %s", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
        }
    });
    leaderboards.addSubCommand("streak", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Cursor<Map> m;
            try (Connection conn = Utils.newDbConnection()) {
                m = r.table("players").orderBy().optArg("index", r.desc("userDailyStreak")).filter(player -> player.g("id").match(pattern)).map(player -> player.pluck("id", r.hashMap("data", "dailyStrike"))).limit(10).run(conn, OptArgs.of("read_mode", "outdated"));
            }
            List<Map> c = m.toList();
            m.close();
            event.getChannel().sendMessage(baseEmbed(event, "Daily streak leaderboard (Top 10)", event.getJDA().getSelfUser().getEffectiveAvatarUrl()).setDescription(c.stream().map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("id").toString().split(":")[0]), ((HashMap) (map.get("data"))).get("dailyStrike").toString())).filter(p -> Objects.nonNull(p.getKey())).map(p -> String.format("%s**%s#%s** - %sx", EmoteReference.MARKER, p.getKey().getName(), p.getKey().getDiscriminator(), p.getValue())).collect(Collectors.joining("\n"))).build()).queue();
        }
    });
    // TODO enable in 4.9
    /*
        leaderboards.addSubCommand("localxp", new SubCommand() {
            @Override
            protected void call(GuildMessageReceivedEvent event, String content) {
                List<Map> l;

                try(Connection conn = Utils.newDbConnection()) {
                    l = r.table("guilds")
                            .get(event.getGuild().getId())
                            .getField("data")
                            .getField("localPlayerExperience")
                            .run(conn, OptArgs.of("read_mode", "outdated"));
                }

                l.sort(Comparator.<Map>comparingLong(o -> (long) o.get("experience")).reversed());

                event.getChannel().sendMessage(
                        baseEmbed(event,
                                "Local level leaderboard", event.getJDA().getSelfUser().getEffectiveAvatarUrl()
                        ).setDescription(l.stream()
                                .map(map -> Pair.of(MantaroBot.getInstance().getUserById(map.get("userId").toString()), map.get("level").toString() +
                                        "\n - Experience: **" + map.get("experience") + "**\n"))
                                .map(p -> String.format("%s**%s** - %s", EmoteReference.MARKER,
                                        p == null ? "User left guild" : p.getKey().getName() + "#" + p.getKey().getDiscriminator(), p.getValue()))
                                .collect(Collectors.joining("\n"))
                        ).build()
                ).queue();
            }
        });

        leaderboards.createSubCommandAlias("localxp", "local");
        */
    leaderboards.createSubCommandAlias("rep", "reputation");
    leaderboards.createSubCommandAlias("lvl", "level");
    leaderboards.createSubCommandAlias("streak", "daily");
    cr.registerAlias("leaderboard", "richest");
}
Also used : OrderBy(com.rethinkdb.gen.ast.OrderBy) Items(net.kodehawa.mantarobot.commands.currency.item.Items) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) Member(net.dv8tion.jda.core.entities.Member) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) Utils(net.kodehawa.mantarobot.utils.Utils) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) NumberFormat(java.text.NumberFormat) InteractiveOperation(net.kodehawa.mantarobot.core.listeners.operations.core.InteractiveOperation) MantaroBot(net.kodehawa.mantarobot.MantaroBot) SecureRandom(java.security.SecureRandom) RethinkDB.r(com.rethinkdb.RethinkDB.r) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Cursor(com.rethinkdb.net.Cursor) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) Pair(org.apache.commons.lang3.tuple.Pair) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.handleDefaultRatelimit(net.kodehawa.mantarobot.utils.Utils.handleDefaultRatelimit) OptArgs(com.rethinkdb.model.OptArgs) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) ParseException(java.text.ParseException) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) Connection(com.rethinkdb.net.Connection) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) Month(java.time.Month) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Collectors(java.util.stream.Collectors) ZoneId(java.time.ZoneId) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) TimeUnit(java.util.concurrent.TimeUnit) User(net.dv8tion.jda.core.entities.User) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) LocalDate(java.time.LocalDate) MantaroData(net.kodehawa.mantarobot.data.MantaroData) FinderUtil(com.jagrosh.jdautilities.utils.FinderUtil) OrderBy(com.rethinkdb.gen.ast.OrderBy) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Connection(com.rethinkdb.net.Connection) Cursor(com.rethinkdb.net.Cursor) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) 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) Subscribe(com.google.common.eventbus.Subscribe)

Example 4 with Player

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

the class MoneyCmds method loot.

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

        final RateLimiter rateLimiter = new RateLimiter(TimeUnit.MINUTES, 5, true);

        final ZoneId zoneId = ZoneId.systemDefault();

        final Random r = new Random();

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Player player = MantaroData.db().getPlayer(event.getMember());
            if (player.isLocked()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot loot now.").queue();
                return;
            }
            if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                return;
            LocalDate today = LocalDate.now(zoneId);
            LocalDate eventStart = today.withMonth(Month.DECEMBER.getValue()).withDayOfMonth(23);
            // Up to the 25th
            LocalDate eventStop = eventStart.plusDays(3);
            TextChannelGround ground = TextChannelGround.of(event);
            if (today.isEqual(eventStart) || (today.isAfter(eventStart) && today.isBefore(eventStop))) {
                ground.dropItemWithChance(Items.CHRISTMAS_TREE_SPECIAL, 4);
                ground.dropItemWithChance(Items.BELL_SPECIAL, 4);
            }
            if (r.nextInt(100) == 0) {
                // 1 in 100 chance of it dropping a loot crate.
                ground.dropItem(Items.LOOT_CRATE);
                if (player.getData().addBadgeIfAbsent(Badge.LUCKY))
                    player.saveAsync();
            }
            List<ItemStack> loot = ground.collectItems();
            int moneyFound = ground.collectMoney() + Math.max(0, r.nextInt(50) - 10);
            if (MantaroData.db().getUser(event.getMember()).isPremium() && moneyFound > 0) {
                moneyFound = moneyFound + random.nextInt(moneyFound);
            }
            if (!loot.isEmpty()) {
                String s = ItemStack.toString(ItemStack.reduce(loot));
                String overflow;
                if (player.getInventory().merge(loot))
                    overflow = "But you already had too many items, so you decided to throw away the excess. ";
                else
                    overflow = "";
                if (moneyFound != 0) {
                    if (player.addMoney(moneyFound)) {
                        event.getChannel().sendMessage(String.format("%sDigging through messages, you found %s, along with **$%d credits!** %s", EmoteReference.POPPER, s, moneyFound, overflow)).queue();
                    } else {
                        event.getChannel().sendMessage(String.format("%sDigging through messages, you found %s, along with **$%d credits.** " + "%sBut you already had too many credits.", EmoteReference.POPPER, s, moneyFound, overflow)).queue();
                    }
                } else {
                    event.getChannel().sendMessage(EmoteReference.MEGA + "Digging through messages, you found " + s + ". " + overflow).queue();
                }
            } else {
                if (moneyFound != 0) {
                    if (player.addMoney(moneyFound)) {
                        event.getChannel().sendMessage(EmoteReference.POPPER + "Digging through messages, you found **$" + moneyFound + " credits!**").queue();
                    } else {
                        event.getChannel().sendMessage(String.format("%sDigging through messages, you found **$%d credits.** " + "But you already had too many credits.", EmoteReference.POPPER, moneyFound)).queue();
                    }
                } else {
                    String msg = "Digging through messages, you found nothing but dust";
                    if (r.nextInt(100) > 93) {
                        msg += "\n" + "Seems like you've got so much dust here... You might want to clean this up before it gets too messy!";
                    }
                    event.getChannel().sendMessage(EmoteReference.SAD + msg).queue();
                }
            }
            player.saveAsync();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Loot command").setDescription("**Loot the current chat for items, for usage in Mantaro's currency system.**\n" + "Currently, there are ``" + Items.ALL.length + "`` items available in chance," + "in which you have a `random chance` of getting one or more.").addField("Usage", "~>loot", false).build();
        }
    });
}
Also used : Player(net.kodehawa.mantarobot.db.entities.Player) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ZoneId(java.time.ZoneId) LocalDate(java.time.LocalDate) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) SecureRandom(java.security.SecureRandom) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 5 with Player

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

the class OptsCmd method register.

@Subscribe
public void register(CommandRegistry registry) {
    registry.register("opts", optsCmd = new SimpleCommand(Category.MODERATION, CommandPermission.ADMIN) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length == 0) {
                OptsCmd.onHelp(event);
                return;
            }
            if (args.length == 1 && args[0].equalsIgnoreCase("list") || args[0].equalsIgnoreCase("ls")) {
                StringBuilder builder = new StringBuilder();
                for (String s : Option.getAvaliableOptions()) {
                    builder.append(s).append("\n");
                }
                List<String> m = DiscordUtils.divideString(builder);
                List<String> messages = new LinkedList<>();
                boolean hasReactionPerms = event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION);
                for (String s1 : m) {
                    messages.add("**Mantaro's Options List**\n" + (hasReactionPerms ? "Use the arrow reactions to change pages. " : "Use &page >> and &page << to change pages and &cancel to end") + "*All options must be prefixed with `~>opts` when running them*\n" + String.format("```prolog\n%s```", s1));
                }
                if (hasReactionPerms) {
                    DiscordUtils.list(event, 45, false, messages);
                } else {
                    DiscordUtils.listText(event, 45, false, messages);
                }
                return;
            }
            if (args.length < 2) {
                event.getChannel().sendMessage(help(event)).queue();
                return;
            }
            StringBuilder name = new StringBuilder();
            if (args[0].equalsIgnoreCase("help")) {
                for (int i = 1; i < args.length; i++) {
                    String s = args[i];
                    if (name.length() > 0)
                        name.append(":");
                    name.append(s);
                    Option option = Option.getOptionMap().get(name.toString());
                    if (option != null) {
                        try {
                            EmbedBuilder builder = new EmbedBuilder().setAuthor(option.getOptionName(), null, event.getAuthor().getEffectiveAvatarUrl()).setDescription(option.getDescription()).setThumbnail("https://cdn.pixabay.com/photo/2012/04/14/16/26/question-34499_960_720.png").addField("Type", option.getType().toString(), false);
                            event.getChannel().sendMessage(builder.build()).queue();
                        } catch (IndexOutOfBoundsException ignored) {
                        }
                        return;
                    }
                }
                event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid option help name.").queue(message -> message.delete().queueAfter(10, TimeUnit.SECONDS));
                return;
            }
            for (int i = 0; i < args.length; i++) {
                String s = args[i];
                if (name.length() > 0)
                    name.append(":");
                name.append(s);
                Option option = Option.getOptionMap().get(name.toString());
                if (option != null) {
                    BiConsumer<GuildMessageReceivedEvent, String[]> callable = Option.getOptionMap().get(name.toString()).getEventConsumer();
                    try {
                        String[] a;
                        if (++i < args.length)
                            a = Arrays.copyOfRange(args, i, args.length);
                        else
                            a = new String[0];
                        callable.accept(event, a);
                        Player p = MantaroData.db().getPlayer(event.getAuthor());
                        if (p.getData().addBadgeIfAbsent(Badge.DID_THIS_WORK)) {
                            p.saveAsync();
                        }
                    } catch (IndexOutOfBoundsException ignored) {
                    }
                    return;
                }
            }
            event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid option or arguments.").queue(message -> message.delete().queueAfter(10, TimeUnit.SECONDS));
            event.getChannel().sendMessage(help(event)).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Options and Configurations Command").setDescription("**This command allows you to change Mantaro settings for this server.**\n" + "All values set are local rather than global, meaning that they will only effect this server.").addField("Usage", "The command is so big that we moved the description to the wiki. [Click here](https://github.com/Mantaro/MantaroBot/wiki/Configuration) to go to the Wiki Article.", false).build();
        }
    }).addOption("check:data", new Option("Data check.", "Checks the data values you have set on this server. **THIS IS NOT USER-FRIENDLY**", OptionType.GENERAL).setAction(event -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        // Map as follows: name, value
        Map<String, Object> fieldMap = mapObjects(guildData);
        if (fieldMap == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot retrieve values. Weird thing...").queue();
            return;
        }
        StringBuilder show = new StringBuilder();
        show.append("Options set for server **").append(event.getGuild().getName()).append("**\n\n");
        AtomicInteger ai = new AtomicInteger();
        for (Entry e : fieldMap.entrySet()) {
            if (e.getKey().equals("localPlayerExperience")) {
                continue;
            }
            show.append(ai.incrementAndGet()).append(".- `").append(e.getKey()).append("`");
            if (e.getValue() == null) {
                show.append(" **is not set to anything.").append("**\n");
            } else {
                show.append(" is set to: **").append(e.getValue()).append("**\n");
            }
        }
        List<String> toSend = DiscordUtils.divideString(1600, show);
        toSend.forEach(message -> event.getChannel().sendMessage(message).queue());
    }).setShortDescription("Checks the data values you have set on this server.")).addOption("reset:all", new Option("Options reset.", "Resets all options set on this server.", OptionType.GENERAL).setAction(event -> {
        // Temporary stuff.
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData temp = MantaroData.db().getGuild(event.getGuild()).getData();
        // The persistent data we wish to maintain.
        String premiumKey = temp.getPremiumKey();
        long quoteLastId = temp.getQuoteLastId();
        long ranPolls = temp.getQuoteLastId();
        String gameTimeoutExpectedAt = temp.getGameTimeoutExpectedAt();
        long cases = temp.getCases();
        // Assign everything all over again
        DBGuild newDbGuild = DBGuild.of(dbGuild.getId(), dbGuild.getPremiumUntil());
        GuildData newTmp = newDbGuild.getData();
        newTmp.setGameTimeoutExpectedAt(gameTimeoutExpectedAt);
        newTmp.setRanPolls(ranPolls);
        newTmp.setCases(cases);
        newTmp.setPremiumKey(premiumKey);
        newTmp.setQuoteLastId(quoteLastId);
        // weee
        newDbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Correctly reset your options!").queue();
    }));
}
Also used : Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Module(net.kodehawa.mantarobot.core.modules.Module) Arrays(java.util.Arrays) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) OptionType(net.kodehawa.mantarobot.options.core.OptionType) LinkedList(java.util.LinkedList) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Player(net.kodehawa.mantarobot.db.entities.Player) Utils.mapObjects(net.kodehawa.mantarobot.utils.Utils.mapObjects) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TimeUnit(java.util.concurrent.TimeUnit) Option(net.kodehawa.mantarobot.options.core.Option) List(java.util.List) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) Entry(java.util.Map.Entry) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Player(net.kodehawa.mantarobot.db.entities.Player) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) LinkedList(java.util.LinkedList) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Entry(java.util.Map.Entry) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Option(net.kodehawa.mantarobot.options.core.Option) LinkedList(java.util.LinkedList) List(java.util.List) Map(java.util.Map) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Player (net.kodehawa.mantarobot.db.entities.Player)19 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)15 Subscribe (com.google.common.eventbus.Subscribe)13 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)13 RateLimiter (net.kodehawa.mantarobot.utils.commands.RateLimiter)11 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)10 List (java.util.List)9 TimeUnit (java.util.concurrent.TimeUnit)8 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)8 ItemStack (net.kodehawa.mantarobot.commands.currency.item.ItemStack)8 Badge (net.kodehawa.mantarobot.commands.currency.profile.Badge)8 MantaroData (net.kodehawa.mantarobot.data.MantaroData)8 PlayerData (net.kodehawa.mantarobot.db.entities.helpers.PlayerData)8 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)8 Collectors (java.util.stream.Collectors)7 User (net.dv8tion.jda.core.entities.User)7 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)7 Module (net.kodehawa.mantarobot.core.modules.Module)7 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)7 java.util (java.util)6