Search in sources :

Example 76 with Subscribe

use of com.google.common.eventbus.Subscribe 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 77 with Subscribe

use of com.google.common.eventbus.Subscribe 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 78 with Subscribe

use of com.google.common.eventbus.Subscribe 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 79 with Subscribe

use of com.google.common.eventbus.Subscribe 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)

Example 80 with Subscribe

use of com.google.common.eventbus.Subscribe in project MantaroBot by Mantaro.

the class UtilsCmds method dictionary.

@Subscribe
public void dictionary(CommandRegistry registry) {
    registry.register("dictionary", new SimpleCommand(Category.UTILS) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length == 0) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a word.").queue();
                return;
            }
            String word = content;
            JSONObject main;
            String definition, part_of_speech, headword, example;
            try {
                main = new JSONObject(Utils.wgetResty("http://api.pearson.com/v2/dictionaries/laes/entries?headword=" + word, event));
                JSONArray results = main.getJSONArray("results");
                JSONObject result = results.getJSONObject(0);
                JSONArray senses = result.getJSONArray("senses");
                headword = result.getString("headword");
                if (result.has("part_of_speech"))
                    part_of_speech = result.getString("part_of_speech");
                else
                    part_of_speech = "Not found.";
                if (senses.getJSONObject(0).get("definition") instanceof JSONArray)
                    definition = senses.getJSONObject(0).getJSONArray("definition").getString(0);
                else
                    definition = senses.getJSONObject(0).getString("definition");
                try {
                    if (senses.getJSONObject(0).getJSONArray("translations").getJSONObject(0).get("example") instanceof JSONArray) {
                        example = senses.getJSONObject(0).getJSONArray("translations").getJSONObject(0).getJSONArray("example").getJSONObject(0).getString("text");
                    } else {
                        example = senses.getJSONObject(0).getJSONArray("translations").getJSONObject(0).getJSONObject("example").getString("text");
                    }
                } catch (Exception e) {
                    example = "Not found";
                }
            } catch (Exception e) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "No results.").queue();
                return;
            }
            EmbedBuilder eb = new EmbedBuilder();
            eb.setAuthor("Definition for " + word, null, event.getAuthor().getAvatarUrl()).setThumbnail("https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Wikt_dynamic_dictionary_logo.svg/1000px-Wikt_dynamic_dictionary_logo.svg.png").addField("Definition", "**" + definition + "**", false).addField("Example", "**" + example + "**", false).setDescription(String.format("**Part of speech:** `%s`\n" + "**Headword:** `%s`\n", part_of_speech, headword));
            event.getChannel().sendMessage(eb.build()).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Dictionary command").setDescription("**Looks up a word in the dictionary.**").addField("Usage", "`~>dictionary <word>` - Searches a word in the dictionary.", false).addField("Parameters", "`word` - The word to look for", false).build();
        }
    });
}
Also used : EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) JSONObject(org.json.JSONObject) JSONArray(org.json.JSONArray) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Subscribe (com.google.common.eventbus.Subscribe)179 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)46 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)44 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)29 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)26 MantaroData (net.kodehawa.mantarobot.data.MantaroData)25 List (java.util.List)23 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)22 Utils (net.kodehawa.mantarobot.utils.Utils)22 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)21 Module (net.kodehawa.mantarobot.core.modules.Module)21 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)18 TimeUnit (java.util.concurrent.TimeUnit)16 Collectors (java.util.stream.Collectors)16 MantaroBot (net.kodehawa.mantarobot.MantaroBot)15 Player (net.kodehawa.mantarobot.db.entities.Player)15 DiscordUtils (net.kodehawa.mantarobot.utils.DiscordUtils)15 RateLimiter (net.kodehawa.mantarobot.utils.commands.RateLimiter)14 SubCommand (net.kodehawa.mantarobot.core.modules.commands.SubCommand)13 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)13