Search in sources :

Example 1 with Option

use of net.kodehawa.mantarobot.options.core.Option 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 2 with Option

use of net.kodehawa.mantarobot.options.core.Option in project MantaroBot by Mantaro.

the class OptsCmd method register.

@Subscribe
public void register(CommandRegistry registry) {
    registry.register("opts", optsCmd = new SimpleCommand(Category.MODERATION, CommandPermission.ADMIN) {

        @Override
        protected void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length == 0) {
                OptsCmd.onHelp(event);
                return;
            }
            if (args.length == 1 && args[0].equalsIgnoreCase("list") || args[0].equalsIgnoreCase("ls")) {
                StringBuilder builder = new StringBuilder();
                for (String s : Option.getAvaliableOptions()) {
                    builder.append(s).append("\n");
                }
                List<String> m = DiscordUtils.divideString(builder);
                List<String> messages = new LinkedList<>();
                boolean hasReactionPerms = event.getGuild().getSelfMember().hasPermission(event.getChannel(), Permission.MESSAGE_ADD_REACTION);
                for (String s1 : m) {
                    messages.add("**Mantaro's Options List**\n" + (hasReactionPerms ? "Use the arrow reactions to change pages. " : "Use &page >> and &page << to change pages and &cancel to end") + "*All options must be prefixed with `~>opts` when running them*\n" + String.format("```prolog\n%s```", s1));
                }
                if (hasReactionPerms) {
                    DiscordUtils.list(event, 45, false, messages);
                } else {
                    DiscordUtils.listText(event, 45, false, messages);
                }
                return;
            }
            if (args.length < 2) {
                event.getChannel().sendMessage(help(event)).queue();
                return;
            }
            StringBuilder name = new StringBuilder();
            if (args[0].equalsIgnoreCase("help")) {
                for (int i = 1; i < args.length; i++) {
                    String s = args[i];
                    if (name.length() > 0)
                        name.append(":");
                    name.append(s);
                    Option option = Option.getOptionMap().get(name.toString());
                    if (option != null) {
                        try {
                            EmbedBuilder builder = new EmbedBuilder().setAuthor(option.getOptionName(), null, event.getAuthor().getEffectiveAvatarUrl()).setDescription(option.getDescription()).setThumbnail("https://cdn.pixabay.com/photo/2012/04/14/16/26/question-34499_960_720.png").addField("Type", option.getType().toString(), false);
                            event.getChannel().sendMessage(builder.build()).queue();
                        } catch (IndexOutOfBoundsException ignored) {
                        }
                        return;
                    }
                }
                event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid option help name.").queue(message -> message.delete().queueAfter(10, TimeUnit.SECONDS));
                return;
            }
            for (int i = 0; i < args.length; i++) {
                String s = args[i];
                if (name.length() > 0)
                    name.append(":");
                name.append(s);
                Option option = Option.getOptionMap().get(name.toString());
                if (option != null) {
                    BiConsumer<GuildMessageReceivedEvent, String[]> callable = Option.getOptionMap().get(name.toString()).getEventConsumer();
                    try {
                        String[] a;
                        if (++i < args.length)
                            a = Arrays.copyOfRange(args, i, args.length);
                        else
                            a = new String[0];
                        callable.accept(event, a);
                        Player p = MantaroData.db().getPlayer(event.getAuthor());
                        if (p.getData().addBadgeIfAbsent(Badge.DID_THIS_WORK)) {
                            p.saveAsync();
                        }
                    } catch (IndexOutOfBoundsException ignored) {
                    }
                    return;
                }
            }
            event.getChannel().sendMessage(EmoteReference.ERROR + "Invalid option or arguments.").queue(message -> message.delete().queueAfter(10, TimeUnit.SECONDS));
            event.getChannel().sendMessage(help(event)).queue();
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Options and Configurations Command").setDescription("**This command allows you to change Mantaro settings for this server.**\n" + "All values set are local rather than global, meaning that they will only effect this server.").addField("Usage", "The command is so big that we moved the description to the wiki. [Click here](https://github.com/Mantaro/MantaroBot/wiki/Configuration) to go to the Wiki Article.", false).build();
        }
    }).addOption("check:data", new Option("Data check.", "Checks the data values you have set on this server. **THIS IS NOT USER-FRIENDLY**", OptionType.GENERAL).setAction(event -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        // Map as follows: name, value
        Map<String, Object> fieldMap = mapObjects(guildData);
        if (fieldMap == null) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot retrieve values. Weird thing...").queue();
            return;
        }
        StringBuilder show = new StringBuilder();
        show.append("Options set for server **").append(event.getGuild().getName()).append("**\n\n");
        AtomicInteger ai = new AtomicInteger();
        for (Entry e : fieldMap.entrySet()) {
            if (e.getKey().equals("localPlayerExperience")) {
                continue;
            }
            show.append(ai.incrementAndGet()).append(".- `").append(e.getKey()).append("`");
            if (e.getValue() == null) {
                show.append(" **is not set to anything.").append("**\n");
            } else {
                show.append(" is set to: **").append(e.getValue()).append("**\n");
            }
        }
        List<String> toSend = DiscordUtils.divideString(1600, show);
        toSend.forEach(message -> event.getChannel().sendMessage(message).queue());
    }).setShortDescription("Checks the data values you have set on this server.")).addOption("reset:all", new Option("Options reset.", "Resets all options set on this server.", OptionType.GENERAL).setAction(event -> {
        // Temporary stuff.
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData temp = MantaroData.db().getGuild(event.getGuild()).getData();
        // The persistent data we wish to maintain.
        String premiumKey = temp.getPremiumKey();
        long quoteLastId = temp.getQuoteLastId();
        long ranPolls = temp.getQuoteLastId();
        String gameTimeoutExpectedAt = temp.getGameTimeoutExpectedAt();
        long cases = temp.getCases();
        // Assign everything all over again
        DBGuild newDbGuild = DBGuild.of(dbGuild.getId(), dbGuild.getPremiumUntil());
        GuildData newTmp = newDbGuild.getData();
        newTmp.setGameTimeoutExpectedAt(gameTimeoutExpectedAt);
        newTmp.setRanPolls(ranPolls);
        newTmp.setCases(cases);
        newTmp.setPremiumKey(premiumKey);
        newTmp.setQuoteLastId(quoteLastId);
        // weee
        newDbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Correctly reset your options!").queue();
    }));
}
Also used : Badge(net.kodehawa.mantarobot.commands.currency.profile.Badge) Module(net.kodehawa.mantarobot.core.modules.Module) Arrays(java.util.Arrays) Command(net.kodehawa.mantarobot.core.modules.commands.base.Command) 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) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) BiConsumer(java.util.function.BiConsumer) Subscribe(com.google.common.eventbus.Subscribe) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) OptionType(net.kodehawa.mantarobot.options.core.OptionType) LinkedList(java.util.LinkedList) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) Player(net.kodehawa.mantarobot.db.entities.Player) Utils.mapObjects(net.kodehawa.mantarobot.utils.Utils.mapObjects) Category(net.kodehawa.mantarobot.core.modules.commands.base.Category) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) TimeUnit(java.util.concurrent.TimeUnit) Option(net.kodehawa.mantarobot.options.core.Option) List(java.util.List) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) EmoteReference(net.kodehawa.mantarobot.utils.commands.EmoteReference) Entry(java.util.Map.Entry) MantaroData(net.kodehawa.mantarobot.data.MantaroData) Player(net.kodehawa.mantarobot.db.entities.Player) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) LinkedList(java.util.LinkedList) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Entry(java.util.Map.Entry) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Option(net.kodehawa.mantarobot.options.core.Option) LinkedList(java.util.LinkedList) List(java.util.List) Map(java.util.Map) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) Subscribe(com.google.common.eventbus.Subscribe)

Aggregations

Subscribe (com.google.common.eventbus.Subscribe)2 List (java.util.List)2 Map (java.util.Map)2 TimeUnit (java.util.concurrent.TimeUnit)2 Permission (net.dv8tion.jda.core.Permission)2 MessageEmbed (net.dv8tion.jda.core.entities.MessageEmbed)2 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)2 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)2 Module (net.kodehawa.mantarobot.core.modules.Module)2 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)2 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)2 Command (net.kodehawa.mantarobot.core.modules.commands.base.Command)2 CommandPermission (net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission)2 MantaroData (net.kodehawa.mantarobot.data.MantaroData)2 DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)2 GuildData (net.kodehawa.mantarobot.db.entities.helpers.GuildData)2 Option (net.kodehawa.mantarobot.options.core.Option)2 OptionType (net.kodehawa.mantarobot.options.core.OptionType)2 DiscordUtils (net.kodehawa.mantarobot.utils.DiscordUtils)2 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)2