Search in sources :

Example 21 with EmbedBuilder

use of net.dv8tion.jda.core.EmbedBuilder in project MantaroBot by Mantaro.

the class InfoCmds method guildinfo.

@Command
public static void guildinfo(CommandRegistry cr) {
    cr.register("serverinfo", new SimpleCommand(Category.INFO) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            Guild guild = event.getGuild();
            TextChannel channel = event.getChannel();
            String roles = guild.getRoles().stream().filter(role -> !guild.getPublicRole().equals(role)).map(Role::getName).collect(Collectors.joining(", "));
            if (roles.length() > 1024)
                roles = roles.substring(0, 1024 - 4) + "...";
            channel.sendMessage(new EmbedBuilder().setAuthor("Server Information", null, guild.getIconUrl()).setColor(guild.getOwner().getColor() == null ? Color.ORANGE : guild.getOwner().getColor()).setDescription("Server information for " + guild.getName()).setThumbnail(guild.getIconUrl()).addField("Users (Online/Unique)", (int) guild.getMembers().stream().filter(u -> !u.getOnlineStatus().equals(OnlineStatus.OFFLINE)).count() + "/" + guild.getMembers().size(), true).addField("Main Channel", guild.getPublicChannel().getAsMention(), true).addField("Creation Date", guild.getCreationTime().format(DateTimeFormatter.ISO_DATE_TIME).replaceAll("[^0-9.:-]", " "), true).addField("Voice/Text Channels", guild.getVoiceChannels().size() + "/" + guild.getTextChannels().size(), true).addField("Owner", guild.getOwner().getUser().getName() + "#" + guild.getOwner().getUser().getDiscriminator(), true).addField("Region", guild.getRegion() == null ? "Unknown." : guild.getRegion().getName(), true).addField("Roles (" + guild.getRoles().size() + ")", roles, false).setFooter("Server ID: " + String.valueOf(guild.getId()), null).build()).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Server Info Command").setDescription("**See your server's current stats.**").setColor(event.getGuild().getOwner().getColor() == null ? Color.ORANGE : event.getGuild().getOwner().getColor()).build();
        }
    });
    cr.registerAlias("serverinfo", "guildinfo");
}
Also used : SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Color(java.awt.Color) MantaroInfo(net.kodehawa.mantarobot.MantaroInfo) CommandProcessor(net.kodehawa.mantarobot.core.CommandProcessor) java.util(java.util) CommandStatsManager(net.kodehawa.mantarobot.commands.info.CommandStatsManager) Utils(net.kodehawa.mantarobot.utils.Utils) Module(net.kodehawa.mantarobot.modules.Module) MantaroShard(net.kodehawa.mantarobot.MantaroShard) StatsHelper.calculateDouble(net.kodehawa.mantarobot.commands.info.StatsHelper.calculateDouble) MantaroBot(net.kodehawa.mantarobot.MantaroBot) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Cursor(com.rethinkdb.net.Cursor) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) Duration(java.time.Duration) JDA(net.dv8tion.jda.core.JDA) CommandRegistry(net.kodehawa.mantarobot.modules.CommandRegistry) ManagementFactory(java.lang.management.ManagementFactory) Command(net.kodehawa.mantarobot.modules.Command) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) CommandListener(net.kodehawa.mantarobot.core.listeners.command.CommandListener) GuildStatsManager(net.kodehawa.mantarobot.commands.info.GuildStatsManager) PostLoadEvent(net.kodehawa.mantarobot.modules.events.PostLoadEvent) JDAInfo(net.dv8tion.jda.core.JDAInfo) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) RateLimiter(net.kodehawa.mantarobot.commands.currency.RateLimiter) MantaroListener(net.kodehawa.mantarobot.core.listeners.MantaroListener) Category(net.kodehawa.mantarobot.modules.commands.base.Category) Instant(java.time.Instant) AsyncInfoMonitor(net.kodehawa.mantarobot.commands.info.AsyncInfoMonitor) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) OnlineStatus(net.dv8tion.jda.core.OnlineStatus) TimeUnit(java.util.concurrent.TimeUnit) PlayerLibrary(com.sedmelluq.discord.lavaplayer.tools.PlayerLibrary) DurationFormatUtils(org.apache.commons.lang3.time.DurationFormatUtils) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) DateTimeFormatter(java.time.format.DateTimeFormatter) CommandPermission(net.kodehawa.mantarobot.modules.commands.CommandPermission) MantaroData(net.kodehawa.mantarobot.data.MantaroData) HelpUtils.forType(net.kodehawa.mantarobot.commands.info.HelpUtils.forType) RethinkDB(com.rethinkdb.RethinkDB) StatsHelper.calculateInt(net.kodehawa.mantarobot.commands.info.StatsHelper.calculateInt) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) 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 EmbedBuilder

use of net.dv8tion.jda.core.EmbedBuilder in project MantaroBot by Mantaro.

the class Trivia method onStart.

@Override
public boolean onStart(GameLobby lobby) {
    try {
        String json = Utils.wget("https://opentdb.com/api.php?amount=1", null);
        if (json == null) {
            lobby.getChannel().sendMessage(EmoteReference.ERROR + "Error while starting trivia. Seemingly Open Trivia DB is having trouble.").queue();
            return false;
        }
        EmbedBuilder eb = new EmbedBuilder();
        expectedAnswer = new ArrayList<>();
        JSONObject ob = new JSONObject(json);
        JSONObject question = ob.getJSONArray("results").getJSONObject(0);
        String qu = Jsoup.parse(question.getString("question")).text();
        String category = question.getString("category");
        String diff = question.getString("difficulty");
        expectedAnswer.add(Jsoup.parse(question.getString("correct_answer")).text());
        eb.setAuthor("Trivia Game", null, lobby.getEvent().getAuthor().getAvatarUrl()).setThumbnail("https://cdn.pixabay.com/photo/2012/04/14/16/26/question-34499_960_720.png").setDescription("**" + qu + "**").addField("Difficulty", "`" + Utils.capitalize(diff) + "`", true).addField("Category", "`" + category + "`", true).setFooter("This times out in 2 minutes.", lobby.getEvent().getAuthor().getAvatarUrl());
        lobby.getChannel().sendMessage(eb.build()).queue();
        return true;
    } catch (Exception e) {
        lobby.getChannel().sendMessage(EmoteReference.ERROR + "Error while starting trivia.").queue();
        log.warn("Error while starting a trivia game", e);
        return false;
    }
}
Also used : EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) JSONObject(org.json.JSONObject)

Example 23 with EmbedBuilder

use of net.dv8tion.jda.core.EmbedBuilder in project MantaroBot by Mantaro.

the class ImageGame method sendEmbedImage.

protected RestAction<Message> sendEmbedImage(MessageChannel channel, String url, Consumer<EmbedBuilder> embedConfigurator) {
    EmbedBuilder eb = new EmbedBuilder();
    embedConfigurator.accept(eb);
    if (MantaroData.config().get().cacheGames) {
        eb.setImage("attachment://image.png");
        return channel.sendFile(cache.getInput(url), "image.png", new MessageBuilder().setEmbed(eb.build()).build());
    }
    eb.setImage(url);
    return channel.sendMessage(eb.build());
}
Also used : EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageBuilder(net.dv8tion.jda.core.MessageBuilder)

Example 24 with EmbedBuilder

use of net.dv8tion.jda.core.EmbedBuilder in project MantaroBot by Mantaro.

the class DiscordUtils method list.

public static Future<Void> list(GuildMessageReceivedEvent event, int timeoutSeconds, boolean canEveryoneUse, IntIntObjectFunction<EmbedBuilder> supplier, String... parts) {
    if (parts.length == 0)
        return null;
    List<MessageEmbed> embeds = new ArrayList<>();
    StringBuilder sb = new StringBuilder();
    int total;
    {
        int t = 0;
        int c = 0;
        for (String s : parts) {
            if (s.length() + c + 1 > MessageEmbed.TEXT_MAX_LENGTH) {
                t++;
                c = 0;
            }
            c += s.length() + 1;
        }
        if (c > 0)
            t++;
        total = t;
    }
    for (String s : parts) {
        int l = s.length() + 1;
        if (l > MessageEmbed.TEXT_MAX_LENGTH)
            throw new IllegalArgumentException("Length for one of the pages is greater than the maximum");
        if (sb.length() + l > MessageEmbed.TEXT_MAX_LENGTH) {
            EmbedBuilder eb = supplier.apply(embeds.size() + 1, total);
            eb.setDescription(sb.toString());
            embeds.add(eb.build());
            sb = new StringBuilder();
        }
        sb.append(s).append('\n');
    }
    if (sb.length() > 0) {
        EmbedBuilder eb = supplier.apply(embeds.size() + 1, total);
        eb.setDescription(sb.toString());
        embeds.add(eb.build());
    }
    AtomicInteger index = new AtomicInteger();
    Message m = event.getChannel().sendMessage(embeds.get(0)).complete();
    return ReactionOperations.create(m, timeoutSeconds, (e) -> {
        if (!canEveryoneUse && e.getUser().getIdLong() != event.getAuthor().getIdLong())
            return false;
        switch(e.getReactionEmote().getName()) {
            case //left arrow
            "⬅":
                if (index.get() == 0)
                    break;
                m.editMessage(embeds.get(index.decrementAndGet())).queue();
                break;
            case //right arrow
            "➡":
                if (index.get() + 1 >= embeds.size())
                    break;
                m.editMessage(embeds.get(index.incrementAndGet())).queue();
                break;
        }
        if (event.getGuild().getSelfMember().hasPermission(e.getTextChannel(), Permission.MESSAGE_MANAGE)) {
            e.getReaction().removeReaction(e.getUser()).queue();
        }
        return false;
    }, "⬅", "➡");
}
Also used : EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Message(net.dv8tion.jda.core.entities.Message) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList)

Example 25 with EmbedBuilder

use of net.dv8tion.jda.core.EmbedBuilder in project Ardent by adamint.

the class Tinder method setupSubcommands.

@Override
public void setupSubcommands() throws Exception {
    subcommands.add(new Subcommand("Match yourself with someone in the server!", "matchme", "matchme") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            ArrayList<TinderMatch> matches = queryAsArrayList(TinderMatch.class, r.table("tinder_matches").filter(row -> row.g("user_id").eq(user.getId())).run(connection));
            User potentialMatch = getPotentialMatch(user, guild, matches);
            EmbedBuilder builder = MessageUtils.getDefaultEmbed(user);
            String matchMe = "Match me | Tinder";
            builder.setAuthor(matchMe, getShard().url, getShard().bot.getAvatarUrl());
            builder.setThumbnail(potentialMatch.getAvatarUrl());
            StringBuilder description = new StringBuilder();
            description.append("**" + matchMe + "**");
            description.append("\nTheir name: " + UserUtils.getNameWithDiscriminator(potentialMatch.getId()));
            description.append("Swipe right (rightreaction) to connect with this person, or swipe left (left reaction) to pass them " + "by\nType /tinder connect to connect with the people you've swiped right on");
            Message sent = sendEmbed(builder.setDescription(description.toString()), channel, user, ":arrow_left:", ":arrow_right:");
            interactiveReaction(channel, sent, user, 15, messageReaction -> {
                String name = messageReaction.getEmote().getName();
                if (name != null) {
                    if (name.equals("➡")) {
                        r.table("tinder_matches").insert(r.json(gson.toJson(new TinderMatch(user.getId(), potentialMatch.getId(), true)))).run(connection);
                        sendEditedTranslation("You swiped right on {0}! Connect with them using /tinder connect", user, channel, potentialMatch.getName());
                    } else if (name.equals("⬅")) {
                        r.table("tinder_matches").insert(r.json(gson.toJson(new TinderMatch(user.getId(), potentialMatch.getId(), false)))).run(connection);
                        sendEditedTranslation("You swiped right on {0} - Don't worry, you can find better!", user, channel, potentialMatch.getName());
                    } else
                        sendTranslatedMessage("You reacted with an unexpected emoji :thinking:", channel, user);
                }
            });
        }
    });
    subcommands.add(new Subcommand("Connect with the people you've swiped right on", "connect", "connect") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            String yourMatches = "Discord Tinder | Your Matches";
            String swipedRightOnYou = "Swiped right on you";
            EmbedBuilder builder = MessageUtils.getDefaultEmbed(user);
            builder.setAuthor(yourMatches, getShard().url, getShard().bot.getAvatarUrl());
            builder.setThumbnail(user.getAvatarUrl());
            StringBuilder description = new StringBuilder();
            description.append("**" + yourMatches + "**");
            ArrayList<TinderMatch> matches = queryAsArrayList(TinderMatch.class, r.table("tinder_matches").filter(r.hashMap("user_id", user.getId()).with("swipedRight", true)).run(connection));
            if (matches.size() == 0) {
                description.append("\nYou don't have any connections :frowning:");
            } else {
                for (int i = 0; i < matches.size(); i++) {
                    String swipedRightWithId = matches.get(i).getPerson_id();
                    boolean mutual = swipedRightWith(user.getId(), swipedRightWithId);
                    String yesNo;
                    if (mutual)
                        yesNo = EmojiParser.parseToUnicode(":white_check_mark:");
                    else
                        yesNo = EmojiParser.parseToAliases(":x:");
                    description.append("\n#" + (i + 1) + ": " + UserUtils.getNameWithDiscriminator(swipedRightWithId) + " | " + swipedRightOnYou + ": " + yesNo);
                }
            }
            description.append("\n\nUse /tinder message [number on connection list] to message that person. However, they must have " + "swiped right on you as well to be able to contact them");
            sendEmbed(builder.setDescription(description), channel, user);
        }
    });
    subcommands.add(new Subcommand("Message one of your mutual connections!", "message [number in connection list]", "message") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            if (args.length == 2) {
                sendTranslatedMessage("Usage: /tinder message [person's number in /tinder connect] [message here]", channel, user);
                return;
            }
            if (message.getRawContent().split(" ").length == 3) {
                sendTranslatedMessage("You need to include a message to send that person!", channel, user);
                return;
            }
            try {
                int number = Integer.parseInt(args[2]) - 1;
                if (number < 0)
                    sendTranslatedMessage("Usage: /tinder message [person's number in /tinder connect] [message here]", channel, user);
                else {
                    ArrayList<TinderMatch> matches = queryAsArrayList(TinderMatch.class, r.table("tinder_matches").filter(r.hashMap("user_id", user.getId()).with("swipedRight", true)).run(connection));
                    if (number >= matches.size()) {
                        sendTranslatedMessage("Sorry, but you don't have this many matches!", channel, user);
                        return;
                    }
                    TinderMatch selected = matches.get(number);
                    if (!swipedRightWith(user.getId(), selected.getPerson_id())) {
                        sendTranslatedMessage("That person hasn't swiped right on you!", channel, user);
                        return;
                    }
                    User toMessage = UserUtils.getUserById(selected.getPerson_id());
                    try {
                        toMessage.openPrivateChannel().queue(privateChannel -> privateChannel.sendMessage("One of your Tinder " + "matches, **" + UserUtils.getNameWithDiscriminator(user.getId()) + "**, sent you " + "a message!\n\n**" + user.getName() + "**: " + replace(message.getRawContent(), 3)).queue());
                        if (!sentTo.contains(toMessage.getId())) {
                            toMessage.openPrivateChannel().queue(privateChannel -> {
                                privateChannel.sendMessage("To stop receiving messages from this person, remove them from your match " + "list with /tinder remove [number on the /tinder connect list]\n" + "\n" + "To send a message back to this person, type /tinder message [number on your /tinder connect " + "list] [message here] in a server - meet other tinder savvy people on the Ardent guild (where" + " we have a dedicated Tinder channel)! - https://discordapp.com/invite/rfGSxNA").queue();
                                sentTo.add(toMessage.getId());
                            });
                        }
                        sendTranslatedMessage("Ok! I sent that person your message :wink:", channel, user);
                    } catch (Exception e) {
                        sendTranslatedMessage("I was unable to message that person :frowning:", channel, user);
                    }
                }
            } catch (NumberFormatException e) {
                sendTranslatedMessage("Usage: /tinder message [person's number in /tinder connect] [message here]", channel, user);
            }
        }
    });
    subcommands.add(new Subcommand("Remove one of your connections", "remove [number in connection list]", "remove") {

        @Override
        public void onCall(Guild guild, MessageChannel channel, User user, Message message, String[] args) throws Exception {
            if (args.length == 2) {
                sendTranslatedMessage("Usage: /tinder remove [person's number in /tinder connect]", channel, user);
                return;
            }
            try {
                int number = Integer.parseInt(args[2]) - 1;
                if (number < 0)
                    sendTranslatedMessage("Usage: /tinder remove [person's number in /tinder connect]", channel, user);
                else {
                    ArrayList<TinderMatch> matches = queryAsArrayList(TinderMatch.class, r.table("tinder_matches").filter(r.hashMap("user_id", user.getId()).with("swipedRight", true)).run(connection));
                    if (number >= matches.size()) {
                        sendTranslatedMessage("Sorry, but you don't have this many matches!", channel, user);
                        return;
                    }
                    TinderMatch selected = matches.get(number);
                    r.table("tinder_matches").filter(r.hashMap("user_id", user.getId()).with("person_id", selected.getPerson_id())).delete().run(connection);
                    sendTranslatedMessage(":ok_hand: Removed that person from your connection list", channel, user);
                }
            } catch (NumberFormatException e) {
                sendTranslatedMessage("Usage: /tinder remove [person's number in /tinder connect]", channel, user);
            }
        }
    });
}
Also used : MessageUtils(tk.ardentbot.utils.discord.MessageUtils) Command(tk.ardentbot.core.executor.Command) UserUtils(tk.ardentbot.utils.discord.UserUtils) Subcommand(tk.ardentbot.core.executor.Subcommand) Database.r(tk.ardentbot.rethink.Database.r) MessageChannel(net.dv8tion.jda.core.entities.MessageChannel) Message(net.dv8tion.jda.core.entities.Message) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ArrayList(java.util.ArrayList) SecureRandom(java.security.SecureRandom) Guild(net.dv8tion.jda.core.entities.Guild) EmojiParser(com.vdurmont.emoji.EmojiParser) User(net.dv8tion.jda.core.entities.User) Database.connection(tk.ardentbot.rethink.Database.connection) TinderMatch(tk.ardentbot.rethink.models.TinderMatch) User(net.dv8tion.jda.core.entities.User) Subcommand(tk.ardentbot.core.executor.Subcommand) Message(net.dv8tion.jda.core.entities.Message) ArrayList(java.util.ArrayList) Guild(net.dv8tion.jda.core.entities.Guild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) MessageChannel(net.dv8tion.jda.core.entities.MessageChannel) TinderMatch(tk.ardentbot.rethink.models.TinderMatch)

Aggregations

EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)73 Message (net.dv8tion.jda.core.entities.Message)15 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)13 ArrayList (java.util.ArrayList)12 Guild (net.dv8tion.jda.core.entities.Guild)11 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)11 MantaroData (net.kodehawa.mantarobot.data.MantaroData)11 DBGuild (net.kodehawa.mantarobot.data.entities.DBGuild)11 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)11 Color (java.awt.Color)10 User (net.dv8tion.jda.core.entities.User)10 Command (net.kodehawa.mantarobot.modules.Command)10 SimpleCommand (net.kodehawa.mantarobot.modules.commands.SimpleCommand)10 TimeUnit (java.util.concurrent.TimeUnit)9 Utils (net.kodehawa.mantarobot.utils.Utils)9 List (java.util.List)8 Collectors (java.util.stream.Collectors)8 GuildData (net.kodehawa.mantarobot.data.entities.helpers.GuildData)8 CommandRegistry (net.kodehawa.mantarobot.modules.CommandRegistry)8 Module (net.kodehawa.mantarobot.modules.Module)8