Search in sources :

Example 31 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent 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 32 with GuildMessageReceivedEvent

use of net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent 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)

Example 33 with GuildMessageReceivedEvent

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

the class ImageCmd method call.

@Override
protected void call(GuildMessageReceivedEvent event, String content) {
    String random;
    String id = "";
    if (images.size() == 1) {
        if (type != null) {
            Pair<String, String> result = weebapi.getRandomImageByType(type, false, null);
            images = Collections.singletonList(result.getKey());
            id = result.getValue();
        }
        // Guaranteed random selection :^).
        random = images.get(0);
    } else {
        random = random(images);
    }
    String extension = random.substring(random.lastIndexOf("."));
    MessageBuilder builder = new MessageBuilder();
    builder.append(EmoteReference.TALKING);
    if (!noMentions) {
        List<User> users = event.getMessage().getMentionedUsers();
        String names = "";
        if (users != null)
            names = users.stream().map(user -> event.getGuild().getMember(user).getEffectiveName()).collect(Collectors.joining(", "));
        if (!names.isEmpty())
            builder.append("**").append(names).append("**, ");
    }
    builder.append(toSend);
    event.getChannel().sendFile(CACHE.getInput(random), imageName + "-" + id + "." + extension, builder.build()).queue();
}
Also used : NoArgsCommand(net.kodehawa.mantarobot.core.modules.commands.NoArgsCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Collectors(java.util.stream.Collectors) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) List(java.util.List) URLCache(net.kodehawa.mantarobot.utils.cache.URLCache) User(net.dv8tion.jda.core.entities.User) Pair(org.apache.commons.lang3.tuple.Pair) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Collections(java.util.Collections) User(net.dv8tion.jda.core.entities.User) MessageBuilder(net.dv8tion.jda.core.MessageBuilder)

Example 34 with GuildMessageReceivedEvent

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

the class CommandListener method onEvent.

@Override
public void onEvent(Event event) {
    if (event instanceof ShardMonitorEvent) {
        if (MantaroBot.getInstance().getShardedMantaro().getShards()[shardId].getEventManager().getLastJDAEventTimeDiff() > 30000)
            return;
        // Hey, this listener is alive! (This won't pass if somehow this is blocked)
        ((ShardMonitorEvent) event).alive(shardId, ShardMonitorEvent.COMMAND_LISTENER);
        return;
    }
    if (event instanceof GuildMessageReceivedEvent) {
        GuildMessageReceivedEvent msg = (GuildMessageReceivedEvent) event;
        // Inserts a cached message into the cache. This only holds the id and the content, and is way lighter than saving the entire jda object.
        messageCache.put(msg.getMessage().getId(), Optional.of(new CachedMessage(msg.getAuthor().getIdLong(), msg.getMessage().getContentDisplay())));
        // Ignore myself and bots.
        if (msg.getAuthor().isBot() || msg.getAuthor().equals(msg.getJDA().getSelfUser()))
            return;
        shard.getCommandPool().execute(() -> onCommand(msg));
    }
}
Also used : ShardMonitorEvent(net.kodehawa.mantarobot.core.listeners.events.ShardMonitorEvent) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) CachedMessage(net.kodehawa.mantarobot.core.listeners.entities.CachedMessage)

Example 35 with GuildMessageReceivedEvent

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

the class ImageCmds method getImage.

private static EmbedBuilder getImage(int argsCount, String requestType, String url, String rating, String[] messageArray, GuildMessageReceivedEvent event) {
    EmbedBuilder builder = new EmbedBuilder();
    if (!nsfwCheck(event, false, false))
        return builder.setDescription("Cannot send a lewd image in a non-nsfw channel.");
    String json = Utils.wget(url, event);
    try {
        YandereImageData[] imageData = GsonDataManager.GSON_PRETTY.fromJson(json, YandereImageData[].class);
        List<YandereImageData> filter = new ArrayList<>(Arrays.asList(imageData)).stream().filter(data -> rating.equals(data.rating)).collect(Collectors.toList());
        int get;
        try {
            get = requestType.equals("tags") ? argsCount >= 4 ? number : r.nextInt(filter.size()) : argsCount <= 2 ? Integer.parseInt(messageArray[2]) : r.nextInt(filter.size());
        } catch (IndexOutOfBoundsException e) {
            get = r.nextInt(filter.size());
        } catch (IllegalArgumentException e) {
            if (e.getMessage().equals("bound must be positive"))
                return builder.setDescription("No results found.");
            else
                return builder.setDescription("Query not valid.");
        }
        String AUTHOR = filter.get(get).getAuthor();
        String tags = filter.get(get).getTags().stream().collect(Collectors.joining(", "));
        if (!smallRequest) {
            return builder.setAuthor("Found image", filter.get(get).getFile_url(), null).setDescription("Image uploaded by: " + (AUTHOR == null ? "not found" : AUTHOR) + ", with a rating of: **" + nRating.inverseBidiMap().get(filter.get(get).getRating()) + "**").setImage(filter.get(get).getFile_url()).addField("Height", String.valueOf(filter.get(get).getHeight()), true).addField("Width", String.valueOf(filter.get(get).getWidth()), true).addField("Tags", "``" + (tags == null ? "None" : tags) + "``", false).setFooter("If the image doesn't load, click the title.", null);
        }
        return builder.setAuthor("Found image", filter.get(get).getFile_url(), null).setDescription("Image uploaded by: " + (AUTHOR == null ? "not found" : AUTHOR) + ", with a rating of: **" + nRating.inverseBidiMap().get(filter.get(get).getRating()) + "**").setImage(filter.get(get).getFile_url()).addField("Width", String.valueOf(filter.get(get).getHeight()), true).addField("Height", String.valueOf(filter.get(get).getWidth()), true).addField("Tags", "``" + (tags == null ? "None" : tags) + "``", false).setFooter("If the image doesn't load, click the title.", null);
    } catch (Exception ex) {
        if (ex instanceof NullPointerException)
            return builder.setDescription(EmoteReference.ERROR + "Wrong syntax.");
        return builder.setDescription(EmoteReference.ERROR + "There are no images here, just dust.");
    }
}
Also used : SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Color(java.awt.Color) Arrays(java.util.Arrays) YandereImageData(net.kodehawa.mantarobot.commands.image.YandereImageData) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Utils(net.kodehawa.mantarobot.utils.Utils) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) Module(net.kodehawa.mantarobot.modules.Module) Wallpaper(net.kodehawa.lib.imageboards.konachan.main.entities.Wallpaper) Random(java.util.Random) ArrayList(java.util.ArrayList) Unirest(com.mashape.unirest.http.Unirest) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) OptsCmd.registerOption(net.kodehawa.mantarobot.commands.OptsCmd.registerOption) URLCache(net.kodehawa.mantarobot.utils.cache.URLCache) JSONObject(org.json.JSONObject) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) CommandRegistry(net.kodehawa.mantarobot.modules.CommandRegistry) Command(net.kodehawa.mantarobot.modules.Command) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) BidiMap(org.apache.commons.collections4.BidiMap) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) PostLoadEvent(net.kodehawa.mantarobot.modules.events.PostLoadEvent) DualHashBidiMap(org.apache.commons.collections4.bidimap.DualHashBidiMap) Category(net.kodehawa.mantarobot.modules.commands.base.Category) GsonDataManager(net.kodehawa.mantarobot.utils.data.GsonDataManager) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TimeUnit(java.util.concurrent.TimeUnit) URLEncoder(java.net.URLEncoder) List(java.util.List) CollectionUtils(br.com.brjdevs.java.utils.collections.CollectionUtils) Rule34(net.kodehawa.lib.imageboards.rule34.Rule34) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) net.kodehawa.lib.imageboards.e621.e621(net.kodehawa.lib.imageboards.e621.e621) Konachan(net.kodehawa.lib.imageboards.konachan.Konachan) UnsupportedEncodingException(java.io.UnsupportedEncodingException) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) YandereImageData(net.kodehawa.mantarobot.commands.image.YandereImageData) UnirestException(com.mashape.unirest.http.exceptions.UnirestException) UnsupportedEncodingException(java.io.UnsupportedEncodingException)

Aggregations

GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)67 Subscribe (com.google.common.eventbus.Subscribe)50 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)48 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)42 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)36 MantaroData (net.kodehawa.mantarobot.data.MantaroData)34 List (java.util.List)28 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)27 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)26 Utils (net.kodehawa.mantarobot.utils.Utils)26 TimeUnit (java.util.concurrent.TimeUnit)25 Collectors (java.util.stream.Collectors)25 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)25 Module (net.kodehawa.mantarobot.core.modules.Module)25 MantaroBot (net.kodehawa.mantarobot.MantaroBot)19 SubCommand (net.kodehawa.mantarobot.core.modules.commands.SubCommand)18 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)18 RateLimiter (net.kodehawa.mantarobot.utils.commands.RateLimiter)18 Slf4j (lombok.extern.slf4j.Slf4j)17 Player (net.kodehawa.mantarobot.db.entities.Player)17