Search in sources :

Example 1 with Guild

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

the class CustomCmds method custom.

@Command
public static void custom(CommandRegistry cr) {
    String any = "[\\d\\D]*?";
    cr.register("custom", new SimpleCommand(Category.UTILS) {

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length < 1) {
                onHelp(event);
                return;
            }
            String action = args[0];
            if (action.equals("list") || action.equals("ls")) {
                String filter = event.getGuild().getId() + ":";
                List<String> commands = customCommands.keySet().stream().filter(s -> s.startsWith(filter)).map(s -> s.substring(filter.length())).collect(Collectors.toList());
                EmbedBuilder builder = new EmbedBuilder().setAuthor("Commands for this guild", null, event.getGuild().getIconUrl()).setColor(event.getMember().getColor());
                builder.setDescription(commands.isEmpty() ? "There is nothing here, just dust." : forType(commands));
                event.getChannel().sendMessage(builder.build()).queue();
                return;
            }
            if (db().getGuild(event.getGuild()).getData().isCustomAdminLock() && !CommandPermission.ADMIN.test(event.getMember())) {
                event.getChannel().sendMessage("This guild only accepts custom commands from administrators.").queue();
                return;
            }
            if (action.equals("clear")) {
                if (CommandPermission.ADMIN.test(event.getMember())) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot do that, silly.").queue();
                    return;
                }
                List<CustomCommand> customCommands = db().getCustomCommands(event.getGuild());
                if (customCommands.isEmpty()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There's no Custom Commands registered in this Guild.").queue();
                }
                int size = customCommands.size();
                customCommands.forEach(CustomCommand::deleteAsync);
                customCommands.forEach(c -> CustomCmds.customCommands.remove(c.getId()));
                event.getChannel().sendMessage(EmoteReference.PENCIL + "Cleared **" + size + " Custom Commands**!").queue();
                return;
            }
            if (args.length < 2) {
                onHelp(event);
                return;
            }
            String cmd = args[1];
            if (action.equals("make")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                List<String> responses = new ArrayList<>();
                boolean created = InteractiveOperations.create(event.getChannel(), "Custom Command Creation", 60000, OptionalInt.of(60000), e -> {
                    if (!e.getAuthor().equals(event.getAuthor()))
                        return false;
                    String c = e.getMessage().getRawContent();
                    if (!c.startsWith("&"))
                        return false;
                    c = c.substring(1);
                    if (c.startsWith("~>cancel") || c.startsWith("~>stop")) {
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "Command Creation canceled.").queue();
                        return true;
                    }
                    if (c.startsWith("~>save")) {
                        String arg = c.substring(6).trim();
                        String saveTo = !arg.isEmpty() ? arg : cmd;
                        if (!NAME_PATTERN.matcher(cmd).matches()) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                            return false;
                        }
                        if (CommandProcessor.REGISTRY.commands().containsKey(saveTo) && !CommandProcessor.REGISTRY.commands().get(saveTo).equals(customCommand)) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                            return false;
                        }
                        if (responses.isEmpty()) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "No responses were added. Stopping creation without saving...").queue();
                        } else {
                            CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmd, responses);
                            custom.saveAsync();
                            customCommands.put(custom.getId(), custom.getValues());
                            CommandProcessor.REGISTRY.commands().put(cmd, customCommand);
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Saved to command ``" + cmd + "``!").queue();
                            TextChannelGround.of(event).dropItemWithChance(8, 2);
                        }
                        return true;
                    }
                    responses.add(c);
                    e.getMessage().addReaction(EmoteReference.CORRECT.getUnicode()).queue();
                    return false;
                });
                if (created) {
                    event.getChannel().sendMessage(EmoteReference.PENCIL + "Started **\"Creation of Custom Command ``" + cmd + "``\"**!\nSend ``&~>stop`` to stop creation **without saving**.\nSend ``&~>save`` to stop creation an **save the new Command**. Send any text beginning with ``&`` to be added to the Command Responses.\nThis Interactive Operation ends without saving after 60 seconds of inactivity.").queue();
                } else {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There's already an Interactive Operation happening on this channel.").queue();
                }
                return;
            }
            if (action.equals("remove") || action.equals("rm")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
                if (custom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                //delete at DB
                custom.deleteAsync();
                //reflect at local
                customCommands.remove(custom.getId());
                //clear commands if none
                if (customCommands.keySet().stream().noneMatch(s -> s.endsWith(":" + cmd)))
                    CommandProcessor.REGISTRY.commands().remove(cmd);
                event.getChannel().sendMessage(EmoteReference.PENCIL + "Removed Custom Command ``" + cmd + "``!").queue();
                return;
            }
            if (action.equals("raw")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                CustomCommand custom = db().getCustomCommand(event.getGuild(), cmd);
                if (custom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                Pair<String, Integer> pair = DiscordUtils.embedList(custom.getValues(), Object::toString);
                event.getChannel().sendMessage(baseEmbed(event, "Command ``" + cmd + "``:").setDescription(pair.getLeft()).setFooter("(Showing " + pair.getRight() + " responses of " + custom.getValues().size() + ")", null).build()).queue();
                return;
            }
            if (action.equals("import")) {
                if (!NAME_WILDCARD_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                Map<String, Guild> mapped = MantaroBot.getInstance().getMutualGuilds(event.getAuthor()).stream().collect(Collectors.toMap(ISnowflake::getId, g -> g));
                List<Pair<Guild, CustomCommand>> filtered = MantaroData.db().getCustomCommandsByName(("*" + cmd + "*").replace("*", any)).stream().map(customCommand -> {
                    Guild guild = mapped.get(customCommand.getGuildId());
                    return guild == null ? null : Pair.of(guild, customCommand);
                }).filter(Objects::nonNull).collect(Collectors.toList());
                if (filtered.size() == 0) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "There are no custom commands matching your search query.").queue();
                    return;
                }
                DiscordUtils.selectList(event, filtered, pair -> "``" + pair.getValue().getName() + "`` - Guild: ``" + pair.getKey() + "``", s -> baseEmbed(event, "Select the Command:").setDescription(s).setFooter("(You can only select custom commands from guilds that you are a member of)", null).build(), pair -> {
                    String cmdName = pair.getValue().getName();
                    List<String> responses = pair.getValue().getValues();
                    CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmdName, responses);
                    custom.saveAsync();
                    customCommands.put(custom.getId(), custom.getValues());
                    event.getChannel().sendMessage(String.format("Imported custom command ``%s`` from guild `%s` with responses ``%s``", cmdName, pair.getKey().getName(), String.join("``, ``", responses))).queue();
                    TextChannelGround.of(event).dropItemWithChance(8, 2);
                });
                return;
            }
            if (args.length < 3) {
                onHelp(event);
                return;
            }
            String value = args[2];
            if (action.equals("rename")) {
                if (!NAME_PATTERN.matcher(cmd).matches() || !NAME_PATTERN.matcher(value).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                if (CommandProcessor.REGISTRY.commands().containsKey(value) && !CommandProcessor.REGISTRY.commands().get(value).equals(customCommand)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                    return;
                }
                CustomCommand oldCustom = db().getCustomCommand(event.getGuild(), cmd);
                if (oldCustom == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR2 + "There's no Custom Command ``" + cmd + "`` in this Guild.").queue();
                    return;
                }
                CustomCommand newCustom = CustomCommand.of(event.getGuild().getId(), value, oldCustom.getValues());
                //change at DB
                oldCustom.deleteAsync();
                newCustom.saveAsync();
                //reflect at local
                customCommands.remove(oldCustom.getId());
                customCommands.put(newCustom.getId(), newCustom.getValues());
                //add mini-hack
                CommandProcessor.REGISTRY.commands().put(cmd, customCommand);
                //clear commands if none
                if (customCommands.keySet().stream().noneMatch(s -> s.endsWith(":" + cmd)))
                    CommandProcessor.REGISTRY.commands().remove(cmd);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Renamed command ``" + cmd + "`` to ``" + value + "``!").queue();
                //easter egg :D
                TextChannelGround.of(event).dropItemWithChance(8, 2);
                return;
            }
            if (action.equals("add") || action.equals("new")) {
                if (!NAME_PATTERN.matcher(cmd).matches()) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "Not allowed character.").queue();
                    return;
                }
                if (CommandProcessor.REGISTRY.commands().containsKey(cmd) && !CommandProcessor.REGISTRY.commands().get(cmd).equals(customCommand)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "A command already exists with this name!").queue();
                    return;
                }
                CustomCommand custom = CustomCommand.of(event.getGuild().getId(), cmd, Collections.singletonList(value));
                if (action.equals("add")) {
                    CustomCommand c = db().getCustomCommand(event, cmd);
                    if (c != null)
                        custom.getValues().addAll(c.getValues());
                }
                //save at DB
                custom.saveAsync();
                //reflect at local
                customCommands.put(custom.getId(), custom.getValues());
                //add mini-hack
                CommandProcessor.REGISTRY.commands().put(cmd, customCommand);
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Saved to command ``" + cmd + "``!").queue();
                //easter egg :D
                TextChannelGround.of(event).dropItemWithChance(8, 2);
                return;
            }
            onHelp(event);
        }

        @Override
        public String[] splitArgs(String content) {
            return SPLIT_PATTERN.split(content, 3);
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "CustomCommand Manager").setDescription("**Manages the Custom Commands of the Guild.**").addField("Guide", "https://github.com/Mantaro/MantaroBot/wiki/Custom-Commands", false).addField("Usage:", "`~>custom` - Shows this help\n" + "`~>custom <list|ls> [detailed]` - **List all commands. If detailed is supplied, it prints the responses of each command.**\n" + "`~>custom debug` - **Gives a Hastebin of the Raw Custom Commands Data. (OWNER-ONLY)**\n" + "`~>custom clear` - **Remove all Custom Commands from this Guild. (OWNER-ONLY)**\n" + "`~>custom add <name> <responses>` - **Add a new Command with the response provided.**\n" + "`~>custom make <name>` - **Starts a Interactive Operation to create a command with the specified name.**\n" + "`~>custom <remove|rm> <name>` - **Removes a command with an specific name.**\n" + "`~>custom import <search>` - **Imports a command from another guild you're in.**", false).build();
        }
    });
}
Also used : SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) CommandProcessor(net.kodehawa.mantarobot.core.CommandProcessor) java.util(java.util) URL(java.net.URL) Module(net.kodehawa.mantarobot.modules.Module) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) CommandStatsManager.log(net.kodehawa.mantarobot.commands.info.CommandStatsManager.log) MantaroBot(net.kodehawa.mantarobot.MantaroBot) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) Pair(org.apache.commons.lang3.tuple.Pair) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) CustomCommand(net.kodehawa.mantarobot.data.entities.CustomCommand) CommandRegistry(net.kodehawa.mantarobot.modules.CommandRegistry) Command(net.kodehawa.mantarobot.modules.Command) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) TextChannelGround(net.kodehawa.mantarobot.commands.currency.TextChannelGround) MantaroData.db(net.kodehawa.mantarobot.data.MantaroData.db) ConditionalCustoms(net.kodehawa.mantarobot.commands.custom.ConditionalCustoms) PostLoadEvent(net.kodehawa.mantarobot.modules.events.PostLoadEvent) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) SPLIT_PATTERN(net.kodehawa.mantarobot.utils.StringUtils.SPLIT_PATTERN) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Mapifier.map(net.kodehawa.mantarobot.commands.custom.Mapifier.map) AbstractCommand(net.kodehawa.mantarobot.modules.commands.base.AbstractCommand) 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) Guild(net.dv8tion.jda.core.entities.Guild) Slf4j(lombok.extern.slf4j.Slf4j) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) Mapifier.dynamicResolve(net.kodehawa.mantarobot.commands.custom.Mapifier.dynamicResolve) GuildData(net.kodehawa.mantarobot.data.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) CommandPermission(net.kodehawa.mantarobot.modules.commands.CommandPermission) EmbedJSON(net.kodehawa.mantarobot.commands.custom.EmbedJSON) MantaroData(net.kodehawa.mantarobot.data.MantaroData) HelpUtils.forType(net.kodehawa.mantarobot.commands.info.HelpUtils.forType) Pattern(java.util.regex.Pattern) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) DBGuild(net.kodehawa.mantarobot.data.entities.DBGuild) Guild(net.dv8tion.jda.core.entities.Guild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) CustomCommand(net.kodehawa.mantarobot.data.entities.CustomCommand) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Pair(org.apache.commons.lang3.tuple.Pair) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) CustomCommand(net.kodehawa.mantarobot.data.entities.CustomCommand) Command(net.kodehawa.mantarobot.modules.Command) AbstractCommand(net.kodehawa.mantarobot.modules.commands.base.AbstractCommand)

Example 2 with Guild

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

the class QuoteCmd method quote.

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

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (content.isEmpty()) {
                onHelp(event);
                return;
            }
            String action = args[0];
            String phrase = content.replace(action + " ", "");
            Guild guild = event.getGuild();
            ManagedDatabase db = MantaroData.db();
            EmbedBuilder builder = new EmbedBuilder();
            SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
            List<Message> messageHistory;
            try {
                messageHistory = event.getChannel().getHistory().retrievePast(100).complete();
            } catch (Exception e) {
                if (e instanceof PermissionException) {
                    event.getChannel().sendMessage(EmoteReference.CRYING + "I don't have permission to do this :<").queue();
                    return;
                }
                event.getChannel().sendMessage(EmoteReference.ERROR + "It seems like discord is on fire, as my" + " " + "request to retrieve message history was denied" + "with the error `" + e.getClass().getSimpleName() + "`").queue();
                log.warn("Shit exploded on Discord's backend. <@155867458203287552>", e);
                return;
            }
            if (action.equals("addfrom")) {
                Message message = messageHistory.stream().filter(msg -> msg.getContent().toLowerCase().contains(phrase.toLowerCase()) && !msg.getContent().startsWith(db.getGuild(guild).getData().getGuildCustomPrefix() == null ? MantaroData.config().get().getPrefix() : db.getGuild(guild).getData().getGuildCustomPrefix()) && !msg.getContent().startsWith(MantaroData.config().get().getPrefix())).findFirst().orElse(null);
                if (message == null) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "I couldn't find a message matching the specified search" + " criteria. Please try again with a more specific query.").queue();
                    return;
                }
                TextChannel channel = guild.getTextChannelById(message.getChannel().getId());
                Quote quote = Quote.of(guild.getMember(message.getAuthor()), channel, message);
                db.getQuotes(guild).add(quote);
                event.getChannel().sendMessage(buildQuoteEmbed(dateFormat, builder, quote)).queue();
                quote.saveAsync();
                return;
            }
            if (action.equals("random")) {
                try {
                    Quote quote = CollectionUtils.random(db.getQuotes(event.getGuild()));
                    event.getChannel().sendMessage(buildQuoteEmbed(dateFormat, builder, quote)).queue();
                } catch (Exception e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "This server has no set quotes!").queue();
                }
                return;
            }
            if (action.equals("readfrom")) {
                try {
                    List<Quote> quotes = db.getQuotes(guild);
                    for (int i2 = 0; i2 < quotes.size(); i2++) {
                        if (quotes.get(i2).getContent().contains(phrase)) {
                            Quote quote = quotes.get(i2);
                            event.getChannel().sendMessage(buildQuoteEmbed(dateFormat, builder, quote)).queue();
                            break;
                        }
                    }
                } catch (Exception e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "I didn't find any quotes! (no quotes match the criteria).").queue();
                }
                return;
            }
            if (action.equals("removefrom")) {
                try {
                    List<Quote> quotes = db.getQuotes(guild);
                    for (int i2 = 0; i2 < quotes.size(); i2++) {
                        if (quotes.get(i2).getContent().contains(phrase)) {
                            Quote quote = quotes.get(i2);
                            db.getQuotes(guild).remove(i2);
                            quote.saveAsync();
                            event.getChannel().sendMessage(EmoteReference.CORRECT + "Removed quote with content: " + quote.getContent()).queue();
                            break;
                        }
                    }
                } catch (Exception e) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "No quotes match the criteria.").queue();
                }
            }
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Quote command").setDescription("**Quotes a message by search term.**").addField("Usage", "`~>quote addfrom <phrase>`- **Add a quote with the content defined by the specified number. For example, providing 1 will quote " + "the last message.**\n" + "`~>quote removefrom <phrase>` - **Remove a quote based on your text query.**\n" + "`~>quote readfrom <phrase>` - **Search for the first quote which matches your search criteria and prints " + "it.**\n" + "`~>quote random` - **Get a random quote.** \n", false).addField("Parameters", "`phrase` - A part of the quote phrase.", false).setColor(Color.DARK_GRAY).build();
        }
    });
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Color(java.awt.Color) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Date(java.util.Date) Module(net.kodehawa.mantarobot.modules.Module) SimpleDateFormat(java.text.SimpleDateFormat) Category(net.kodehawa.mantarobot.modules.commands.base.Category) Quote(net.kodehawa.mantarobot.data.entities.Quote) Message(net.dv8tion.jda.core.entities.Message) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Guild(net.dv8tion.jda.core.entities.Guild) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Slf4j(lombok.extern.slf4j.Slf4j) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) List(java.util.List) CollectionUtils(br.com.brjdevs.java.utils.collections.CollectionUtils) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) ManagedDatabase(net.kodehawa.mantarobot.data.db.ManagedDatabase) CommandRegistry(net.kodehawa.mantarobot.modules.CommandRegistry) Command(net.kodehawa.mantarobot.modules.Command) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Message(net.dv8tion.jda.core.entities.Message) Guild(net.dv8tion.jda.core.entities.Guild) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) Quote(net.kodehawa.mantarobot.data.entities.Quote) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TextChannel(net.dv8tion.jda.core.entities.TextChannel) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) List(java.util.List) ManagedDatabase(net.kodehawa.mantarobot.data.db.ManagedDatabase) SimpleDateFormat(java.text.SimpleDateFormat) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) SimpleCommand(net.kodehawa.mantarobot.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.modules.Command)

Example 3 with Guild

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

the class AudioCmdUtils method embedForQueue.

public static void embedForQueue(int page, GuildMessageReceivedEvent event, GuildMusicManager musicManager) {
    String toSend = AudioUtils.getQueueList(musicManager.getTrackScheduler().getQueue());
    Guild guild = event.getGuild();
    if (toSend.isEmpty()) {
        event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Queue for server " + guild.getName(), null, guild.getIconUrl()).setColor(Color.CYAN).setDescription("Nothing here, just dust. Why don't you queue some songs?").setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").build()).queue();
        return;
    }
    String[] lines = NEWLINE_PATTERN.split(toSend);
    if (!guild.getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION)) {
        String line = null;
        StringBuilder sb = new StringBuilder();
        int total;
        {
            int t = 0;
            int c = 0;
            for (String s : lines) {
                if (s.length() + c + 1 > MessageEmbed.TEXT_MAX_LENGTH) {
                    t++;
                    c = 0;
                }
                c += s.length() + 1;
            }
            if (c > 0)
                t++;
            total = t;
        }
        int current = 0;
        for (String s : lines) {
            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) {
                current++;
                if (current == page) {
                    line = sb.toString();
                    break;
                }
                sb = new StringBuilder();
            }
            sb.append(s).append('\n');
        }
        if (sb.length() > 0 && current + 1 == page) {
            line = sb.toString();
        }
        if (line == null || page > total) {
            event.getChannel().sendMessage(new EmbedBuilder().setAuthor("Queue for server " + guild.getName(), null, guild.getIconUrl()).setColor(Color.CYAN).setDescription("Nothing here, just dust. Why don't you go back some pages?").setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").build()).queue();
        } else {
            long length = musicManager.getTrackScheduler().getQueue().stream().mapToLong(value -> value.getInfo().length).sum();
            EmbedBuilder builder = new EmbedBuilder().setAuthor("Queue for server " + guild.getName(), null, guild.getIconUrl()).setColor(Color.CYAN);
            String nowPlaying = musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack() != null ? "**[" + musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().title + "](" + musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().uri + ")** (" + Utils.getDurationMinutes(musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().length) + ")" : "Nothing or title/duration not found";
            VoiceChannel vch = guild.getSelfMember().getVoiceState().getChannel();
            builder.addField("Currently playing", nowPlaying, false).setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").addField("Total queue time", "`" + Utils.getReadableTime(length) + "`", true).addField("Total queue size", "`" + musicManager.getTrackScheduler().getQueue().size() + " songs`", true).addField("Repeat / Pause", "`" + (musicManager.getTrackScheduler().getRepeat() == null ? "false" : musicManager.getTrackScheduler().getRepeat()) + " / " + String.valueOf(musicManager.getTrackScheduler().getAudioPlayer().isPaused()) + "`", true).addField("Playing in", vch == null ? "No channel :<" : "`" + vch.getName() + "`", true).setFooter("Total pages: " + total + " -> Use ~>queue <page> to change pages. Currently in page " + page, guild.getIconUrl());
            event.getChannel().sendMessage(builder.setDescription(line).build()).queue();
        }
        return;
    }
    DiscordUtils.list(event, 30, false, (p, total) -> {
        long length = musicManager.getTrackScheduler().getQueue().stream().mapToLong(value -> value.getInfo().length).sum();
        EmbedBuilder builder = new EmbedBuilder().setAuthor("Queue for server " + guild.getName(), null, guild.getIconUrl()).setColor(Color.CYAN);
        String nowPlaying = musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack() != null ? "**[" + musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().title + "](" + musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().uri + ")** (" + Utils.getDurationMinutes(musicManager.getTrackScheduler().getAudioPlayer().getPlayingTrack().getInfo().length) + ")" : "Nothing or title/duration not found";
        VoiceChannel vch = guild.getSelfMember().getVoiceState().getChannel();
        builder.addField("Currently playing", nowPlaying, false).setThumbnail("http://www.clipartbest.com/cliparts/jix/6zx/jix6zx4dT.png").addField("Total queue time", "`" + Utils.getReadableTime(length) + "`", true).addField("Total queue size", "`" + musicManager.getTrackScheduler().getQueue().size() + " songs`", true).addField("Repeat / Pause", "`" + (musicManager.getTrackScheduler().getRepeat() == null ? "false" : musicManager.getTrackScheduler().getRepeat()) + " / " + String.valueOf(musicManager.getTrackScheduler().getAudioPlayer().isPaused()) + "`", true).addField("Playing in", vch == null ? "No channel :<" : "`" + vch.getName() + "`", true).setFooter("Total pages: " + total + " -> React to change pages. Currently in page " + p, guild.getIconUrl());
        return builder;
    }, lines);
}
Also used : Color(java.awt.Color) Region(net.dv8tion.jda.core.Region) Arrays(java.util.Arrays) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) Iterator(java.util.Iterator) NEWLINE_PATTERN(net.kodehawa.mantarobot.utils.data.SimpleFileDataManager.NEWLINE_PATTERN) Utils(net.kodehawa.mantarobot.utils.Utils) AudioManager(net.dv8tion.jda.core.managers.AudioManager) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) ArrayList(java.util.ArrayList) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) Guild(net.dv8tion.jda.core.entities.Guild) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) List(java.util.List) Matcher(java.util.regex.Matcher) Permission(net.dv8tion.jda.core.Permission) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) AudioTrack(com.sedmelluq.discord.lavaplayer.track.AudioTrack) Pattern(java.util.regex.Pattern) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) VoiceChannel(net.dv8tion.jda.core.entities.VoiceChannel) Guild(net.dv8tion.jda.core.entities.Guild)

Example 4 with Guild

use of net.dv8tion.jda.core.entities.Guild 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)

Example 5 with Guild

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

the class CheckIfPremiumGuild method run.

@Override
public void run() {
    for (Shard shard : ShardManager.getShards()) {
        for (Guild guild : shard.jda.getGuilds()) {
            int premiumCounter = 0;
            for (Member member : guild.getMembers()) {
                if (UserUtils.hasTierThreePermissions(member.getUser()))
                    premiumCounter++;
            }
            if (premiumCounter == 0) {
                guild.getPublicChannel().sendMessage("Someone in your guild needs Tier 3 permissions to be able to access me (the " + "premium bot). " + "Pledge $5 a month @ https://patreon.com/ardent to get access!").queue();
                guild.leave().queue();
            }
        }
    }
}
Also used : Shard(tk.ardentbot.main.Shard) Guild(net.dv8tion.jda.core.entities.Guild) Member(net.dv8tion.jda.core.entities.Member)

Aggregations

Guild (net.dv8tion.jda.core.entities.Guild)27 User (net.dv8tion.jda.core.entities.User)14 Message (net.dv8tion.jda.core.entities.Message)13 MessageChannel (net.dv8tion.jda.core.entities.MessageChannel)11 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)10 Shard (tk.ardentbot.main.Shard)9 Subcommand (tk.ardentbot.core.executor.Subcommand)8 TextChannel (net.dv8tion.jda.core.entities.TextChannel)7 Command (tk.ardentbot.core.executor.Command)7 ArrayList (java.util.ArrayList)6 HashMap (java.util.HashMap)6 List (java.util.List)5 Database.connection (tk.ardentbot.rethink.Database.connection)4 Database.r (tk.ardentbot.rethink.Database.r)4 AudioPlayer (com.sedmelluq.discord.lavaplayer.player.AudioPlayer)3 AudioTrack (com.sedmelluq.discord.lavaplayer.track.AudioTrack)3 Map (java.util.Map)3 Member (net.dv8tion.jda.core.entities.Member)3 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)3 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)3