Search in sources :

Example 21 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class OwnerCmd method blacklist.

@Command
public static void blacklist(CommandRegistry cr) {
    cr.register("blacklist", new SimpleCommand(Category.OWNER, CommandPermission.OWNER) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            MantaroObj obj = MantaroData.db().getMantaroData();
            if (args[0].equals("guild")) {
                if (args[1].equals("add")) {
                    if (MantaroBot.getInstance().getGuildById(args[2]) == null)
                        return;
                    obj.getBlackListedGuilds().add(args[2]);
                    event.getChannel().sendMessage(EmoteReference.CORRECT + "Blacklisted Guild: " + event.getJDA().getGuildById(args[2])).queue();
                    obj.save();
                } else if (args[1].equals("remove")) {
                    if (!obj.getBlackListedGuilds().contains(args[2]))
                        return;
                    obj.getBlackListedGuilds().remove(args[2]);
                    event.getChannel().sendMessage(EmoteReference.CORRECT + "Unblacklisted Guild: " + args[2]).queue();
                    obj.save();
                }
                return;
            }
            if (args[0].equals("user")) {
                if (args[1].equals("add")) {
                    if (MantaroBot.getInstance().getUserById(args[2]) == null)
                        return;
                    obj.getBlackListedUsers().add(args[2]);
                    event.getChannel().sendMessage(EmoteReference.CORRECT + "Blacklisted User: " + event.getJDA().getUserById(args[2])).queue();
                    obj.save();
                } else if (args[1].equals("remove")) {
                    if (!obj.getBlackListedUsers().contains(args[2]))
                        return;
                    obj.getBlackListedUsers().remove(args[2]);
                    event.getChannel().sendMessage(EmoteReference.CORRECT + "Unblacklisted User: " + event.getJDA().getUserById(args[2])).queue();
                    obj.save();
                }
            }
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Blacklist command").setDescription("**Blacklists a user (user argument) or a guild (guild argument) by id.**").setFooter("Examples", "~>blacklist user add/remove 293884638101897216\n" + "~>blacklist guild add/remove 305408763915927552").build();
        }
    });
}
Also used : MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) MantaroObj(net.kodehawa.mantarobot.data.entities.MantaroObj) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.modules.Command)

Example 22 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class OwnerCmd method owner.

@Command
public static void owner(CommandRegistry cr) {
    Map<String, Evaluator> evals = new HashMap<>();
    evals.put("js", (event, code) -> {
        ScriptEngine script = new ScriptEngineManager().getEngineByName("nashorn");
        script.put("mantaro", MantaroBot.getInstance());
        script.put("db", MantaroData.db());
        script.put("jda", event.getJDA());
        script.put("event", event);
        script.put("guild", event.getGuild());
        script.put("channel", event.getChannel());
        try {
            return script.eval(String.join("\n", "load(\"nashorn:mozilla_compat.js\");", "imports = new JavaImporter(java.util, java.io, java.net);", "(function() {", "with(imports) {", code, "}", "})()"));
        } catch (Exception e) {
            return e;
        }
    });
    evals.put("bsh", (event, code) -> {
        Interpreter interpreter = new Interpreter();
        try {
            interpreter.set("mantaro", MantaroBot.getInstance());
            interpreter.set("db", MantaroData.db());
            interpreter.set("jda", event.getJDA());
            interpreter.set("event", event);
            interpreter.set("guild", event.getGuild());
            interpreter.set("channel", event.getChannel());
            return interpreter.eval(String.join("\n", "import *;", code));
        } catch (Exception e) {
            return e;
        }
    });
    evals.put("cw", (event, code) -> {
        Object[] returns;
        boolean errored = false;
        try {
            returns = MantaroData.connectionWatcher().eval(code);
        } catch (RuntimeException e) {
            errored = true;
            returns = new Object[] { e.getMessage() };
        }
        String result = returns.length == 1 ? returns[0] == null ? null : String.valueOf(returns[0]) : Arrays.asList(returns).toString();
        if (errored)
            return new Error(result == null ? "Internal error" : result) {

                @Override
                public String toString() {
                    return getMessage();
                }
            };
        return result;
    });
    cr.register("owner", new SimpleCommand(Category.OWNER) {

        @Override
        public CommandPermission permission() {
            return CommandPermission.OWNER;
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Owner command").setDescription("`~>owner shutdown/forceshutdown`: Shutdowns the bot\n" + "`~>owner restart/forcerestart`: Restarts the bot.\n" + "`~>owner scheduleshutdown time <time>` - Schedules a fixed amount of seconds the bot will wait to be shutted down.\n" + "`~>owner varadd <pat/hug/greeting/splash>` - Adds a link or phrase to the specified list.\n" + "`~>owner eval <bsh/js/cw> <line of code>` - Evals a specified code snippet.\n" + "`~>owner cw <info/eval>` - Shows info or evals specified code in the Connection Watcher.\n" + "`~>owner premium add <id> <days>` - Adds premium to the specified user for x days.").addField("Shush.", "If you aren't Adrian or Kode you shouldn't be looking at this, huh 👀" + EmoteReference.EYES, false).build();
        }

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length < 1) {
                onHelp(event);
                return;
            }
            String option = args[0];
            if (option.equals("cw")) {
                if (args.length < 2) {
                    onHelp(event);
                    return;
                }
                String sub = args[1].split("\\s+")[0];
                if (sub.equals("info")) {
                    event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Connection Watcher info", null, null).setDescription(MantaroData.connectionWatcher().get().toString()).setColor(event.getGuild().getSelfMember().getColor()).setFooter("Asked by: " + event.getAuthor().getName(), null).build()).queue();
                } else if (sub.equals("eval")) {
                    String[] parts = event.getMessage().getRawContent().split(" ");
                    if (parts.length < 4) {
                        onHelp(event);
                        return;
                    }
                    Object[] returns;
                    boolean errored = false;
                    try {
                        returns = MantaroData.connectionWatcher().eval(String.join(" ", Arrays.copyOfRange(parts, 3, parts.length)));
                    } catch (RuntimeException e) {
                        errored = true;
                        returns = new Object[] { e.getMessage() };
                    }
                    String result = returns.length == 1 ? returns[0] == null ? null : String.valueOf(returns[0]) : Arrays.asList(returns).toString();
                    event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Evaluated " + (errored ? "and errored" : "with success"), null, event.getAuthor().getAvatarUrl()).setColor(errored ? Color.RED : Color.GREEN).setDescription(result == null ? "Executed successfully with no objects returned" : ("Executed " + (errored ? "and errored: " : "successfully and returned: ") + result)).setFooter("Asked by: " + event.getAuthor().getName(), null).build()).queue();
                } else {
                    onHelp(event);
                }
                return;
            }
            if (option.equals("premium")) {
                String sub = args[1].substring(0, args[1].indexOf(' '));
                if (sub.equals("add")) {
                    try {
                        String[] values = SPLIT_PATTERN.split(args[1], 3);
                        try {
                            Long.parseLong(values[1]);
                        } catch (Exception e) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid user id").queue();
                            return;
                        }
                        DBUser db = MantaroData.db().getUser(values[1]);
                        db.incrementPremium(TimeUnit.DAYS.toMillis(Long.parseLong(values[2])));
                        db.saveAsync();
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "The premium feature for user " + db.getId() + " now is until " + new Date(db.getPremiumUntil())).queue();
                        return;
                    } catch (IndexOutOfBoundsException e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify id and number of days").queue();
                        e.printStackTrace();
                        return;
                    }
                }
                if (sub.equals("guild")) {
                    try {
                        String[] values = SPLIT_PATTERN.split(args[1], 3);
                        DBGuild db = MantaroData.db().getGuild(values[1]);
                        db.incrementPremium(TimeUnit.DAYS.toMillis(Long.parseLong(values[2])));
                        db.saveAsync();
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "The premium feature for guild " + db.getId() + " now is until " + new Date(db.getPremiumUntil())).queue();
                        return;
                    } catch (IndexOutOfBoundsException e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify id and number of days").queue();
                        e.printStackTrace();
                        return;
                    }
                }
            }
            if (option.equals("shutdown") || option.equals("restart")) {
                if (args.length == 2) {
                    try {
                        notifyMusic(args[1]).get();
                    } catch (InterruptedException | ExecutionException ignored) {
                    }
                }
                try {
                    prepareShutdown(event);
                } catch (Exception e) {
                    log.warn(EmoteReference.ERROR + "Couldn't prepare shutdown." + e.toString(), e);
                    return;
                }
                if (option.equals("restart")) {
                    try {
                        MantaroData.connectionWatcher().reboot(false);
                    } catch (Exception e) {
                        log.error("Error restarting via manager, manual reboot required", e);
                        System.exit(-1);
                    }
                } else {
                    System.exit(0);
                }
                return;
            }
            if (option.equals("forceshutdown") || option.equals("forcerestart")) {
                if (args.length == 2) {
                    try {
                        notifyMusic(args[1]).get();
                    } catch (InterruptedException | ExecutionException ignored) {
                    }
                }
                try {
                    prepareShutdown(event);
                } catch (Exception e) {
                    log.warn(EmoteReference.ERROR + "Couldn't prepare shutdown. I don't care, I'm gonna restart anyway." + e.toString(), e);
                }
                if (option.equals("forcerestart")) {
                    try {
                        MantaroData.connectionWatcher().reboot(false);
                    } catch (Exception e) {
                        log.error("Error restarting via manager, manual reboot required", e);
                        System.exit(-1);
                    }
                } else {
                    System.exit(0);
                }
                return;
            }
            if (args.length < 2) {
                onHelp(event);
                return;
            }
            String value = args[1];
            if (option.equals("notifymusic")) {
                notifyMusic(value);
                event.getChannel().sendMessage(EmoteReference.MEGA + "Guilds playing music were notified!").queue();
                return;
            }
            String[] values = SPLIT_PATTERN.split(value, 2);
            if (values.length < 2) {
                onHelp(event);
                return;
            }
            String k = values[0], v = values[1];
            if (option.equals("scheduleshutdown") || option.equals("schedulerestart")) {
                boolean restart = option.equals("schedulerestart");
                if (k.equals("time")) {
                    double s = Double.parseDouble(v);
                    int millis = (int) (s * 1000);
                    Async.thread(millis, TimeUnit.MILLISECONDS, () -> {
                        try {
                            prepareShutdown(event);
                        } catch (Exception e) {
                            log.warn(EmoteReference.ERROR + "Couldn't prepare shutdown. I don't care, I'm gonna restart anyway." + e.toString(), e);
                        }
                        if (restart) {
                            try {
                                MantaroData.connectionWatcher().reboot(false);
                            } catch (Exception e) {
                                log.error("Error restarting via manager, manual reboot required", e);
                                System.exit(-1);
                            }
                        } else {
                            System.exit(0);
                        }
                    });
                    event.getChannel().sendMessage(EmoteReference.STOPWATCH + " Sleeping in " + s + " seconds...").queue();
                    return;
                }
                if (k.equals("connections")) {
                    int connections = Integer.parseInt(v);
                    IntSupplier currentConnections = () -> (int) event.getJDA().getVoiceChannels().stream().filter(voiceChannel -> voiceChannel.getMembers().contains(voiceChannel.getGuild().getSelfMember())).count();
                    Async.task("Watching Thread.", s -> {
                        if (currentConnections.getAsInt() > connections)
                            return;
                        try {
                            prepareShutdown(event);
                        } catch (Exception e) {
                            log.warn("Couldn't prepare shutdown. I don't care, I'm gonna do it anyway." + e.toString(), e);
                        }
                        if (restart) {
                            try {
                                MantaroData.connectionWatcher().reboot(false);
                            } catch (Exception e) {
                                log.error("Error restarting via manager, manual reboot required", e);
                                System.exit(-1);
                            }
                        } else {
                            System.exit(0);
                        }
                        s.shutdown();
                    }, 2, TimeUnit.SECONDS);
                    return;
                }
                onHelp(event);
                return;
            }
            if (option.equals("varadd")) {
                try {
                    String v1 = values[1];
                    switch(values[0]) {
                        case "pat":
                            ActionCmds.PATS.get().add(v1);
                            ActionCmds.PATS.save();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added to pat list: " + v).queue();
                            break;
                        case "hug":
                            ActionCmds.HUGS.get().add(v1);
                            ActionCmds.HUGS.save();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added to hug list: " + v).queue();
                            break;
                        case "greeting":
                            ActionCmds.GREETINGS.get().add(content.replace("varadd greeting ", ""));
                            ActionCmds.GREETINGS.save();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added to greet list: " + content.replace("greeting ", "")).queue();
                            break;
                        case "splash":
                            MantaroShard.SPLASHES.get().add(content.replace("varadd splash ", ""));
                            MantaroShard.SPLASHES.save();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added to splash list: " + content.replace("splash ", "")).queue();
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return;
            }
            if (option.equals("eval")) {
                Evaluator evaluator = evals.get(k);
                if (evaluator == null) {
                    onHelp(event);
                    return;
                }
                Object result = evaluator.eval(event, v);
                boolean errored = result instanceof Throwable;
                event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Evaluated " + (errored ? "and errored" : "with success"), null, event.getAuthor().getAvatarUrl()).setColor(errored ? Color.RED : Color.GREEN).setDescription(result == null ? "Executed successfully with no objects returned" : ("Executed " + (errored ? "and errored: " : "successfully and returned: ") + result.toString())).setFooter("Asked by: " + event.getAuthor().getName(), null).build()).queue();
                return;
            }
            if (option.equals("query")) {
                try {
                    String[] values1 = SPLIT_PATTERN.split(content);
                    String expression = content.replace(values1[0] + " ", "");
                    SQLDatabase.getInstance().run((conn) -> {
                        try {
                            ResultSet set;
                            try {
                                set = conn.prepareStatement(expression).executeQuery();
                            } catch (SQLException e) {
                                try {
                                    conn.prepareStatement(expression).execute();
                                    event.getChannel().sendMessage(" Query was successfully executed!").queue();
                                } catch (SQLException e1) {
                                    event.getChannel().sendMessage("Failed to execute query! " + Utils.paste(getStackTrace(e1))).queue();
                                }
                                return;
                            }
                            List<String> header = new ArrayList<>();
                            List<List<String>> table = new ArrayList<>();
                            ResultSetMetaData metaData = set.getMetaData();
                            int columnsCount = metaData.getColumnCount();
                            for (int i = 0; i < columnsCount; i++) {
                                header.add(metaData.getColumnName(i + 1));
                            }
                            while (set.next()) {
                                List<String> row = new ArrayList<>();
                                for (int i = 0; i < columnsCount; i++) {
                                    String s = String.valueOf(set.getString(i + 1)).trim();
                                    row.add(s.substring(0, Math.min(30, s.length())));
                                }
                                table.add(row);
                            }
                            String output = makeAsciiTable(header, table, null);
                            event.getChannel().sendMessage(Utils.paste(output)).queue();
                        } catch (SQLException e) {
                            event.getChannel().sendMessage(" Failed to build ascii table! " + Utils.paste(getStackTrace(e))).queue();
                        }
                    }).queue();
                } catch (SQLException e) {
                    event.getChannel().sendMessage(" Failed to run query! " + Utils.paste(getStackTrace(e))).queue();
                }
                return;
            }
            onHelp(event);
        }

        @Override
        public String[] splitArgs(String content) {
            return SPLIT_PATTERN.split(content, 2);
        }
    });
}
Also used : SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Color(java.awt.Color) java.util(java.util) Async(br.com.brjdevs.java.utils.async.Async) Utils(net.kodehawa.mantarobot.utils.Utils) Module(net.kodehawa.mantarobot.modules.Module) CompletableFuture(java.util.concurrent.CompletableFuture) MantaroShard(net.kodehawa.mantarobot.MantaroShard) Message(net.dv8tion.jda.core.entities.Message) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) SQLException(java.sql.SQLException) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) ResultSet(java.sql.ResultSet) CommandRegistry(net.kodehawa.mantarobot.modules.CommandRegistry) SQLDatabase(net.kodehawa.mantarobot.utils.sql.SQLDatabase) Command(net.kodehawa.mantarobot.modules.Command) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) IntSupplier(java.util.function.IntSupplier) PrintWriter(java.io.PrintWriter) Interpreter(bsh.Interpreter) DBUser(net.kodehawa.mantarobot.data.entities.DBUser) StringWriter(java.io.StringWriter) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) ScriptEngineManager(javax.script.ScriptEngineManager) Category(net.kodehawa.mantarobot.modules.commands.base.Category) MantaroObj(net.kodehawa.mantarobot.data.entities.MantaroObj) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) CommandPermission(net.kodehawa.mantarobot.modules.commands.CommandPermission) ScriptEngine(javax.script.ScriptEngine) MantaroData(net.kodehawa.mantarobot.data.MantaroData) ResultSetMetaData(java.sql.ResultSetMetaData) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) IntSupplier(java.util.function.IntSupplier) SQLException(java.sql.SQLException) ScriptEngineManager(javax.script.ScriptEngineManager) CommandPermission(net.kodehawa.mantarobot.modules.commands.CommandPermission) ResultSetMetaData(java.sql.ResultSetMetaData) ResultSet(java.sql.ResultSet) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Interpreter(bsh.Interpreter) ScriptEngine(javax.script.ScriptEngine) SQLException(java.sql.SQLException) ExecutionException(java.util.concurrent.ExecutionException) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) DBUser(net.kodehawa.mantarobot.data.entities.DBUser) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.modules.Command)

Example 23 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class CurrencyCmds method inventory.

@Command
public static void inventory(CommandRegistry cr) {
    cr.register("inventory", new SimpleCommand(Category.CURRENCY) {

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Player user = MantaroData.db().getPlayer(event.getMember());
            EmbedBuilder builder = baseEmbed(event, event.getMember().getEffectiveName() + "'s Inventory", event.getAuthor().getEffectiveAvatarUrl());
            List<ItemStack> list = user.getInventory().asList();
            if (list.isEmpty())
                builder.setDescription("There is only dust.");
            else
                user.getInventory().asList().forEach(stack -> {
                    long buyValue = stack.getItem().isBuyable() ? (long) (stack.getItem().getValue() * 1.1) : 0;
                    long sellValue = stack.getItem().isSellable() ? (long) (stack.getItem().getValue() * 0.9) : 0;
                    builder.addField(stack.getItem().getEmoji() + " " + stack.getItem().getName() + " x " + stack.getAmount(), String.format("**Price**: 📥 %d 📤 %d\n%s", buyValue, sellValue, stack.getItem().getDesc()), false);
                });
            event.getChannel().sendMessage(builder.build()).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Inventory command").setDescription("**Shows your current inventory.**").build();
        }
    });
}
Also used : Player(net.kodehawa.mantarobot.data.entities.Player) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.modules.Command)

Example 24 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class CurrencyCmds method market.

@Command
public static void market(CommandRegistry cr) {
    cr.register("market", new SimpleCommand(Category.CURRENCY) {

        RateLimiter rateLimiter = new RateLimiter(TimeUnit.SECONDS, 5);

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (!rateLimiter.process(event.getAuthor().getId())) {
                event.getChannel().sendMessage(EmoteReference.STOPWATCH + "Wait! You're calling me so fast that I can't get enough items!").queue();
                return;
            }
            Player player = MantaroData.db().getPlayer(event.getMember());
            if (args.length > 0) {
                int itemNumber = 1;
                String itemName = content.replace(args[0] + " ", "");
                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[1] + " ", "");
                    } 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;
                        }
                    }
                }
                if (itemNumber > 5000) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You can't buy more than 5000 items").queue();
                    return;
                }
                if (args[0].equals("sell")) {
                    try {
                        if (args[1].equals("all")) {
                            long all = player.getInventory().asList().stream().filter(item -> item.getItem().isSellable()).mapToLong(value -> (long) (value.getItem().getValue() * value.getAmount() * 0.9d)).sum();
                            if (args.length > 2 && args[2].equals("calculate")) {
                                event.getChannel().sendMessage(EmoteReference.THINKING + "You'll get **" + all + "** credits if you " + "sell all of your items").queue();
                                return;
                            }
                            player.getInventory().clearOnlySellables();
                            if (player.addMoney(all)) {
                                event.getChannel().sendMessage(EmoteReference.MONEY + "You sold all your inventory items and gained " + all + " credits!").queue();
                            } else {
                                event.getChannel().sendMessage(EmoteReference.MONEY + "You sold all your inventory items and gained " + all + " credits. But you already had too many credits. Your bag overflowed" + ".\nCongratulations, you exploded a Java long (how??). Here's a buggy money bag for you.").queue();
                            }
                            player.saveAsync();
                            return;
                        }
                        Item toSell = Items.fromAny(itemName).orElse(null);
                        if (!toSell.isSellable()) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot sell an item that cannot be sold.").queue();
                            return;
                        }
                        if (player.getInventory().asMap().getOrDefault(toSell, null) == null) {
                            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));
                        if (player.addMoney(amount)) {
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "You sold " + Math.abs(many) + " **" + toSell.getName() + "** and gained " + amount + " credits!").queue();
                        } else {
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "You sold **" + toSell.getName() + "** and gained" + amount + " credits. But you already had too many credits. Your bag overflowed" + ".\nCongratulations, you exploded a Java long (how??). Here's a buggy money bag for you.").queue();
                        }
                        player.save();
                        return;
                    } catch (Exception e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "Item doesn't exist or invalid syntax").queue();
                        e.printStackTrace();
                    }
                    return;
                }
                if (args[0].equals("buy")) {
                    Item itemToBuy = Items.fromAny(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.save();
                            event.getChannel().sendMessage(EmoteReference.OK + "Bought " + itemNumber + " " + itemToBuy.getEmoji() + " successfully. You now have " + player.getMoney() + " credits.").queue();
                        } else {
                            event.getChannel().sendMessage(EmoteReference.STOP + "You don't have enough money to buy this item.").queue();
                        }
                        return;
                    } catch (Exception e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "Item doesn't exist or invalid syntax.").queue();
                    }
                    return;
                }
            }
            EmbedBuilder embed = baseEmbed(event, EmoteReference.MARKET + "Mantaro Market");
            Stream.of(Items.ALL).forEach(item -> {
                if (!item.isHidden()) {
                    String buyValue = item.isBuyable() ? EmoteReference.BUY + "$" + String.valueOf((int) Math.floor(item.getValue() * 1.1)) + " " : "";
                    String sellValue = item.isSellable() ? EmoteReference.SELL + "$" + String.valueOf((int) Math.floor(item.getValue() * 0.9)) : "";
                    embed.addField(item.getEmoji() + " " + item.getName(), buyValue + sellValue, true);
                }
            });
            event.getChannel().sendMessage(embed.setThumbnail("https://i.imgur.com/OA7QCaM.png").build()).queue();
        }

        @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 substract 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.**", false).addField("To know", "If you don't have enough money you cannot buy the items.", false).addField("Information", "To buy and sell multiple items you need to do `~>market <buy/sell> <amount> <item>`", false).build();
        }
    });
}
Also used : Items(net.kodehawa.mantarobot.commands.currency.item.Items) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) UserData(net.kodehawa.mantarobot.data.entities.helpers.UserData) java.util(java.util) Member(net.dv8tion.jda.core.entities.Member) Utils(net.kodehawa.mantarobot.utils.Utils) Module(net.kodehawa.mantarobot.modules.Module) MantaroShard(net.kodehawa.mantarobot.MantaroShard) MantaroBot(net.kodehawa.mantarobot.MantaroBot) RethinkDB.r(com.rethinkdb.RethinkDB.r) Inventory(net.kodehawa.mantarobot.data.entities.helpers.Inventory) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Cursor(com.rethinkdb.net.Cursor) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) Pair(org.apache.commons.lang3.tuple.Pair) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) OptArgs(com.rethinkdb.model.OptArgs) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) CommandRegistry(net.kodehawa.mantarobot.modules.CommandRegistry) Command(net.kodehawa.mantarobot.modules.Command) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Player(net.kodehawa.mantarobot.data.entities.Player) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) PostLoadEvent(net.kodehawa.mantarobot.modules.events.PostLoadEvent) DBUser(net.kodehawa.mantarobot.data.entities.DBUser) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) RateLimiter(net.kodehawa.mantarobot.commands.currency.RateLimiter) Category(net.kodehawa.mantarobot.modules.commands.base.Category) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TimeUnit(java.util.concurrent.TimeUnit) Guild(net.dv8tion.jda.core.entities.Guild) Stream(java.util.stream.Stream) User(net.dv8tion.jda.core.entities.User) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) OrderBy(com.rethinkdb.gen.ast.OrderBy) Item(net.kodehawa.mantarobot.commands.currency.item.Item) Player(net.kodehawa.mantarobot.data.entities.Player) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) RateLimiter(net.kodehawa.mantarobot.commands.currency.RateLimiter) Item(net.kodehawa.mantarobot.commands.currency.item.Item) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.modules.Command)

Example 25 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent in project MantaroBot by Mantaro.

the class CurrencyCmds method rep.

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

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

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (event.getMessage().getMentionedUsers().isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention at least one user.").queue();
                return;
            }
            if (event.getMessage().getMentionedUsers().get(0).isBot()) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "You cannot rep a bot.").queue();
                return;
            }
            if (event.getMessage().getMentionedUsers().get(0).equals(event.getAuthor())) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "You cannot rep yourself.").queue();
                return;
            }
            if (event.getMessage().getMentionedUsers().isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "You need to mention one user.").queue();
                return;
            }
            if (!rateLimiter.process(event.getMember())) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You can only rep once every 12 hours.\n**You'll be able to use this command again in " + Utils.getVerboseTime(rateLimiter.tryAgainIn(event.getMember())) + ".**").queue();
                return;
            }
            User mentioned = event.getMessage().getMentionedUsers().get(0);
            Player player = MantaroData.db().getPlayer(event.getGuild().getMember(mentioned));
            player.addReputation(1L);
            player.saveAsync();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added reputation to **" + mentioned.getName() + "**").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 24 hours.", false).build();
        }
    });
    cr.registerAlias("rep", "reputation");
}
Also used : Player(net.kodehawa.mantarobot.data.entities.Player) DBUser(net.kodehawa.mantarobot.data.entities.DBUser) User(net.dv8tion.jda.core.entities.User) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) RateLimiter(net.kodehawa.mantarobot.commands.currency.RateLimiter) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.modules.Command)

Aggregations

GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)36 Command (net.kodehawa.mantarobot.modules.Command)31 SimpleCommand (net.kodehawa.mantarobot.modules.commands.SimpleCommand)31 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)25 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)15 MantaroData (net.kodehawa.mantarobot.data.MantaroData)15 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)15 CommandRegistry (net.kodehawa.mantarobot.modules.CommandRegistry)14 Module (net.kodehawa.mantarobot.modules.Module)14 Category (net.kodehawa.mantarobot.modules.commands.base.Category)14 TimeUnit (java.util.concurrent.TimeUnit)12 Color (java.awt.Color)11 Collectors (java.util.stream.Collectors)11 PostLoadEvent (net.kodehawa.mantarobot.modules.events.PostLoadEvent)11 Utils (net.kodehawa.mantarobot.utils.Utils)11 Slf4j (lombok.extern.slf4j.Slf4j)10 TextChannelGround (net.kodehawa.mantarobot.commands.currency.TextChannelGround)10 DBGuild (net.kodehawa.mantarobot.data.entities.DBGuild)9 Player (net.kodehawa.mantarobot.data.entities.Player)9 java.util (java.util)8