Search in sources :

Example 1 with Role

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

the class MiscCmds method iamnotFunction.

protected static void iamnotFunction(String autoroleName, GuildMessageReceivedEvent event) {
    DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
    Map<String, String> autoroles = dbGuild.getData().getAutoroles();
    if (autoroles.containsKey(autoroleName)) {
        Role role = event.getGuild().getRoleById(autoroles.get(autoroleName));
        if (role == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "The role that this autorole corresponded " + "to has been deleted").queue();
            // delete the non-existent autorole.
            dbGuild.getData().getAutoroles().remove(autoroleName);
            dbGuild.saveAsync();
        } else {
            if (!(event.getMember().getRoles().stream().filter(r1 -> r1.getId().equals(role.getId())).collect(Collectors.toList()).size() > 0)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You don't have this role, silly!").queue();
                return;
            }
            try {
                event.getGuild().getController().removeRolesFromMember(event.getMember(), role).queue(aVoid -> event.getChannel().sendMessage(EmoteReference.OK + event.getMember().getEffectiveName() + ", you've " + "lost the **" + role.getName() + "** role").queue());
            } catch (PermissionException pex) {
                event.getChannel().sendMessage(String.format("%sI couldn't give you **%s. Make sure that I have permission to add roles and that my role is above **%s**", EmoteReference.ERROR, role.getName(), role.getName())).queue();
            }
        }
    } else {
        event.getChannel().sendMessage(EmoteReference.ERROR + "There isn't an autorole with the name ``" + autoroleName + "``!").queue();
    }
}
Also used : Role(net.dv8tion.jda.core.entities.Role) IntStream(java.util.stream.IntStream) Poll(net.kodehawa.mantarobot.commands.interaction.polls.Poll) Module(net.kodehawa.mantarobot.core.modules.Module) SimpleTreeCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleTreeCommand) Utils(net.kodehawa.mantarobot.utils.Utils) Random(java.util.Random) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) Message(net.dv8tion.jda.core.entities.Message) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) MessageBuilder(net.dv8tion.jda.core.MessageBuilder) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) ITreeCommand(net.kodehawa.mantarobot.core.modules.commands.base.ITreeCommand) JSONObject(org.json.JSONObject) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Map(java.util.Map) StringUtils(br.com.brjdevs.java.utils.texts.StringUtils) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) SimpleFileDataManager(net.kodehawa.mantarobot.utils.data.SimpleFileDataManager) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Role(net.dv8tion.jda.core.entities.Role) PollBuilder(net.kodehawa.mantarobot.commands.interaction.polls.PollBuilder) SubCommand(net.kodehawa.mantarobot.core.modules.commands.SubCommand) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Slf4j(lombok.extern.slf4j.Slf4j) DataManager(net.kodehawa.mantarobot.utils.data.DataManager) URLEncoder(java.net.URLEncoder) List(java.util.List) CollectionUtils.random(br.com.brjdevs.java.utils.collections.CollectionUtils.random) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Optional(java.util.Optional) PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild)

Example 2 with Role

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

the class MuteCmds method mute.

@Subscribe
public void mute(CommandRegistry registry) {
    Command mute = registry.register("mute", new SimpleCommand(Category.MODERATION) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (!event.getMember().hasPermission(Permission.KICK_MEMBERS) || !event.getMember().hasPermission(Permission.BAN_MEMBERS)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to have either ban or kick members permission to mute!").queue();
                return;
            }
            ManagedDatabase db = MantaroData.db();
            DBGuild dbGuild = db.getGuild(event.getGuild());
            GuildData guildData = dbGuild.getData();
            String reason = "Not specified";
            Map<String, Optional<String>> opts = br.com.brjdevs.java.utils.texts.StringUtils.parse(args);
            if (guildData.getMutedRole() == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "The mute role is not set in this server, you can set it by doing `~>opts muterole set <role>`").queue();
                return;
            }
            Role mutedRole = event.getGuild().getRoleById(guildData.getMutedRole());
            if (mutedRole == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "The previously configured mute role on this server is now non-existent!").queue();
                return;
            }
            if (args.length > 1) {
                reason = StringUtils.splitArgs(content, 2)[1];
            }
            if (event.getMessage().getMentionedUsers().isEmpty()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You need to mention at least one user to mute.").queue();
                return;
            }
            if (!event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MANAGE_ROLES)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "I don't have permissions to administrate roles on this server!").queue();
                return;
            }
            // Regex from: Fabricio20
            final String finalReason = timePattern.matcher(reason).replaceAll("");
            MantaroObj data = db.getMantaroData();
            event.getMessage().getMentionedUsers().forEach(user -> {
                Member m = event.getGuild().getMember(user);
                long time = guildData.getSetModTimeout() > 0 ? System.currentTimeMillis() + guildData.getSetModTimeout() : 0L;
                if (opts.containsKey("time")) {
                    if (!opts.get("time").isPresent() || opts.get("time").get().isEmpty()) {
                        event.getChannel().sendMessage(EmoteReference.WARNING + "You wanted time but didn't specify for how long!").queue();
                        return;
                    }
                    time = System.currentTimeMillis() + Utils.parseTime(opts.get("time").get());
                    if (time > System.currentTimeMillis() + TimeUnit.DAYS.toMillis(10)) {
                        // smh smh smfh god fuck rethinkdb just
                        // dont
                        event.getChannel().sendMessage(EmoteReference.ERROR + "Too long...").queue();
                        // smh
                        return;
                    }
                    if (time < 0) {
                        event.getChannel().sendMessage("You cannot mute someone for negative time!").queue();
                        return;
                    }
                    data.getMutes().put(user.getIdLong(), Pair.of(event.getGuild().getId(), time));
                    data.save();
                    dbGuild.save();
                } else {
                    if (time > 0) {
                        if (time > System.currentTimeMillis() + TimeUnit.DAYS.toMillis(10)) {
                            event.getChannel().sendMessage(EmoteReference.ERROR + "The default mute timeout length is too long (Maximum: 10 days)...").queue();
                            return;
                        }
                        data.getMutes().put(user.getIdLong(), Pair.of(event.getGuild().getId(), time));
                        data.save();
                        dbGuild.save();
                    } else {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "You didn't specify any time!").queue();
                        return;
                    }
                }
                if (m.getRoles().contains(mutedRole)) {
                    event.getChannel().sendMessage(EmoteReference.WARNING + "This user already has a mute role assigned. Please do `~>unmute` to unmute them.").queue();
                    return;
                }
                if (!event.getGuild().getSelfMember().canInteract(m)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot assign the mute role to this user because they're in a higher hierarchy than me, or the role is in a higher hierarchy!").queue();
                    return;
                }
                if (!event.getMember().canInteract(m)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "I cannot assign the mute role to this user because they're in a higher hierarchy than me, or the role is in a higher hierarchy than you!").queue();
                    return;
                }
                final DBGuild dbg = db.getGuild(event.getGuild());
                event.getGuild().getController().addSingleRoleToMember(m, mutedRole).reason(String.format("Muted by %#s for %s: %s", event.getAuthor(), Utils.formatDuration(time - System.currentTimeMillis()), finalReason)).queue();
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Added mute role to **" + m.getEffectiveName() + (time > 0 ? "** for around " + Utils.getHumanizedTime(time - System.currentTimeMillis()) : "**")).queue();
                dbg.getData().setCases(dbg.getData().getCases() + 1);
                dbg.saveAsync();
                ModLog.log(event.getMember(), user, finalReason, ModLog.ModAction.MUTE, dbg.getData().getCases());
            });
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Mute").setDescription("**Mutes the specified users**").addField("Usage", "`~>mute <user> <reason> [-time <time>]` - Mutes the specified users.", false).addField("Parameters", "`users` - The users to mute. Needs to be mentions.\n" + "`[-time <time>]` - The time to mute an user for. For example `~>mute @Natan#1289 wew, nice -time 1m20s` will mute Natan for 1 minute and 20 seconds.", false).addField("Considerations", "To unmute an user, do `~>unmute`.", false).addField("Extended usage", "`time` - can be used with the following parameters: " + "d (days), s (second), m (minutes), h (hour). **For example -time 1d1h will mute for one day and one hour.**", false).build();
        }
    });
    mute.addOption("defaultmutetimeout:set", new Option("Default mute timeout", "Sets the default mute timeout for ~>mute.\n" + "This command will set the timeout of ~>mute to a fixed value **unless you specify another time in the command**\n" + "**Example:** `~>opts defaultmutetimeout set 1m20s`\n" + "**Considerations:** Time is in 1m20s or 1h10m3s format, for example.", OptionType.GUILD).setAction(((event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You have to specify a timeout in the format of 1m20s, for example.").queue();
            return;
        }
        if (!(args[0]).matches("(?:(\\d+)h)?(?:(\\d+)m)?(?:(\\d+)s)?")) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Wrong time format. You have to specify a timeout in the format of 1m20s, for example.").queue();
            return;
        }
        long timeoutToSet = Utils.parseTime(args[0]);
        long time = System.currentTimeMillis() + timeoutToSet;
        if (time > System.currentTimeMillis() + TimeUnit.DAYS.toMillis(10)) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Too long...").queue();
            return;
        }
        if (time < 0) {
            event.getChannel().sendMessage("You cannot mute someone for negative time!").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setSetModTimeout(timeoutToSet);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully set mod action timeout to `" + args[0] + "` (" + timeoutToSet + "ms)").queue();
    })).setShortDescription("Sets the default timeout for the ~>mute command"));
    mute.addOption("defaultmutetimeout:reset", new Option("Default mute timeout reset", "Resets the default mute timeout which was set previously with `defaultmusictimeout set`", OptionType.GUILD).setAction((event -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setSetModTimeout(0L);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully reset timeout.").queue();
    })).setShortDescription("Resets the default mute timeout."));
    mute.addOption("muterole:set", new Option("Mute role set", "Sets this guilds mute role to apply on the ~>mute command.\n" + "To use this command you need to specify a role name. *In case the name contains spaces, the name should" + " be wrapped in quotation marks", OptionType.COMMAND).setAction((event, args) -> {
        if (args.length < 1) {
            OptsCmd.onHelp(event);
            return;
        }
        String roleName = String.join(" ", args);
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        List<Role> roleList = event.getGuild().getRolesByName(roleName, true);
        if (roleList.size() == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I didn't find a role with that name!").queue();
        } else if (roleList.size() == 1) {
            Role role = roleList.get(0);
            guildData.setMutedRole(role.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.OK + "Set mute role to **" + roleName + "**").queue();
        } else {
            DiscordUtils.selectList(event, roleList, role -> String.format("%s (ID: %s)  | Position: %s", role.getName(), role.getId(), role.getPosition()), s -> OptsCmd.getOpts().baseEmbed(event, "Select the Mute Role:").setDescription(s).build(), role -> {
                guildData.setMutedRole(role.getId());
                dbGuild.saveAsync();
                event.getChannel().sendMessage(EmoteReference.OK + "Set mute role to **" + roleName + "**").queue();
            });
        }
    }).setShortDescription("Sets this guilds mute role to apply on the ~>mute command"));
    mute.addOption("muterole:unbind", new Option("Mute Role unbind", "Resets the current value set for the mute role", OptionType.GENERAL).setAction(event -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setMutedRole(null);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.OK + "Correctly reset the mute role.").queue();
    }).setShortDescription("Resets the current value set for the mute role."));
}
Also used : Module(net.kodehawa.mantarobot.core.modules.Module) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) StringUtils(net.kodehawa.mantarobot.utils.StringUtils) Member(net.dv8tion.jda.core.entities.Member) Pair(net.kodehawa.mantarobot.utils.Pair) Utils(net.kodehawa.mantarobot.utils.Utils) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Permission(net.dv8tion.jda.core.Permission) CommandRegistry(net.kodehawa.mantarobot.core.CommandRegistry) Map(java.util.Map) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) OptionType(net.kodehawa.mantarobot.options.core.OptionType) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Role(net.dv8tion.jda.core.entities.Role) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) TimeUnit(java.util.concurrent.TimeUnit) Option(net.kodehawa.mantarobot.options.core.Option) ModLog(net.kodehawa.mantarobot.commands.moderation.ModLog) List(java.util.List) ManagedDatabase(net.kodehawa.mantarobot.db.ManagedDatabase) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) MantaroObj(net.kodehawa.mantarobot.db.entities.MantaroObj) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) MantaroObj(net.kodehawa.mantarobot.db.entities.MantaroObj) Role(net.dv8tion.jda.core.entities.Role) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) Option(net.kodehawa.mantarobot.options.core.Option) ManagedDatabase(net.kodehawa.mantarobot.db.ManagedDatabase) Map(java.util.Map) Member(net.dv8tion.jda.core.entities.Member) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Example 3 with Role

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

the class BirthdayTask method handle.

public void handle(int shardId) {
    try {
        BirthdayCacher cache = MantaroBot.getInstance().getBirthdayCacher();
        if (cache == null)
            return;
        if (!cache.isDone)
            return;
        int i = 0;
        int r = 0;
        JDA jda = MantaroBot.getInstance().getShard(shardId);
        log.info("Checking birthdays in shard {} to assign roles...", jda.getShardInfo() == null ? 0 : jda.getShardInfo().getShardId());
        long start = System.currentTimeMillis();
        Calendar cal = Calendar.getInstance();
        String now = dateFormat.format(cal.getTime()).substring(0, 5);
        Map<String, String> cached = cache.cachedBirthdays;
        SnowflakeCacheView<Guild> guilds = jda.getGuildCache();
        for (Guild guild : guilds) {
            GuildData tempData = db.getGuild(guild).getData();
            if (tempData.getBirthdayChannel() != null && tempData.getBirthdayRole() != null) {
                Role birthdayRole = guild.getRoleById(tempData.getBirthdayRole());
                TextChannel channel = guild.getTextChannelById(tempData.getBirthdayChannel());
                if (channel != null && birthdayRole != null) {
                    if (!guild.getSelfMember().canInteract(birthdayRole))
                        // Go to next guild...
                        continue;
                    if (tempData.getGuildAutoRole() != null && birthdayRole.getId().equals(tempData.getGuildAutoRole()))
                        continue;
                    if (birthdayRole.isPublicRole())
                        continue;
                    if (birthdayRole.isManaged())
                        continue;
                    Map<String, String> guildMap = cached.entrySet().stream().filter(map -> guild.getMemberById(map.getKey()) != null).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
                    for (Map.Entry<String, String> data : guildMap.entrySet()) {
                        Member member = guild.getMemberById(data.getKey());
                        String birthday = data.getValue();
                        if (birthday == null) {
                            log.debug("Birthday is null? Continuing to next iteration...");
                            // shouldn't happen
                            continue;
                        }
                        // tada!
                        if (birthday.substring(0, 5).equals(now)) {
                            log.debug("Assigning birthday role on guild {} (M: {})", guild.getId(), member.getEffectiveName());
                            if (!member.getRoles().contains(birthdayRole)) {
                                try {
                                    guild.getController().addSingleRoleToMember(member, birthdayRole).reason("Birthday assigner. If you see this happening for every member of your server, or in unintended ways, please do ~>opts birthday disable").queue(s -> {
                                        channel.sendMessage(String.format(EmoteReference.POPPER + "**%s is a year older now! Wish them a happy birthday.** :tada:", member.getEffectiveName())).queue();
                                        MantaroBot.getInstance().getStatsClient().increment("birthdays_logged");
                                    });
                                    log.debug("Assigned birthday role on guild {} (M: {})", guild.getId(), member.getEffectiveName());
                                    i++;
                                // Something went boom, ignore and continue
                                } catch (Exception e) {
                                    log.debug("Something went boom while assigning a birthday role?...");
                                }
                            }
                        } else {
                            // day passed
                            if (member.getRoles().contains(birthdayRole)) {
                                try {
                                    log.debug("Removing birthday role on guild {} (M: {})", guild.getId(), member.getEffectiveName());
                                    guild.getController().removeRolesFromMember(member, birthdayRole).reason("Birthday assigner. If you see this happening for every member of your server, or in unintended ways, please do ~>opts birthday disable").queue();
                                    r++;
                                // Something went boom, ignore and continue
                                } catch (Exception e) {
                                    log.debug("Something went boom while removing a birthday role?...");
                                }
                            }
                        }
                    }
                }
            }
        }
        long end = System.currentTimeMillis();
        String toSend = String.format("Finished checking birthdays for shard %s, people assigned: %d, people divested: %d, took %dms", jda.getShardInfo() == null ? 0 : jda.getShardInfo().getShardId(), i, r, (end - start));
        log.info(toSend);
    } catch (Exception e) {
        e.printStackTrace();
        Sentry.capture(e);
    }
}
Also used : Role(net.dv8tion.jda.core.entities.Role) Member(net.dv8tion.jda.core.entities.Member) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Collectors(java.util.stream.Collectors) FastDateFormat(org.apache.commons.lang3.time.FastDateFormat) MantaroBot(net.kodehawa.mantarobot.MantaroBot) Guild(net.dv8tion.jda.core.entities.Guild) Slf4j(lombok.extern.slf4j.Slf4j) ManagedDatabase(net.kodehawa.mantarobot.db.ManagedDatabase) Calendar(java.util.Calendar) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) Map(java.util.Map) SnowflakeCacheView(net.dv8tion.jda.core.utils.cache.SnowflakeCacheView) JDA(net.dv8tion.jda.core.JDA) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Sentry(io.sentry.Sentry) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) JDA(net.dv8tion.jda.core.JDA) Calendar(java.util.Calendar) Guild(net.dv8tion.jda.core.entities.Guild) Role(net.dv8tion.jda.core.entities.Role) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Map(java.util.Map) Member(net.dv8tion.jda.core.entities.Member)

Example 4 with Role

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

the class CommandOptions method onRegister.

@Subscribe
public void onRegister(OptionRegistryEvent e) {
    // region disallow
    registerOption("server:command:disallow", "Command disallow", "Disallows a command from being triggered at all. Use the command name\n" + "**Example:** `~>opts server command disallow 8ball`", "Disallows a command from being triggered at all.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        String commandName = args[0];
        if (DefaultCommandProcessor.REGISTRY.commands().get(commandName) == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "No command called " + commandName).queue();
            return;
        }
        if (commandName.equals("opts") || commandName.equals("help")) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot disable the options or the help command.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.getDisabledCommands().add(commandName);
        event.getChannel().sendMessage(EmoteReference.MEGA + "Disabled " + commandName + " on this server.").queue();
        dbGuild.saveAsync();
    });
    // endregion
    // region allow
    registerOption("server:command:allow", "Command allow", "Allows a command from being triggered. Use the command name\n" + "**Example:** `~>opts server command allow 8ball`", "Allows a command from being triggered.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        String commandName = args[0];
        if (DefaultCommandProcessor.REGISTRY.commands().get(commandName) == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "No command called " + commandName).queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.getDisabledCommands().remove(commandName);
        event.getChannel().sendMessage(EmoteReference.MEGA + "Enabled " + commandName + " on this server.").queue();
        dbGuild.saveAsync();
    });
    // endregion
    // region specific
    registerOption("server:command:specific:disallow", "Specific command disallow", "Disallows a command from being triggered at all in a specific channel. Use the channel **name** and command name\n" + "**Example:** `~>opts server command specific disallow general 8ball`", "Disallows a command from being triggered at all in a specific channel.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the channel name and the command to disallow!").queue();
            return;
        }
        String channelName = args[0];
        String commandName = args[1];
        if (DefaultCommandProcessor.REGISTRY.commands().get(commandName) == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "No command called " + commandName).queue();
            return;
        }
        if (commandName.equals("opts") || commandName.equals("help")) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot disable the options or the help command.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        TextChannel channel = Utils.findChannel(event, channelName);
        if (channel == null)
            return;
        String id = channel.getId();
        guildData.getChannelSpecificDisabledCommands().computeIfAbsent(id, k -> new ArrayList<>());
        guildData.getChannelSpecificDisabledCommands().get(id).add(commandName);
        event.getChannel().sendMessage(EmoteReference.MEGA + "Disabled " + commandName + " on channel #" + channel.getName() + ".").queue();
        dbGuild.saveAsync();
    });
    registerOption("server:command:specific:allow", "Specific command allow", "Re-allows a command from being triggered in a specific channel. Use the channel **name** and command name\n" + "**Example:** `~>opts server command specific allow general 8ball`", "Re-allows a command from being triggered in a specific channel.", ((event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the channel name and the command to disallow!").queue();
            return;
        }
        String channelName = args[0];
        String commandName = args[1];
        if (DefaultCommandProcessor.REGISTRY.commands().get(commandName) == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "No command called " + commandName).queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        TextChannel channel = Utils.findChannel(event, channelName);
        if (channel == null)
            return;
        String id = channel.getId();
        guildData.getChannelSpecificDisabledCommands().computeIfAbsent(id, k -> new ArrayList<>());
        guildData.getChannelSpecificDisabledCommands().get(id).remove(commandName);
        event.getChannel().sendMessage(EmoteReference.MEGA + "Enabled " + commandName + " on channel #" + channel.getName() + ".").queue();
        dbGuild.saveAsync();
    }));
    // endregion
    // region channel
    // region disallow
    registerOption("server:channel:disallow", "Channel disallow", "Disallows a channel from commands. Use the channel **name**\n" + "**Example:** `~>opts server channel disallow general`", "Disallows a channel from commands.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        if (args[0].equals("*")) {
            Set<String> allChannelsMinusCurrent = event.getGuild().getTextChannels().stream().filter(textChannel -> textChannel.getId().equals(event.getChannel().getId())).map(ISnowflake::getId).collect(Collectors.toSet());
            guildData.getDisabledChannels().addAll(allChannelsMinusCurrent);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Disallowed all channels except the current one. " + "You can start allowing channels one by one again with `opts server channel allow` from **this** channel. " + "You can disallow this channel later if you so desire.").queue();
            return;
        }
        if ((guildData.getDisabledChannels().size() + 1) >= event.getGuild().getTextChannels().size()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot disable more channels since the bot wouldn't be able to talk otherwise :<").queue();
            return;
        }
        Consumer<TextChannel> consumer = textChannel -> {
            guildData.getDisabledChannels().add(textChannel.getId());
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.OK + "Channel " + textChannel.getAsMention() + " will not longer listen to commands").queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, args[0], consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    // endregion
    // region allow
    registerOption("server:channel:allow", "Channel allow", "Allows a channel from commands. Use the channel **name**\n" + "**Example:** `~>opts server channel allow general`", "Re-allows a channel from commands.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        if (args[0].equals("*")) {
            guildData.getDisabledChannels().clear();
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "All channels are allowed now.").queue();
            return;
        }
        Consumer<TextChannel> consumer = textChannel -> {
            guildData.getDisabledChannels().remove(textChannel.getId());
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.OK + "Channel " + textChannel.getAsMention() + " will now listen to commands").queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, args[0], consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    // endregion
    // endregion
    // region category
    registerOption("category:disable", "Disable categories", "Disables a specified category.\n" + "If a non-valid category it's specified, it will display a list of valid categories\n" + "You need the category name, for example ` ~>opts category disable Action`", "Disables a specified category", (event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toDisable = Category.lookupFromString(args[0]);
        if (toDisable == null) {
            AtomicInteger at = new AtomicInteger();
            event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
            return;
        }
        if (guildData.getDisabledCategories().contains(toDisable)) {
            event.getChannel().sendMessage(EmoteReference.WARNING + "This category is already disabled.").queue();
            return;
        }
        if (toDisable.toString().equals("Moderation")) {
            event.getChannel().sendMessage(EmoteReference.WARNING + "You cannot disable moderation since it contains this command.").queue();
            return;
        }
        guildData.getDisabledCategories().add(toDisable);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Disabled category `" + toDisable.toString() + "`").queue();
    });
    registerOption("category:enable", "Enable categories", "Enables a specified category.\n" + "If a non-valid category it's specified, it will display a list of valid categories\n" + "You need the category name, for example ` ~>opts category enable Action`", "Enables a specified category", (event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toEnable = Category.lookupFromString(args[0]);
        if (toEnable == null) {
            AtomicInteger at = new AtomicInteger();
            event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
            return;
        }
        guildData.getDisabledCategories().remove(toEnable);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Enabled category `" + toEnable.toString() + "`").queue();
    });
    // region specific
    registerOption("category:specific:disable", "Disable categories on a specific channel", "Disables a specified category on a specific channel.\n" + "If a non-valid category it's specified, it will display a list of valid categories\n" + "You need the category name and the channel name, for example ` ~>opts category specific disable Action general`", "Disables a specified category", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable and the channel where.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toDisable = Category.lookupFromString(args[0]);
        String channelName = args[1];
        Consumer<TextChannel> consumer = selectedChannel -> {
            if (toDisable == null) {
                AtomicInteger at = new AtomicInteger();
                event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
                return;
            }
            guildData.getChannelSpecificDisabledCategories().computeIfAbsent(selectedChannel.getId(), uwu -> new ArrayList<>());
            if (guildData.getChannelSpecificDisabledCategories().get(selectedChannel.getId()).contains(toDisable)) {
                event.getChannel().sendMessage(EmoteReference.WARNING + "This category is already disabled.").queue();
                return;
            }
            if (toDisable.toString().equals("Moderation")) {
                event.getChannel().sendMessage(EmoteReference.WARNING + "You cannot disable moderation since it contains this command.").queue();
                return;
            }
            guildData.getChannelSpecificDisabledCategories().get(selectedChannel.getId()).add(toDisable);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Disabled category `" + toDisable.toString() + "` on channel " + selectedChannel.getAsMention()).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    registerOption("category:specific:enable", "Enable categories on a specific channel", "Enables a specified category on a specific channel.\n" + "If a non-valid category it's specified, it will display a list of valid categories\n" + "You need the category name and the channel name, for example ` ~>opts category specific enable Action general`", "Enables a specified category", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable and the channel where.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toEnable = Category.lookupFromString(args[0]);
        String channelName = args[1];
        Consumer<TextChannel> consumer = selectedChannel -> {
            if (toEnable == null) {
                AtomicInteger at = new AtomicInteger();
                event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
                return;
            }
            if (selectedChannel == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a valid channel!").queue();
                return;
            }
            List l = guildData.getChannelSpecificDisabledCategories().computeIfAbsent(selectedChannel.getId(), uwu -> new ArrayList<>());
            if (l.isEmpty() || !l.contains(toEnable)) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "This category wasn't disabled?").queue();
                return;
            }
            guildData.getChannelSpecificDisabledCategories().get(selectedChannel.getId()).remove(toEnable);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Enabled category `" + toEnable.toString() + "` on channel " + selectedChannel.getAsMention()).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    // endregion
    // endregion
    registerOption("server:role:specific:disallow", "Disallows a role from executing an specific command", "Disallows a role from executing an specific command\n" + "This command takes the command to disallow and the role name afterwards. If the role name contains spaces, wrap it in quotes \"like this\"\n" + "Example: `~>opts server role specific disallow daily Member`", "Disallows a role from executing an specific command", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need the role and the command to disallow!").queue();
            return;
        }
        String commandDisallow = args[0];
        String roleDisallow = args[1];
        Consumer<Role> consumer = role -> {
            DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
            GuildData guildData = dbGuild.getData();
            if (!DefaultCommandProcessor.REGISTRY.commands().containsKey(commandDisallow)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That command doesn't exist!").queue();
                return;
            }
            if (commandDisallow.equals("opts") || commandDisallow.equals("help")) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot disable the options or the help command.").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCommands().computeIfAbsent(role.getId(), key -> new ArrayList<>());
            if (guildData.getRoleSpecificDisabledCommands().get(role.getId()).contains(commandDisallow)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "This command was already disabled for the specified role.").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCommands().get(role.getId()).add(commandDisallow);
            dbGuild.save();
            event.getChannel().sendMessage(String.format("%sSuccessfully restricted command `%s` for role `%s`", EmoteReference.CORRECT, commandDisallow, role.getName())).queue();
        };
        Role role = Utils.findRoleSelect(event, roleDisallow, consumer);
        if (role != null) {
            consumer.accept(role);
        }
    });
    registerOption("server:role:specific:allow", "Allows a role from executing an specific command", "Allows a role from executing an specific command\n" + "This command takes either the role name, id or mention and the command to disallow afterwards. If the role name contains spaces, wrap it in quotes \"like this\"\n" + "Example: `~>opts server role specific allow daily Member`", "Allows a role from executing an specific command", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need the role and the command to allow!").queue();
            return;
        }
        String commandAllow = args[0];
        String roleAllow = args[1];
        Consumer<Role> consumer = role -> {
            if (role == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a valid role!").queue();
                return;
            }
            DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
            GuildData guildData = dbGuild.getData();
            if (!DefaultCommandProcessor.REGISTRY.commands().containsKey(commandAllow)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That command doesn't exist!").queue();
                return;
            }
            List l = guildData.getRoleSpecificDisabledCommands().computeIfAbsent(role.getId(), key -> new ArrayList<>());
            if (l.isEmpty() || !l.contains(commandAllow)) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "This command wasn't disabled for this role?").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCommands().get(role.getId()).remove(commandAllow);
            dbGuild.save();
            event.getChannel().sendMessage(String.format("%sSuccessfully un-restricted command `%s` for role `%s`", EmoteReference.CORRECT, commandAllow, role.getName())).queue();
        };
        Role role = Utils.findRoleSelect(event, roleAllow, consumer);
        if (role != null) {
            consumer.accept(role);
        }
    });
    registerOption("category:role:specific:disable", "Disables a role from executing commands in an specified category.", "Disables a role from executing commands in an specified category\n" + "This command takes the category name and the role to disable afterwards. If the role name contains spaces, wrap it in quotes \"like this\"\n" + "Example: `~>opts category role specific disable Currency Member`", "Disables a role from executing commands in an specified category.", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable and the role to.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toDisable = Category.lookupFromString(args[0]);
        String roleName = args[1];
        Consumer<Role> consumer = role -> {
            if (toDisable == null) {
                AtomicInteger at = new AtomicInteger();
                event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCategories().computeIfAbsent(role.getId(), cat -> new ArrayList<>());
            if (guildData.getRoleSpecificDisabledCategories().get(role.getId()).contains(toDisable)) {
                event.getChannel().sendMessage(EmoteReference.WARNING + "This category is already disabled.").queue();
                return;
            }
            if (toDisable.toString().equals("Moderation")) {
                event.getChannel().sendMessage(EmoteReference.WARNING + "You cannot disable moderation since it contains this command.").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCategories().get(role.getId()).add(toDisable);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Disabled category `" + toDisable.toString() + "` for role " + role.getName()).queue();
        };
        Role role = Utils.findRoleSelect(event, roleName, consumer);
        if (role != null) {
            consumer.accept(role);
        }
    });
    registerOption("category:role:specific:enable", "Enables a role from executing commands in an specified category.", "Enables a role from executing commands in an specified category\n" + "This command takes the category name and the role to enable afterwards. If the role name contains spaces, wrap it in quotes \"like this\"\n" + "Example: `~>opts category role specific enable Currency Member`", "Enables a role from executing commands in an specified category.", (event, args) -> {
        if (args.length < 2) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a category to disable and the channel where.").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        Category toEnable = Category.lookupFromString(args[0]);
        String roleName = args[1];
        Consumer<Role> consumer = role -> {
            if (toEnable == null) {
                AtomicInteger at = new AtomicInteger();
                event.getChannel().sendMessage(EmoteReference.ERROR + "You entered a invalid category. A list of valid categories to disable (case-insensitive) will be shown below" + "```md\n" + Category.getAllNames().stream().map(name -> "#" + at.incrementAndGet() + ". " + name).collect(Collectors.joining("\n")) + "```").queue();
                return;
            }
            if (role == null) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "That's not a valid role!").queue();
                return;
            }
            List l = guildData.getRoleSpecificDisabledCategories().computeIfAbsent(role.getId(), cat -> new ArrayList<>());
            if (l.isEmpty() || !l.contains(toEnable)) {
                event.getChannel().sendMessage(EmoteReference.THINKING + "This category wasn't disabled?").queue();
                return;
            }
            guildData.getRoleSpecificDisabledCategories().get(role.getId()).remove(toEnable);
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Enabled category `" + toEnable.toString() + "` for role " + role.getName()).queue();
        };
        Role role = Utils.findRoleSelect(event, roleName, consumer);
        if (role != null) {
            consumer.accept(role);
        }
    });
}
Also used : Role(net.dv8tion.jda.core.entities.Role) DefaultCommandProcessor(net.kodehawa.mantarobot.core.processor.DefaultCommandProcessor) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) Option(net.kodehawa.mantarobot.options.annotations.Option) Utils(net.kodehawa.mantarobot.utils.Utils) Set(java.util.Set) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) Collectors(java.util.stream.Collectors) ArrayList(java.util.ArrayList) Consumer(java.util.function.Consumer) List(java.util.List) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ISnowflake(net.dv8tion.jda.core.entities.ISnowflake) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Subscribe(com.google.common.eventbus.Subscribe) OptionType(net.kodehawa.mantarobot.options.core.OptionType) OptionRegistryEvent(net.kodehawa.mantarobot.options.event.OptionRegistryEvent) OptionHandler(net.kodehawa.mantarobot.options.core.OptionHandler) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) ArrayList(java.util.ArrayList) Role(net.dv8tion.jda.core.entities.Role) TextChannel(net.dv8tion.jda.core.entities.TextChannel) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) ArrayList(java.util.ArrayList) List(java.util.List) Subscribe(com.google.common.eventbus.Subscribe)

Example 5 with Role

use of net.dv8tion.jda.core.entities.Role in project FlareBot by FlareBot.

the class GuildUtils method getRole.

/**
 * Gets a {@link Role} that matches a string. Case doesn't matter.
 *
 * @param s       The String to get a role from
 * @param guildId The id of the {@link Guild} to get the role from
 * @param channel The channel to send an error message to if anything goes wrong.
 * @return null if the role doesn't, otherwise a list of roles matching the string
 */
public static Role getRole(String s, String guildId, TextChannel channel) {
    Guild guild = Getters.getGuildById(guildId);
    Role role = guild.getRoles().stream().filter(r -> r.getName().equalsIgnoreCase(s)).findFirst().orElse(null);
    if (role != null)
        return role;
    try {
        role = guild.getRoleById(Long.parseLong(s.replaceAll("[^0-9]", "")));
        if (role != null)
            return role;
    } catch (NumberFormatException | NullPointerException ignored) {
    }
    if (channel != null) {
        if (guild.getRolesByName(s, true).isEmpty()) {
            String closest = null;
            int distance = LEVENSHTEIN_DISTANCE;
            for (Role role1 : guild.getRoles().stream().filter(role1 -> FlareBotManager.instance().getGuild(guildId).getSelfAssignRoles().contains(role1.getId())).collect(Collectors.toList())) {
                int currentDistance = StringUtils.getLevenshteinDistance(role1.getName(), s);
                if (currentDistance < distance) {
                    distance = currentDistance;
                    closest = role1.getName();
                }
            }
            MessageUtils.sendErrorMessage("That role does not exist! " + (closest != null ? "Maybe you mean `" + closest + "`" : ""), channel);
            return null;
        } else {
            return guild.getRolesByName(s, true).get(0);
        }
    }
    return null;
}
Also used : Role(net.dv8tion.jda.core.entities.Role) Role(net.dv8tion.jda.core.entities.Role) Member(net.dv8tion.jda.core.entities.Member) TextChannel(net.dv8tion.jda.core.entities.TextChannel) FlareBot(stream.flarebot.flarebot.FlareBot) PlayerManager(com.arsenarsen.lavaplayerbridge.PlayerManager) StringUtils(org.apache.commons.lang3.StringUtils) GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) Collectors(java.util.stream.Collectors) Getters(stream.flarebot.flarebot.Getters) Objects(java.util.Objects) Guild(net.dv8tion.jda.core.entities.Guild) List(java.util.List) Permission(net.dv8tion.jda.core.Permission) User(net.dv8tion.jda.core.entities.User) Emote(net.dv8tion.jda.core.entities.Emote) FlareBotManager(stream.flarebot.flarebot.FlareBotManager) Constants(stream.flarebot.flarebot.util.Constants) MessageUtils(stream.flarebot.flarebot.util.MessageUtils) Pattern(java.util.regex.Pattern) Guild(net.dv8tion.jda.core.entities.Guild)

Aggregations

Role (net.dv8tion.jda.core.entities.Role)11 List (java.util.List)7 MantaroData (net.kodehawa.mantarobot.data.MantaroData)6 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)6 Subscribe (com.google.common.eventbus.Subscribe)5 Collectors (java.util.stream.Collectors)5 Permission (net.dv8tion.jda.core.Permission)5 TextChannel (net.dv8tion.jda.core.entities.TextChannel)5 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)5 Utils (net.kodehawa.mantarobot.utils.Utils)5 Map (java.util.Map)4 Member (net.dv8tion.jda.core.entities.Member)4 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)4 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)4 DiscordUtils (net.kodehawa.mantarobot.utils.DiscordUtils)4 Optional (java.util.Optional)3 Slf4j (lombok.extern.slf4j.Slf4j)3 Guild (net.dv8tion.jda.core.entities.Guild)3 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)3 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)3