Search in sources :

Example 6 with RateLimiter

use of net.kodehawa.mantarobot.utils.commands.RateLimiter in project MantaroBot by Mantaro.

the class PlayerCmds method rep.

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

        final RateLimiter rateLimiter = new RateLimiter(TimeUnit.HOURS, 12);

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            long rl = rateLimiter.tryAgainIn(event.getMember());
            User user;
            if (content.isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention or put the name of at least one user.\n" + (rl > 0 ? "**You'll be able to use this command again in " + Utils.getVerboseTime(rateLimiter.tryAgainIn(event.getMember())) + ".**" : "You can rep someone now.")).queue();
                return;
            }
            List<User> mentioned = event.getMessage().getMentionedUsers();
            if (!mentioned.isEmpty() && mentioned.size() > 1) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You can only give reputation to one person!").queue();
                return;
            }
            Member member = Utils.findMember(event, event.getMember(), content);
            if (member == null)
                return;
            user = member.getUser();
            if (user.isBot()) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "You cannot rep a bot.\n" + (rl > 0 ? "**You'll be able to use this command again in " + Utils.getVerboseTime(rateLimiter.tryAgainIn(event.getMember())) + ".**" : "You can rep someone now.")).queue();
                return;
            }
            if (user.equals(event.getAuthor())) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "You cannot rep yourself.\n" + (rl > 0 ? "**You'll be able to use this command again in " + Utils.getVerboseTime(rateLimiter.tryAgainIn(event.getMember())) + ".**" : "You can rep someone now.")).queue();
                return;
            }
            if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                return;
            Player player = MantaroData.db().getPlayer(user);
            player.addReputation(1L);
            player.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added reputation to **" + member.getEffectiveName() + "**").queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Reputation command").setDescription("**Reps an user**").addField("Usage", "`~>rep <@user>` - **Gives reputation to x user**", false).addField("Parameters", "`@user` - user to mention", false).addField("Important", "Only usable every 12 hours.", false).build();
        }
    });
    cr.registerAlias("rep", "reputation");
}
Also used : Player(net.kodehawa.mantarobot.db.entities.Player) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) List(java.util.List) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 7 with RateLimiter

use of net.kodehawa.mantarobot.utils.commands.RateLimiter in project MantaroBot by Mantaro.

the class CurrencyCmds method market.

@Subscribe
public void market(CommandRegistry cr) {
    final RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 8);
    TreeCommand marketCommand = (TreeCommand) cr.register("market", 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) {
                    EmbedBuilder embed = baseEmbed(event, "Mantaro's Market").setThumbnail("https://png.icons8.com/metro/540/shopping-cart.png");
                    List<MessageEmbed.Field> fields = new LinkedList<>();
                    Stream.of(Items.ALL).forEach(item -> {
                        if (!item.isHidden()) {
                            String buyValue = item.isBuyable() ? String.format("$%d", item.getValue()) : "N/A";
                            String sellValue = item.isSellable() ? String.format("$%d", (int) Math.floor(item.getValue() * 0.9)) : "N/A";
                            fields.add(new MessageEmbed.Field(String.format("%s %s", item.getEmoji(), item.getName()), EmoteReference.BUY + buyValue + " " + EmoteReference.SELL + sellValue, true));
                        }
                    });
                    List<List<MessageEmbed.Field>> splitFields = DiscordUtils.divideFields(8, fields);
                    boolean hasReactionPerms = event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION);
                    if (hasReactionPerms) {
                        DiscordUtils.list(event, 120, false, embed, splitFields);
                    } else {
                        DiscordUtils.listText(event, 120, false, embed, splitFields);
                    }
                }
            };
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Mantaro's market").setDescription("**List current items for buying and selling.**").addField("Buying and selling", "To buy do ~>market buy <item emoji>. It will subtract the value from your money" + " and give you the item.\n" + "To sell do `~>market sell all` to sell all your items or `~>market sell <item emoji>` to sell the specified item. " + "**You'll get the sell value of the item on coins to spend.**\n" + "You can check the value of a single item using `~>market price <item emoji>`\n" + "You can send an item to the trash using `~>market dump <amount> <item emoji>`\n" + "Use `~>inventory -calculate` to check how much is your inventory worth.", false).addField("To know", "If you don't have enough money you cannot buy the items.\n" + "Note: Don't use the item id, it's just for aesthetic reasons, the internal IDs are different than the ones shown here!", false).addField("Information", "To buy and sell multiple items you need to do `~>market <buy/sell> <amount> <item>`", false).build();
        }
    });
    marketCommand.setPredicate((event) -> {
        if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
            return false;
        Player player = MantaroData.db().getPlayer(event.getMember());
        if (player.isLocked()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot access the market now.").queue();
            return false;
        }
        return true;
    });
    marketCommand.addSubCommand("dump", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            String itemName = content;
            int itemNumber = 1;
            boolean isMassive = !itemName.isEmpty() && itemName.split(" ")[0].matches("^[0-9]*$");
            if (isMassive) {
                try {
                    itemNumber = Math.abs(Integer.valueOf(itemName.split(" ")[0]));
                    itemName = itemName.replace(args[0], "").trim();
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid number of items to dump.").queue();
                    return;
                } catch (Exception e) {
                    onHelp(event);
                    return;
                }
            }
            Item item = Items.fromAny(itemName).orElse(null);
            if (item == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot check the dump a non-existent item!").queue();
                return;
            }
            Player player = MantaroData.db().getPlayer(event.getAuthor());
            if (!player.getInventory().containsItem(item)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot dump an item you don't have!").queue();
                return;
            }
            if (player.getInventory().getAmount(item) < itemNumber) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot dump more items than what you have.").queue();
                return;
            }
            player.getInventory().process(new ItemStack(item, -itemNumber));
            player.saveAsync();
            event.getChannel().sendMessage(String.format("%sSent %dx **%s %s** to the trash!", EmoteReference.CORRECT, itemNumber, item.getEmoji(), item.getName())).queue();
        }
    }).createSubCommandAlias("dump", "trash");
    marketCommand.addSubCommand("price", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            String[] args = content.split(" ");
            String itemName = content.replace(args[0] + " ", "");
            Item item = Items.fromAny(itemName).orElse(null);
            if (item == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot check the price of a non-existent item!").queue();
                return;
            }
            if (!item.isBuyable() && !item.isSellable()) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "This item is not available neither for sell or buy (could be an exclusive collectible)").queue();
                return;
            }
            if (!item.isBuyable()) {
                event.getChannel().sendMessage(EmoteReference.EYES + "This is a collectible item. (Sell value: " + ((int) (item.getValue() * 0.9)) + " credits)").queue();
                return;
            }
            event.getChannel().sendMessage(String.format("%sThe market value of %s**%s** is %s credits to buy it and you can get %s credits if you sell it.", EmoteReference.MARKET, item.getEmoji(), item.getName(), item.getValue(), (int) (item.getValue() * 0.9))).queue();
        }
    });
    marketCommand.addSubCommand("sell", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Player player = MantaroData.db().getPlayer(event.getMember());
            String[] args = content.split(" ");
            String itemName = content;
            int itemNumber = 1;
            boolean isMassive = !itemName.isEmpty() && itemName.split(" ")[0].matches("^[0-9]*$");
            if (isMassive) {
                try {
                    itemNumber = Math.abs(Integer.valueOf(itemName.split(" ")[0]));
                    itemName = itemName.replace(args[0], "").trim();
                } catch (NumberFormatException e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid number of items to buy.").queue();
                    return;
                } catch (Exception e) {
                    onHelp(event);
                    return;
                }
            }
            try {
                if (args[0].equals("all")) {
                    long all = player.getInventory().asList().stream().filter(item -> item.getItem().isSellable()).mapToLong(value -> (long) (value.getItem().getValue() * value.getAmount() * 0.9d)).sum();
                    player.getInventory().clearOnlySellables();
                    player.addMoney(all);
                    event.getChannel().sendMessage(String.format("%sYou sold all your inventory items and gained %d credits!", EmoteReference.MONEY, all)).queue();
                    player.saveAsync();
                    return;
                }
                Item toSell = Items.fromAny(itemName).orElse(null);
                if (toSell == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot sell a non-existant item.").queue();
                    return;
                }
                if (!toSell.isSellable()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot sell an item that cannot be sold.").queue();
                    return;
                }
                if (player.getInventory().getAmount(toSell) < 1) {
                    event.getChannel().sendMessage(EmoteReference.STOP + "You cannot sell an item you don't have.").queue();
                    return;
                }
                if (player.getInventory().getAmount(toSell) < itemNumber) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot sell more items than what you have.").queue();
                    return;
                }
                int many = itemNumber * -1;
                long amount = Math.round((toSell.getValue() * 0.9)) * Math.abs(many);
                player.getInventory().process(new ItemStack(toSell, many));
                player.addMoney(amount);
                player.getData().setMarketUsed(player.getData().getMarketUsed() + 1);
                event.getChannel().sendMessage(String.format("%sYou sold %d **%s** and gained %d credits!", EmoteReference.CORRECT, Math.abs(many), toSell.getName(), amount)).queue();
                player.saveAsync();
            } catch (Exception e) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid syntax.").queue();
            }
        }
    });
    marketCommand.addSubCommand("buy", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            Player player = MantaroData.db().getPlayer(event.getMember());
            String[] args = content.split(" ");
            String itemName = content;
            int itemNumber = 1;
            boolean isMassive = !itemName.isEmpty() && itemName.split(" ")[0].matches("^[0-9]*$");
            if (isMassive) {
                try {
                    itemNumber = Math.abs(Integer.valueOf(itemName.split(" ")[0]));
                    itemName = itemName.replace(args[0], "").trim();
                } catch (Exception e) {
                    if (e instanceof NumberFormatException) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid number of items to buy.").queue();
                    } else {
                        onHelp(event);
                        return;
                    }
                }
            }
            Item itemToBuy = Items.fromAnyNoId(itemName).orElse(null);
            if (itemToBuy == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot buy an unexistant item.").queue();
                return;
            }
            try {
                if (!itemToBuy.isBuyable()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot buy an item that cannot be bought.").queue();
                    return;
                }
                ItemStack stack = player.getInventory().getStackOf(itemToBuy);
                if (stack != null && !stack.canJoin(new ItemStack(itemToBuy, itemNumber))) {
                    // assume overflow
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot buy more of that object!").queue();
                    return;
                }
                if (player.removeMoney(itemToBuy.getValue() * itemNumber)) {
                    player.getInventory().process(new ItemStack(itemToBuy, itemNumber));
                    player.getData().addBadgeIfAbsent(Badge.BUYER);
                    player.getData().setMarketUsed(player.getData().getMarketUsed() + 1);
                    player.saveAsync();
                    event.getChannel().sendMessage(String.format("%sBought %d %s for %d credits successfully. You now have %d credits.", EmoteReference.OK, itemNumber, itemToBuy.getEmoji(), itemToBuy.getValue() * itemNumber, player.getMoney())).queue();
                } else {
                    event.getChannel().sendMessage(EmoteReference.STOP + "You don't have enough money to buy this item.").queue();
                }
            } catch (Exception e) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid syntax.").queue();
            }
        }
    });
}
Also used : 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) Utils(net.kodehawa.mantarobot.utils.Utils) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) RethinkDB.r(com.rethinkdb.RethinkDB.r) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Cursor(com.rethinkdb.net.Cursor) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.handleDefaultRatelimit(net.kodehawa.mantarobot.utils.Utils.handleDefaultRatelimit) OptArgs(com.rethinkdb.model.OptArgs) Inventory(net.kodehawa.mantarobot.db.entities.helpers.Inventory) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) Connection(com.rethinkdb.net.Connection) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) 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) Stream(java.util.stream.Stream) User(net.dv8tion.jda.core.entities.User) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Item(net.kodehawa.mantarobot.commands.currency.item.Item) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) Item(net.kodehawa.mantarobot.commands.currency.item.Item) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) List(java.util.List) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 8 with RateLimiter

use of net.kodehawa.mantarobot.utils.commands.RateLimiter in project MantaroBot by Mantaro.

the class DebugCmds method ping.

@Subscribe
public void ping(CommandRegistry cr) {
    final RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 5, true);
    final Random r = new Random();
    final String[] pingQuotes = { "W-Was I fast enough?", "What are you doing?", "W-What are you looking at?!", "Huh.", "Did I do well?", "What do you think?", "Does this happen often?", "Am I performing p-properly?", "<3", "*pats*", "Pong.", "Pang.", "Pung.", "Peng.", "Ping-pong? Yay!", "U-Uh... h-hi" };
    cr.register("ping", new SimpleCommand(Category.INFO) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                return;
            long start = System.currentTimeMillis();
            event.getChannel().sendTyping().queue(v -> {
                long ping = System.currentTimeMillis() - start;
                event.getChannel().sendMessage(EmoteReference.MEGA + "*" + pingQuotes[r.nextInt(pingQuotes.length)] + "* - My ping: " + ping + " ms (" + ratePing(ping) + ")  `Websocket:" + event.getJDA().getPing() + "ms`").queue();
                TextChannelGround.of(event).dropItemWithChance(5, 5);
            });
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Ping Command").setDescription("**Plays Ping-Pong with Discord and prints out the result.**").build();
        }
    });
}
Also used : MantaroInfo(net.kodehawa.mantarobot.MantaroInfo) Module(net.kodehawa.mantarobot.core.modules.Module) DefaultCommandProcessor(net.kodehawa.mantarobot.core.processor.DefaultCommandProcessor) Utils(net.kodehawa.mantarobot.utils.Utils) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) Random(java.util.Random) 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) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.handleDefaultRatelimit(net.kodehawa.mantarobot.utils.Utils.handleDefaultRatelimit) SnowflakeCacheView(net.dv8tion.jda.core.utils.cache.SnowflakeCacheView) JDA(net.dv8tion.jda.core.JDA) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) ManagementFactory(java.lang.management.ManagementFactory) LinkedList(java.util.LinkedList) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) CommandListener(net.kodehawa.mantarobot.core.listeners.command.CommandListener) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) JDAInfo(net.dv8tion.jda.core.JDAInfo) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) MantaroListener(net.kodehawa.mantarobot.core.listeners.MantaroListener) AsyncInfoMonitor(net.kodehawa.mantarobot.commands.info.AsyncInfoMonitor) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) TimeUnit(java.util.concurrent.TimeUnit) Guild(net.dv8tion.jda.core.entities.Guild) List(java.util.List) PlayerLibrary(com.sedmelluq.discord.lavaplayer.tools.PlayerLibrary) User(net.dv8tion.jda.core.entities.User) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) PreLoadEvent(net.kodehawa.mantarobot.core.listeners.events.PreLoadEvent) MantaroShard(net.kodehawa.mantarobot.core.shard.MantaroShard) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Random(java.util.Random) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 9 with RateLimiter

use of net.kodehawa.mantarobot.utils.commands.RateLimiter in project MantaroBot by Mantaro.

the class MoneyCmds method gamble.

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

        final RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 20, true);

        SecureRandom r = new SecureRandom();

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Player player = MantaroData.db().getPlayer(event.getMember());
            if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                return;
            if (player.getMoney() <= 0) {
                event.getChannel().sendMessage(EmoteReference.ERROR2 + "You're broke. Search for some credits first!").queue();
                return;
            }
            if (player.getMoney() > GAMBLE_ABSOLUTE_MAX_MONEY) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You have too much money! Maybe transfer or buy items? Now you can also use `~>slots`" + " for all your gambling needs! Thanks for not breaking the local bank. *(Gamble limit: " + GAMBLE_ABSOLUTE_MAX_MONEY + ")*").queue();
                return;
            }
            double multiplier;
            long i;
            int luck;
            try {
                switch(content) {
                    case "all":
                    case "everything":
                        i = player.getMoney();
                        multiplier = 1.3d + (r.nextInt(1450) / 1000d);
                        luck = 21 + (int) (multiplier * 13) + r.nextInt(18);
                        break;
                    case "half":
                        i = player.getMoney() == 1 ? 1 : player.getMoney() / 2;
                        multiplier = 1.2d + (r.nextInt(1350) / 1000d);
                        luck = 19 + (int) (multiplier * 13) + r.nextInt(18);
                        break;
                    case "quarter":
                        i = player.getMoney() == 1 ? 1 : player.getMoney() / 4;
                        multiplier = 1.1d + (r.nextInt(1250) / 1000d);
                        luck = 18 + (int) (multiplier * 12) + r.nextInt(18);
                        break;
                    default:
                        i = content.endsWith("%") ? Math.round(PERCENT_FORMAT.get().parse(content).doubleValue() * player.getMoney()) : Long.parseLong(content);
                        if (i > player.getMoney() || i < 0)
                            throw new UnsupportedOperationException();
                        multiplier = 1.1d + (i / player.getMoney() * r.nextInt(1300) / 1000d);
                        luck = 17 + (int) (multiplier * 13) + r.nextInt(12);
                        break;
                }
            } catch (NumberFormatException e) {
                event.getChannel().sendMessage(EmoteReference.ERROR2 + "Please type a valid number less than or equal to your current balance or" + " `all` to gamble all your credits.").queue();
                return;
            } catch (UnsupportedOperationException e) {
                event.getChannel().sendMessage(EmoteReference.ERROR2 + "Please type a value within your balance.").queue();
                return;
            } catch (ParseException e) {
                event.getChannel().sendMessage(EmoteReference.ERROR2 + "Please type a valid percentage value.").queue();
                return;
            }
            User user = event.getAuthor();
            long gains = (long) (i * multiplier);
            gains = Math.round(gains * 0.45);
            final int finalLuck = luck;
            final long finalGains = gains;
            if (i >= Integer.MAX_VALUE / 4) {
                player.setLocked(true);
                player.save();
                event.getChannel().sendMessage(String.format("%sYou're about to bet **%d** credits (which seems to be a lot). " + "Are you sure? Type **yes** to continue and **no** otherwise.", EmoteReference.WARNING, i)).queue();
                InteractiveOperations.create(event.getChannel(), 30, new InteractiveOperation() {

                    @Override
                    public int run(GuildMessageReceivedEvent e) {
                        if (e.getAuthor().getId().equals(user.getId())) {
                            if (e.getMessage().getContentRaw().equalsIgnoreCase("yes")) {
                                proceedGamble(event, player, finalLuck, random, i, finalGains);
                                return COMPLETED;
                            } else if (e.getMessage().getContentRaw().equalsIgnoreCase("no")) {
                                e.getChannel().sendMessage(EmoteReference.ZAP + "Cancelled bet.").queue();
                                player.setLocked(false);
                                player.saveAsync();
                                return COMPLETED;
                            }
                        }
                        return IGNORED;
                    }

                    @Override
                    public void onExpire() {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "Time to complete the operation has ran out.").queue();
                        player.setLocked(false);
                        player.saveAsync();
                    }
                });
                return;
            }
            proceedGamble(event, player, luck, random, i, gains);
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Gamble command").setDescription("Gambles your money").addField("Usage", "~>gamble <all/half/quarter> or ~>gamble <amount>\n" + "You can also use percentages now, for example `~>gamble 35%`", false).build();
        }
    });
}
Also used : InteractiveOperation(net.kodehawa.mantarobot.core.listeners.operations.core.InteractiveOperation) Player(net.kodehawa.mantarobot.db.entities.Player) User(net.dv8tion.jda.core.entities.User) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SecureRandom(java.security.SecureRandom) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) ParseException(java.text.ParseException) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 10 with RateLimiter

use of net.kodehawa.mantarobot.utils.commands.RateLimiter in project MantaroBot by Mantaro.

the class MoneyCmds method daily.

@Subscribe
public void daily(CommandRegistry cr) {
    final RateLimiter rateLimiter = new RateLimiter(TimeUnit.HOURS, 24);
    Random r = new Random();
    cr.register("daily", new SimpleCommand(Category.CURRENCY) {

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            long money = 150L;
            User mentionedUser = null;
            List<User> mentioned = event.getMessage().getMentionedUsers();
            if (!mentioned.isEmpty())
                mentionedUser = event.getMessage().getMentionedUsers().get(0);
            if (mentionedUser != null && mentionedUser.isBot()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot transfer your daily to a bot!").queue();
                return;
            }
            Player player = mentionedUser != null ? MantaroData.db().getPlayer(event.getGuild().getMember(mentionedUser)) : MantaroData.db().getPlayer(event.getMember());
            if (player.isLocked()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + (mentionedUser != null ? "That user cannot receive daily credits now." : "You cannot get daily credits now.")).queue();
                return;
            }
            if (!handleDefaultRatelimit(rateLimiter, event.getAuthor(), event))
                return;
            PlayerData playerData = player.getData();
            String streak;
            String playerId = player.getUserId();
            if (playerId.equals(event.getAuthor().getId())) {
                if (System.currentTimeMillis() - playerData.getLastDailyAt() < TimeUnit.HOURS.toMillis(50)) {
                    playerData.setDailyStreak(playerData.getDailyStreak() + 1);
                    streak = "Streak up! Current streak: `" + playerData.getDailyStreak() + "x`";
                } else {
                    if (playerData.getDailyStreak() == 0) {
                        streak = "First time claiming daily, have fun! (Come back for your streak tomorrow!)";
                    } else {
                        streak = String.format("2+ days have passed since your last daily, so your streak got reset :(\nOld streak: `%dx`", playerData.getDailyStreak());
                    }
                    playerData.setDailyStreak(1);
                }
                if (playerData.getDailyStreak() > 5) {
                    int bonus = 150;
                    if (playerData.getDailyStreak() > 15)
                        bonus += Math.min(700, Math.floor(150 * playerData.getDailyStreak() / 15));
                    streak += "\nYou won a bonus of $" + bonus + " for claiming your daily for 5 days in a row or more! (Included on the money shown!)";
                    money += bonus;
                }
                if (playerData.getDailyStreak() > 10) {
                    playerData.addBadgeIfAbsent(Badge.CLAIMER);
                }
                if (playerData.getDailyStreak() > 100) {
                    playerData.addBadgeIfAbsent(Badge.BIG_CLAIMER);
                }
            } else {
                Player authorPlayer = MantaroData.db().getPlayer(event.getAuthor());
                PlayerData authorPlayerData = authorPlayer.getData();
                if (System.currentTimeMillis() - authorPlayerData.getLastDailyAt() < TimeUnit.HOURS.toMillis(50)) {
                    authorPlayerData.setDailyStreak(authorPlayerData.getDailyStreak() + 1);
                    streak = String.format("Streak up! Current streak: `%dx`.\n*The streak was applied to your profile!*", authorPlayerData.getDailyStreak());
                } else {
                    if (authorPlayerData.getDailyStreak() == 0) {
                        streak = "First time claiming daily, have fun! (Come back for your streak tomorrow!)";
                    } else {
                        streak = String.format("2+ days have passed since your last daily, so your streak got reset :(\nOld streak: `%dx`", authorPlayerData.getDailyStreak());
                    }
                    authorPlayerData.setDailyStreak(1);
                }
                if (authorPlayerData.getDailyStreak() > 5) {
                    int bonus = 150;
                    if (authorPlayerData.getDailyStreak() > 15)
                        bonus += Math.min(700, Math.floor(150 * authorPlayerData.getDailyStreak() / 15));
                    ;
                    streak += "\n" + (mentionedUser == null ? "You" : mentionedUser.getName()) + " won a bonus of $" + bonus + " for claiming your daily for 5 days in a row or more! (Included on the money shown!)";
                    money += bonus;
                }
                if (authorPlayerData.getDailyStreak() > 10) {
                    authorPlayerData.addBadgeIfAbsent(Badge.CLAIMER);
                }
                if (authorPlayerData.getDailyStreak() > 100) {
                    playerData.addBadgeIfAbsent(Badge.BIG_CLAIMER);
                }
                authorPlayerData.setLastDailyAt(System.currentTimeMillis());
                authorPlayer.save();
            }
            if (mentionedUser != null && !mentionedUser.getId().equals(event.getAuthor().getId())) {
                money = money + r.nextInt(90);
                if (mentionedUser.getId().equals(player.getData().getMarriedWith())) {
                    if (player.getInventory().containsItem(Items.RING)) {
                        money = money + r.nextInt(70);
                    }
                }
                player.addMoney(money);
                playerData.setLastDailyAt(System.currentTimeMillis());
                player.save();
                event.getChannel().sendMessage(EmoteReference.CORRECT + "I gave your **$" + money + "** daily credits to " + mentionedUser.getName() + "\n\n" + streak).queue();
                return;
            }
            player.addMoney(money);
            playerData.setLastDailyAt(System.currentTimeMillis());
            player.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "You got **$" + money + "** daily credits.\n\n" + streak).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Daily command").setDescription("**Gives you $150 credits per day (or between 150 and 180 if you transfer it to another person)**.\n" + "This command gives a reward for claiming it every day.").build();
        }
    });
    cr.registerAlias("daily", "dailies");
}
Also used : Player(net.kodehawa.mantarobot.db.entities.Player) User(net.dv8tion.jda.core.entities.User) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SecureRandom(java.security.SecureRandom) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Subscribe (com.google.common.eventbus.Subscribe)10 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)10 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)10 RateLimiter (net.kodehawa.mantarobot.utils.commands.RateLimiter)10 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)9 Player (net.kodehawa.mantarobot.db.entities.Player)8 User (net.dv8tion.jda.core.entities.User)6 SecureRandom (java.security.SecureRandom)5 List (java.util.List)4 TimeUnit (java.util.concurrent.TimeUnit)3 Collectors (java.util.stream.Collectors)3 ItemStack (net.kodehawa.mantarobot.commands.currency.item.ItemStack)3 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)3 Module (net.kodehawa.mantarobot.core.modules.Module)3 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)3 StringUtils (br.com.brjdevs.java.utils.texts.StringUtils)2 RethinkDB.r (com.rethinkdb.RethinkDB.r)2 OptArgs (com.rethinkdb.model.OptArgs)2 Connection (com.rethinkdb.net.Connection)2 Cursor (com.rethinkdb.net.Cursor)2