Search in sources :

Example 11 with CommandRegistry

use of net.kodehawa.mantarobot.core.CommandRegistry 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)

Example 12 with CommandRegistry

use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.

the class OsuStatsCmd method osustats.

@Subscribe
public void osustats(CommandRegistry cr) {
    ITreeCommand osuCommand = (SimpleTreeCommand) cr.register("osustats", new SimpleTreeCommand(Category.GAMES) {

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "osu! command").setDescription("**Retrieves information from osu! (Players and scores)**.").addField("Usage", "`~>osu best <player>` - **Retrieves best scores of the user specified in the specified game mode**.\n" + "`~>osu recent <player>` - **Retrieves recent scores of the user specified in the specified game mode.**\n" + "`~>osu user <player>` - **Retrieves information about a osu! player**.\n", false).addField("Parameters", "`player` - **The osu! player to look info for.**", false).build();
        }
    });
    osuCommand.addSubCommand("best", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            event.getChannel().sendMessage(EmoteReference.STOPWATCH + "Retrieving information from osu! server...").queue(sentMessage -> {
                Future<String> task = pool.submit(() -> best(content));
                try {
                    sentMessage.editMessage(task.get(16, TimeUnit.SECONDS)).queue();
                } catch (Exception e) {
                    if (e instanceof TimeoutException) {
                        task.cancel(true);
                        sentMessage.editMessage(EmoteReference.ERROR + "The osu! api seems to be taking a nap. Maybe try again later?").queue();
                    } else {
                        SentryHelper.captureException("Error retrieving results from osu!API", e, OsuStatsCmd.class);
                    }
                }
            });
        }
    });
    osuCommand.addSubCommand("recent", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            event.getChannel().sendMessage(EmoteReference.STOPWATCH + "Retrieving information from server...").queue(sentMessage -> {
                Future<String> task = pool.submit(() -> recent(content));
                try {
                    sentMessage.editMessage(task.get(16, TimeUnit.SECONDS)).queue();
                } catch (Exception e) {
                    if (e instanceof TimeoutException) {
                        task.cancel(true);
                        sentMessage.editMessage(EmoteReference.ERROR + "The osu! api seems to be taking a nap. Maybe try again later?").queue();
                    } else
                        log.warn("Exception thrown while fetching data", e);
                }
            });
        }
    });
    osuCommand.addSubCommand("user", new SubCommand() {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            event.getChannel().sendMessage(user(content)).queue();
        }
    });
    cr.registerAlias("osustats", "osu");
}
Also used : Module(net.kodehawa.mantarobot.core.modules.Module) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) SimpleTreeCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleTreeCommand) java.util.concurrent(java.util.concurrent) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) DecimalFormat(java.text.DecimalFormat) SentryHelper(net.kodehawa.mantarobot.utils.SentryHelper) HashMap(java.util.HashMap) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MantaroBot(net.kodehawa.mantarobot.MantaroBot) java.awt(java.awt) Slf4j(lombok.extern.slf4j.Slf4j) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) JSONException(org.json.JSONException) List(java.util.List) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) com.osu.api.ciyfhx(com.osu.api.ciyfhx) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) Map(java.util.Map) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Subscribe(com.google.common.eventbus.Subscribe) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) OsuMod(net.kodehawa.mantarobot.commands.osu.OsuMod) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) SimpleTreeCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleTreeCommand) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) JSONException(org.json.JSONException) Subscribe(com.google.common.eventbus.Subscribe)

Example 13 with CommandRegistry

use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.

the class OwnerCmd method badge.

@Subscribe
public void badge(CommandRegistry cr) {
    cr.register("addbadge", new SimpleCommand(Category.OWNER, CommandPermission.OWNER) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (event.getMessage().getMentionedUsers().isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to give me an user to apply the badge to!").queue();
                return;
            }
            if (args.length != 2) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Wrong args length").queue();
                return;
            }
            String b = args[1];
            List<User> users = event.getMessage().getMentionedUsers();
            Badge badge = Badge.lookupFromString(b);
            if (badge == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "No badge with that enum name! Valid badges: " + Arrays.stream(Badge.values()).map(b1 -> "`" + b1.name() + "`").collect(Collectors.joining(" ,"))).queue();
                return;
            }
            for (User u : users) {
                Player p = MantaroData.db().getPlayer(u);
                p.getData().addBadgeIfAbsent(badge);
                p.saveAsync();
            }
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Added badge " + badge + " to " + users.stream().map(User::getName).collect(Collectors.joining(" ,"))).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return null;
        }
    });
    cr.register("removebadge", new SimpleCommand(Category.OWNER, CommandPermission.OWNER) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (event.getMessage().getMentionedUsers().isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to give me an user to remove the badge from!").queue();
                return;
            }
            if (args.length != 2) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "Wrong args length").queue();
                return;
            }
            String b = args[1];
            List<User> users = event.getMessage().getMentionedUsers();
            Badge badge = Badge.lookupFromString(b);
            if (badge == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "No badge with that enum name! Valid badges: " + Arrays.stream(Badge.values()).map(b1 -> "`" + b1.name() + "`").collect(Collectors.joining(" ,"))).queue();
                return;
            }
            for (User u : users) {
                Player p = MantaroData.db().getPlayer(u);
                p.getData().removeBadge(badge);
                p.saveAsync();
            }
            event.getChannel().sendMessage(String.format("%sRemoved badge %s from %s", EmoteReference.CORRECT, badge, users.stream().map(User::getName).collect(Collectors.joining(" ,")))).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return null;
        }
    });
}
Also used : Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) CompilationException(com.github.natanbc.javaeval.CompilationException) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) JavaEvaluator(com.github.natanbc.javaeval.JavaEvaluator) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Player(net.kodehawa.mantarobot.db.entities.Player) Interpreter(bsh.Interpreter) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) CompilationResult(com.github.natanbc.javaeval.CompilationResult) ScriptEngineManager(javax.script.ScriptEngineManager) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) User(net.dv8tion.jda.core.entities.User) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) MantaroObj(net.kodehawa.mantarobot.db.entities.MantaroObj) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) ScriptEngine(javax.script.ScriptEngine) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) Player(net.kodehawa.mantarobot.db.entities.Player) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) User(net.dv8tion.jda.core.entities.User) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) List(java.util.List) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 14 with CommandRegistry

use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.

the class OwnerCmd method eval.

@Subscribe
public void eval(CommandRegistry cr) {
    // has no state
    JavaEvaluator javaEvaluator = new JavaEvaluator();
    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("java", (event, code) -> {
        try {
            CompilationResult r = javaEvaluator.compile().addCompilerOptions("-Xlint:unchecked").source("Eval", JAVA_EVAL_IMPORTS + "\n\n" + "public class Eval {\n" + "   public static Object run(GuildMessageReceivedEvent event) {\n" + "       try {\n" + "           return null;\n" + "       } finally {\n" + "           " + (code + ";").replaceAll(";{2,}", ";") + "\n" + "       }\n" + "   }\n" + "}").execute();
            EvalClassLoader ecl = new EvalClassLoader();
            r.getClasses().forEach((name, bytes) -> ecl.define(bytes));
            return ecl.loadClass("Eval").getMethod("run", GuildMessageReceivedEvent.class).invoke(null, event);
        } catch (CompilationException e) {
            StringBuilder sb = new StringBuilder("\n");
            if (e.getCompilerOutput() != null)
                sb.append(e.getCompilerOutput());
            if (!e.getDiagnostics().isEmpty()) {
                if (sb.length() > 0)
                    sb.append("\n\n");
                e.getDiagnostics().forEach(d -> sb.append(d).append('\n'));
            }
            return new Error(sb.toString()) {

                @Override
                public String toString() {
                    return getMessage();
                }
            };
        } catch (Exception e) {
            return e;
        }
    });
    cr.register("eval", new SimpleCommand(Category.OWNER, CommandPermission.OWNER) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Evaluator evaluator = evals.get(args[0]);
            if (evaluator == null) {
                onHelp(event);
                return;
            }
            String[] values = SPLIT_PATTERN.split(content, 2);
            if (values.length < 2) {
                onHelp(event);
                return;
            }
            String v = values[1];
            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();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Eval cmd").setDescription("**Evaluates stuff (A: js/bsh)**").build();
        }
    });
}
Also used : Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) CompilationException(com.github.natanbc.javaeval.CompilationException) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) JavaEvaluator(com.github.natanbc.javaeval.JavaEvaluator) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Player(net.kodehawa.mantarobot.db.entities.Player) Interpreter(bsh.Interpreter) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) CompilationResult(com.github.natanbc.javaeval.CompilationResult) ScriptEngineManager(javax.script.ScriptEngineManager) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) Slf4j(lombok.extern.slf4j.Slf4j) List(java.util.List) User(net.dv8tion.jda.core.entities.User) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) MantaroObj(net.kodehawa.mantarobot.db.entities.MantaroObj) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) ScriptEngine(javax.script.ScriptEngine) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) CompilationException(com.github.natanbc.javaeval.CompilationException) Interpreter(bsh.Interpreter) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ScriptEngineManager(javax.script.ScriptEngineManager) JavaEvaluator(com.github.natanbc.javaeval.JavaEvaluator) ScriptEngine(javax.script.ScriptEngine) CompilationException(com.github.natanbc.javaeval.CompilationException) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) CompilationResult(com.github.natanbc.javaeval.CompilationResult) JavaEvaluator(com.github.natanbc.javaeval.JavaEvaluator) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 15 with CommandRegistry

use of net.kodehawa.mantarobot.core.CommandRegistry in project MantaroBot by Mantaro.

the class PlayerCmds method badges.

@Subscribe
public void badges(CommandRegistry cr) {
    final Random r = new Random();
    ITreeCommand badgeCommand = (ITreeCommand) cr.register("badges", 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) {
                    Map<String, Optional<String>> t = StringUtils.parse(content.isEmpty() ? new String[] {} : content.split("\\s+"));
                    content = Utils.replaceArguments(t, content, "brief");
                    Member member = Utils.findMember(event, event.getMember(), content);
                    if (member == null)
                        return;
                    User toLookup = member.getUser();
                    Player player = MantaroData.db().getPlayer(toLookup);
                    PlayerData playerData = player.getData();
                    if (!t.isEmpty() && t.containsKey("brief")) {
                        event.getChannel().sendMessage(String.format("**%s's badges:**\n%s", member.getEffectiveName(), playerData.getBadges().stream().map(b -> "*" + b.display + "*").collect(Collectors.joining(", ")))).queue();
                        return;
                    }
                    List<Badge> badges = playerData.getBadges();
                    Collections.sort(badges);
                    // Show the message that tells the person that they can get a free badge for upvoting mantaro one out of 3 times they use this command.
                    // The message stops appearing when they upvote.
                    String toShow = "If you think you got a new badge and it doesn't appear here, please use `~>profile` and then run this command again.\n" + "Use `~>badges info <badge name>` to get more information about a badge.\n" + ((r.nextInt(3) == 0 && !playerData.hasBadge(Badge.UPVOTER) ? "**You can get a free badge for " + "[up-voting Mantaro on discordbots.org](https://discordbots.org/bot/mantaro)!** (It might take some minutes to process)\n\n" : "\n")) + badges.stream().map(badge -> String.format("**%s:** *%s*", badge, badge.description)).collect(Collectors.joining("\n"));
                    if (toShow.isEmpty())
                        toShow = "No badges to show (yet!)";
                    List<String> parts = DiscordUtils.divideString(MessageEmbed.TEXT_MAX_LENGTH, toShow);
                    DiscordUtils.list(event, 30, false, (current, max) -> new EmbedBuilder().setAuthor("Badges achieved by " + toLookup.getName()).setColor(event.getMember().getColor() == null ? Color.PINK : event.getMember().getColor()).setThumbnail(toLookup.getEffectiveAvatarUrl()), parts);
                }
            };
        }

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

        @Override
        protected void call(GuildMessageReceivedEvent event, String content) {
            if (content.isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a badge to see the info of.").queue();
                return;
            }
            Badge badge = Badge.lookupFromString(content);
            if (badge == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "There's no such badge...").queue();
                return;
            }
            Player p = MantaroData.db().getPlayer(event.getAuthor());
            Message message = new MessageBuilder().setEmbed(new EmbedBuilder().setAuthor("Badge information for " + badge.display).setDescription(String.join("\n", EmoteReference.BLUE_SMALL_MARKER + "**Name:** " + badge.display, EmoteReference.BLUE_SMALL_MARKER + "**Description:** " + badge.description, EmoteReference.BLUE_SMALL_MARKER + "**Achieved:** " + p.getData().getBadges().stream().anyMatch(b -> b == badge))).setThumbnail("attachment://icon.png").setColor(Color.CYAN).build()).build();
            event.getChannel().sendFile(badge.icon, "icon.png", message).queue();
        }
    });
}
Also used : Items(net.kodehawa.mantarobot.commands.currency.item.Items) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) MantaroInfo(net.kodehawa.mantarobot.MantaroInfo) Module(net.kodehawa.mantarobot.core.modules.Module) java.util(java.util) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) Utils(net.kodehawa.mantarobot.utils.Utils) RateLimiter(net.kodehawa.mantarobot.utils.commands.RateLimiter) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) MantaroBot(net.kodehawa.mantarobot.MantaroBot) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Utils.handleDefaultRatelimit(net.kodehawa.mantarobot.utils.Utils.handleDefaultRatelimit) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Inventory(net.kodehawa.mantarobot.db.entities.helpers.Inventory) Response(okhttp3.Response) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) ItemStack(net.kodehawa.mantarobot.commands.currency.item.ItemStack) ResponseBody(okhttp3.ResponseBody) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Request(okhttp3.Request) UserData(net.kodehawa.mantarobot.db.entities.helpers.UserData) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) IOException(java.io.IOException) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) java.awt(java.awt) TimeUnit(java.util.concurrent.TimeUnit) List(java.util.List) OkHttpClient(okhttp3.OkHttpClient) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) FinderUtil(com.jagrosh.jdautilities.utils.FinderUtil) Player(net.kodehawa.mantarobot.db.entities.Player) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) PlayerData(net.kodehawa.mantarobot.db.entities.helpers.PlayerData) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) TreeCommand(net.kodehawa.mantarobot.core.modules.commands.TreeCommand) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Subscribe (com.google.common.eventbus.Subscribe)21 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)21 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)21 Module (net.kodehawa.mantarobot.core.modules.Module)21 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)21 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)21 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)20 MantaroData (net.kodehawa.mantarobot.data.MantaroData)20 Utils (net.kodehawa.mantarobot.utils.Utils)17 TimeUnit (java.util.concurrent.TimeUnit)16 List (java.util.List)15 MantaroBot (net.kodehawa.mantarobot.MantaroBot)15 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)14 Collectors (java.util.stream.Collectors)13 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)13 DiscordUtils (net.kodehawa.mantarobot.utils.DiscordUtils)13 java.awt (java.awt)12 java.util (java.util)12 Command (net.kodehawa.mantarobot.core.modules.commands.base.Command)11 Permission (net.dv8tion.jda.core.Permission)10