Search in sources :

Example 26 with DBGuild

use of net.kodehawa.mantarobot.db.entities.DBGuild in project MantaroBot by Mantaro.

the class MessageCmds method prune.

private void prune(GuildMessageReceivedEvent event, List<Message> messageHistory) {
    messageHistory = messageHistory.stream().filter(message -> !message.getCreationTime().isBefore(OffsetDateTime.now().minusWeeks(2))).collect(Collectors.toList());
    TextChannel channel = event.getChannel();
    if (messageHistory.isEmpty()) {
        channel.sendMessage(EmoteReference.ERROR + "There are no messages newer than 2 weeks old, discord won't let me delete them.").queue();
        return;
    }
    final int size = messageHistory.size();
    if (messageHistory.size() < 3) {
        channel.sendMessage(EmoteReference.ERROR + "Too few messages to prune!").queue();
        return;
    }
    channel.deleteMessages(messageHistory).queue(success -> {
        channel.sendMessage(EmoteReference.PENCIL + "Successfully pruned " + size + " messages from this channel!").queue(message -> message.delete().queueAfter(15, TimeUnit.SECONDS));
        DBGuild db = MantaroData.db().getGuild(event.getGuild());
        db.getData().setCases(db.getData().getCases() + 1);
        db.saveAsync();
        ModLog.log(event.getMember(), null, "Pruned Messages", ModLog.ModAction.PRUNE, db.getData().getCases());
    }, error -> {
        if (error instanceof PermissionException) {
            PermissionException pe = (PermissionException) error;
            channel.sendMessage(String.format("%sLack of permission while pruning messages(No permission provided: %s)", EmoteReference.ERROR, pe.getPermission())).queue();
        } else {
            channel.sendMessage(String.format("%sUnknown error while pruning messages<%s>: %s", EmoteReference.ERROR, error.getClass().getSimpleName(), error.getMessage())).queue();
            error.printStackTrace();
        }
    });
}
Also used : PermissionException(net.dv8tion.jda.core.exceptions.PermissionException) TextChannel(net.dv8tion.jda.core.entities.TextChannel) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild)

Example 27 with DBGuild

use of net.kodehawa.mantarobot.db.entities.DBGuild in project MantaroBot by Mantaro.

the class MiscCmds method iamFunction.

protected static void iamFunction(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 already have this role, silly!").queue();
                return;
            }
            try {
                event.getGuild().getController().addSingleRoleToMember(event.getMember(), role).reason("Auto-assignable roles assigner (~>iam)").queue(aVoid -> event.getChannel().sendMessage(String.format("%s%s, you've been given the **%s** role", EmoteReference.OK, event.getMember().getEffectiveName(), role.getName())).queue());
            } catch (PermissionException pex) {
                event.getChannel().sendMessage(String.format("%sI couldn't take from 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 28 with DBGuild

use of net.kodehawa.mantarobot.db.entities.DBGuild in project MantaroBot by Mantaro.

the class OwnerCmd method owner.

@Subscribe
public void owner(CommandRegistry cr) {
    cr.register("owner", new SimpleCommand(Category.OWNER) {

        @Override
        public CommandPermission permission() {
            return CommandPermission.OWNER;
        }

        @Override
        public MessageEmbed help(GuildMessageReceivedEvent event) {
            return helpEmbed(event, "Owner command").setDescription("`~>owner premium add <id> <days>` - Adds premium to the specified user for x days.").build();
        }

        @Override
        public void call(GuildMessageReceivedEvent event, String content, String[] args) {
            if (args.length < 1) {
                onHelp(event);
                return;
            }
            String option = args[0];
            if (option.equals("premium")) {
                String sub = args[1].substring(0, args[1].indexOf(' '));
                if (sub.equals("add")) {
                    try {
                        String userId;
                        String[] values = SPLIT_PATTERN.split(args[1], 3);
                        try {
                            Long.parseLong(values[1]);
                            userId = values[1];
                        } catch (Exception e) {
                            if (!event.getMessage().getMentionedUsers().isEmpty()) {
                                userId = event.getMessage().getMentionedUsers().get(0).getId();
                                return;
                            } else {
                                event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid user id").queue();
                                return;
                            }
                        }
                        DBUser db = MantaroData.db().getUser(userId);
                        db.incrementPremium(TimeUnit.DAYS.toMillis(Long.parseLong(values[2])));
                        db.saveAsync();
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "The premium feature for user " + db.getId() + " now is until " + new Date(db.getPremiumUntil())).queue();
                        return;
                    } catch (IndexOutOfBoundsException e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify id and number of days").queue();
                        e.printStackTrace();
                        return;
                    }
                }
                if (sub.equals("guild")) {
                    try {
                        String[] values = SPLIT_PATTERN.split(args[1], 3);
                        DBGuild db = MantaroData.db().getGuild(values[1]);
                        db.incrementPremium(TimeUnit.DAYS.toMillis(Long.parseLong(values[2])));
                        db.saveAsync();
                        event.getChannel().sendMessage(EmoteReference.CORRECT + "The premium feature for guild " + db.getId() + " now is until " + new Date(db.getPremiumUntil())).queue();
                        return;
                    } catch (IndexOutOfBoundsException e) {
                        event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify id and number of days").queue();
                        e.printStackTrace();
                        return;
                    }
                }
            }
            onHelp(event);
        }

        @Override
        public String[] splitArgs(String content) {
            return SPLIT_PATTERN.split(content, 2);
        }
    });
}
Also used : MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) DBUser(net.kodehawa.mantarobot.db.entities.DBUser) CommandPermission(net.kodehawa.mantarobot.core.modules.commands.base.CommandPermission) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) CompilationException(com.github.natanbc.javaeval.CompilationException) Subscribe(com.google.common.eventbus.Subscribe)

Example 29 with DBGuild

use of net.kodehawa.mantarobot.db.entities.DBGuild in project MantaroBot by Mantaro.

the class GuildOptions method onRegistry.

@Subscribe
public void onRegistry(OptionRegistryEvent e) {
    // region opts birthday
    registerOption("birthday:enable", "Birthday Monitoring enable", "Enables birthday monitoring. You need the channel **name** and the role name (it assigns that role on birthday)\n" + "**Example:** `~>opts birthday enable general Birthday`, `~>opts birthday enable general \"Happy Birthday\"`", "Enables birthday monitoring.", (event, args) -> {
        if (args.length < 2) {
            OptsCmd.onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        try {
            String channel = args[0];
            String role = args[1];
            TextChannel channelObj = Utils.findChannel(event, channel);
            if (channelObj == null)
                return;
            String channelId = channelObj.getId();
            Role roleObj = event.getGuild().getRolesByName(role.replace(channelId, ""), true).get(0);
            if (roleObj.isPublicRole()) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot set the everyone role as a birthday role! " + "Remember that the birthday role is a role that gets assigned to the person when the birthday comes, and then removes when the day passes away.").queue();
                return;
            }
            if (guildData.getGuildAutoRole() != null && roleObj.getId().equals(guildData.getGuildAutoRole())) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "You cannot set the autorole role as a birthday role! " + "Remember that the birthday role is a role that gets assigned to the person when the birthday comes, and then removes when the day passes away.").queue();
                return;
            }
            event.getChannel().sendMessage(EmoteReference.WARNING + "Remember that the birthday role is a role that gets assigned to the person when the birthday comes, and then removes when the day passes away.\n" + "The role *has to be a newly created role or a role you don't use for anyone else*. It MUST NOT be a role you already have on your users.\n" + "This is because of how the birthday assigner works: It assigns a temporary role to the person having its birthday, and unassigns it when the birthday day has passed. " + "**This means that everyone with the birthday role will get the role removed the day the birthday passes through**. Please take caution when choosing what role to use, as a misconfiguration might make bad things happen (really)!\n" + "If you have any doubts on how to configure it, you can always join our support guild and ask. You can also check `~>opts help birthday enable` for an example.\n\n" + "Type **yes** if you agree to set the role " + roleObj.getName() + " as a birthday role, and **no** to cancel. This timeouts in 45 seconds.").queue();
            InteractiveOperations.createOverriding(event.getChannel(), 45, interactiveEvent -> {
                String content = interactiveEvent.getMessage().getContentRaw();
                if (content.equalsIgnoreCase("yes")) {
                    String roleId = roleObj.getId();
                    guildData.setBirthdayChannel(channelId);
                    guildData.setBirthdayRole(roleId);
                    dbGuild.saveAsync();
                    event.getChannel().sendMessage(String.format(EmoteReference.MEGA + "Birthday logging enabled on this server with parameters -> Channel: `%s (%s)` and role: `%s (%s)`", channelObj.getAsMention(), channelId, role, roleId)).queue();
                    return Operation.COMPLETED;
                } else if (content.equalsIgnoreCase("no")) {
                    interactiveEvent.getChannel().sendMessage(EmoteReference.CORRECT + "Cancelled request.").queue();
                    return Operation.COMPLETED;
                }
                return Operation.IGNORED;
            });
        } catch (Exception ex) {
            if (ex instanceof IndexOutOfBoundsException) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "I didn't find a channel or role!\n " + "**Remember, you don't have to mention neither the role or the channel, rather just type its " + "name, order is <channel> <role>, without the leading \"<>\".**").queue();
                return;
            }
            event.getChannel().sendMessage(EmoteReference.ERROR + "You supplied invalid arguments for this command " + EmoteReference.SAD).queue();
            OptsCmd.onHelp(event);
        }
    });
    registerOption("birthday:disable", "Birthday disable", "Disables birthday monitoring.", (event) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setBirthdayChannel(null);
        guildData.setBirthdayRole(null);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.MEGA + "Birthday logging has been disabled on this server").queue();
    });
    // endregion
    // region prefix
    // region set
    registerOption("prefix:set", "Prefix set", "Sets the server prefix.\n" + "**Example:** `~>opts prefix set .`", "Sets the server prefix.", (event, args) -> {
        if (args.length < 1) {
            onHelp(event);
            return;
        }
        String prefix = args[0];
        if (prefix.length() > 200) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Don't you think that's a bit too long?").queue();
            return;
        }
        if (prefix.isEmpty()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Cannot set the guild prefix to nothing...").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setGuildCustomPrefix(prefix);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.MEGA + "Your server's custom prefix has been set to " + prefix).queue();
    });
    // endregion
    // region clear
    registerOption("prefix:clear", "Prefix clear", "Clear the server prefix.\n" + "**Example:** `~>opts prefix clear`", "Resets the server prefix.", (event) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setGuildCustomPrefix(null);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.MEGA + "Your server's custom prefix has been disabled").queue();
    });
    // endregion
    // endregion
    // region autorole
    // region set
    registerOption("autorole:set", "Autorole set", "Sets the server autorole. This means every user who joins will get this role. **You need to use the role name, if it contains spaces" + " you need to wrap it in quotation marks**\n" + "**Example:** `~>opts autorole set Member`, `~>opts autorole set \"Magic Role\"`", "Sets the server autorole.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String name = args[0];
        List<Role> roles = event.getGuild().getRolesByName(name, true);
        if (roles.isEmpty()) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I couldn't find a role with that name").queue();
            return;
        }
        if (roles.size() <= 1) {
            if (!event.getMember().canInteract(roles.get(0))) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "This role is placed higher than your highest role, therefore you cannot put it as autorole!").queue();
                return;
            }
            guildData.setGuildAutoRole(roles.get(0).getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "The server autorole is now set to: **" + roles.get(0).getName() + "** (Position: " + roles.get(0).getPosition() + ")").queue();
            return;
        }
        event.getChannel().sendMessage(new EmbedBuilder().setTitle("Selection", null).setDescription("").build()).queue();
        DiscordUtils.selectList(event, roles, role -> String.format("%s (ID: %s)  | Position: %s", role.getName(), role.getId(), role.getPosition()), s -> ((SimpleCommand) optsCmd).baseEmbed(event, "Select the Role:").setDescription(s).build(), role -> {
            if (!event.getMember().canInteract(role)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "This role is placed higher than your highest role, therefore you cannot put it as autorole!").queue();
                return;
            }
            guildData.setGuildAutoRole(role.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.OK + "The server autorole is now set to role: **" + role.getName() + "** (Position: " + role.getPosition() + ")").queue();
        });
    });
    // endregion
    // region unbind
    registerOption("autorole:unbind", "Autorole clear", "Clear the server autorole.\n" + "**Example:** `~>opts autorole unbind`", "Resets the servers autorole.", (event) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setGuildAutoRole(null);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.OK + "The autorole for this server has been removed.").queue();
    });
    // endregion
    // endregion
    // region usermessage
    // region resetchannel
    registerOption("usermessage:resetchannel", "Reset message channel", "Clears the join/leave message channel.\n" + "**Example:** `~>opts usermessage resetchannel`", "Clears the join/leave message channel.", (event) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setLogJoinLeaveChannel(null);
        guildData.setLogLeaveChannel(null);
        guildData.setLogJoinChannel(null);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Sucessfully reset the join/leave channel.").queue();
    });
    // endregion
    // region resetdata
    registerOption("usermessage:resetdata", "Reset join/leave message data", "Resets the join/leave message data.\n" + "**Example:** `~>opts usermessage resetdata`", "Resets the join/leave message data.", (event) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setLeaveMessage(null);
        guildData.setJoinMessage(null);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Sucessfully reset the join/leave message.").queue();
    });
    // endregion
    // region channel
    registerOption("usermessage:join:channel", "Sets the join message channel", "Sets the join channel, you need the channel **name**\n" + "**Example:** `~>opts usermessage join channel join-magic`\n" + "You can reset it by doing `~>opts usermessage join resetchannel`", "Sets the join message channel", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String channelName = args[0];
        Consumer<TextChannel> consumer = tc -> {
            guildData.setLogJoinChannel(tc.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.OK + "The user join log channel is now set to: " + tc.getAsMention()).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    registerOption("usermessage:join:resetchannel", "Resets the join message channel", "Resets the join message channel", event -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setLogJoinChannel(null);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully reset log join channel!").queue();
    });
    registerOption("usermessage:leave:channel", "Sets the leave message channel", "Sets the leave channel, you need the channel **name**\n" + "**Example:** `~>opts usermessage leave channel leave-magic`\n" + "You can reset it by doing `~>opts usermessage leave resetchannel`", "Sets the leave message channel", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String channelName = args[0];
        Consumer<TextChannel> consumer = tc -> {
            guildData.setLogLeaveChannel(tc.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "The user leave log channel is now set to: " + tc.getAsMention()).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    registerOption("usermessage:leave:resetchannel", "Resets the leave message channel", "Resets the leave message channel", event -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setLogLeaveChannel(null);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Successfully reset log leave channel!").queue();
    });
    registerOption("usermessage:channel", "Set message channel", "Sets the join/leave message channel. You need the channel **name**\n" + "**Example:** `~>opts usermessage channel join-magic`\n" + "Warning: if you set this, you cannot set individual join/leave channels unless you reset the channel.", "Sets the join/leave message channel.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String channelName = args[0];
        Consumer<TextChannel> consumer = textChannel -> {
            guildData.setLogJoinLeaveChannel(textChannel.getId());
            dbGuild.save();
            event.getChannel().sendMessage(EmoteReference.OK + "The logging Join/Leave channel is set to: " + textChannel.getAsMention()).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
    // endregion
    // region joinmessage
    registerOption("usermessage:joinmessage", "User join message", "Sets the join message.\n" + "**Example:** `~>opts usermessage joinmessage Welcome $(event.user.name) to the $(event.guild.name) server! Hope you have a great time`", "Sets the join message.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String joinMessage = String.join(" ", args);
        guildData.setJoinMessage(joinMessage);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Server join message set to: " + joinMessage).queue();
    });
    // endregion
    // region leavemessage
    registerOption("usermessage:leavemessage", "User leave message", "Sets the leave message.\n" + "**Example:** `~>opts usermessage leavemessage Sad to see you depart, $(event.user.name)`", "Sets the leave message.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String leaveMessage = String.join(" ", args);
        guildData.setLeaveMessage(leaveMessage);
        dbGuild.save();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Server leave message set to: " + leaveMessage).queue();
    });
    // endregion
    // endregion
    // region autoroles
    // region add
    registerOption("autoroles:add", "Autoroles add", "Adds a role to the `~>iam` list.\n" + "You need the name of the iam and the name of the role. If the role contains spaces wrap it in quotation marks.\n" + "**Example:** `~>opts autoroles add member Member`, `~>opts autoroles add wew \"A role with spaces on its name\"`", "Adds an auto-assignable role to the iam lists.", (event, args) -> {
        if (args.length < 2) {
            onHelp(event);
            return;
        }
        String roleName = args[1];
        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);
            if (!event.getMember().canInteract(role)) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "This role is placed higher than your highest role, therefore you cannot put it as an auto-assignable role!").queue();
                return;
            }
            guildData.getAutoroles().put(args[0], role.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.OK + "Added autorole **" + args[0] + "**, which gives the role " + "**" + role.getName() + "**").queue();
        } else {
            DiscordUtils.selectList(event, roleList, role -> String.format("%s (ID: %s)  | Position: %s", role.getName(), role.getId(), role.getPosition()), s -> ((SimpleCommand) optsCmd).baseEmbed(event, "Select the Role:").setDescription(s).build(), role -> {
                if (!event.getMember().canInteract(role)) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "This role is placed higher than your highest role, therefore you cannot put it as an auto-assignable role!").queue();
                    return;
                }
                guildData.getAutoroles().put(args[0], role.getId());
                dbGuild.saveAsync();
                event.getChannel().sendMessage(EmoteReference.OK + "Added autorole **" + args[0] + "**, which gives the " + "role " + "**" + role.getName() + "**").queue();
            });
        }
    });
    // region remove
    registerOption("autoroles:remove", "Autoroles remove", "Removes a role from the `~>iam` list.\n" + "You need the name of the iam.\n" + "**Example:** `~>opts autoroles remove iamname`", "Removes an auto-assignable role from iam.", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        HashMap<String, String> autoroles = guildData.getAutoroles();
        if (autoroles.containsKey(args[0])) {
            autoroles.remove(args[0]);
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.OK + "Removed autorole " + args[0]).queue();
        } else {
            event.getChannel().sendMessage(EmoteReference.ERROR + "I couldn't find an autorole with that name").queue();
        }
    });
    // endregion
    // region clear
    registerOption("autoroles:clear", "Autoroles clear", "Removes all autoroles.", "Removes all autoroles.", (event, args) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        dbGuild.getData().getAutoroles().clear();
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Cleared all autoroles!").queue();
    });
    // endregion
    // region custom
    registerOption("admincustom", "Admin custom commands", "Locks custom commands to admin-only.\n" + "Example: `~>opts admincustom true`", "Locks custom commands to admin-only.", (event, args) -> {
        if (args.length == 0) {
            OptsCmd.onHelp(event);
            return;
        }
        String action = args[0];
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        try {
            guildData.setCustomAdminLock(Boolean.parseBoolean(action));
            dbGuild.save();
            String toSend = EmoteReference.CORRECT + (Boolean.parseBoolean(action) ? "Custom command creation " + "is now admin only." : "Custom command creation can now be done by anyone.");
            event.getChannel().sendMessage(toSend).queue();
        } catch (Exception ex) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "Silly, that's not a boolean value!").queue();
        }
    });
    // endregion
    registerOption("timedisplay:set", "Time display set", "Toggles between 12h and 24h time display.\n" + "Example: `~>opts timedisplay 24h`", "Toggles between 12h and 24h time display.", (event, args) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify a mode (12h or 24h)").queue();
            return;
        }
        String mode = args[0];
        switch(mode) {
            case "12h":
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Set time display mode to 12h").queue();
                guildData.setTimeDisplay(1);
                dbGuild.save();
                break;
            case "24h":
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Set time display mode to 24h").queue();
                guildData.setTimeDisplay(0);
                dbGuild.save();
                break;
            default:
                event.getChannel().sendMessage(EmoteReference.ERROR + "Not a valid choice. Valid choices: **24h**, **12h**").queue();
                break;
        }
    });
    registerOption("server:role:disallow", "Role disallow", "Disallows all users with a role from executing commands.\n" + "You need to provide the name of the role to disallow from mantaro.\n" + "Example: `~>opts server role disallow bad`, `~>opts server role disallow \"No commands\"`", "Disallows all users with a role from executing commands.", (event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the name of the role!").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String roleName = String.join(" ", args);
        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.getDisabledRoles().add(role.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Disabled role " + role.getName() + " from executing commands.").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.getDisabledRoles().add(role.getId());
                dbGuild.saveAsync();
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Disabled role " + role.getName() + " from executing commands.").queue();
            });
        }
    });
    registerOption("server:role:allow", "Role allow", "Allows all users with a role from executing commands.\n" + "You need to provide the name of the role to allow from mantaro. Has to be already disabled.\n" + "Example: `~>opts server role allow bad`, `~>opts server role allow \"No commands\"`", "Allows all users with a role from executing commands (Has to be already disabled)", (event, args) -> {
        if (args.length == 0) {
            event.getChannel().sendMessage(EmoteReference.ERROR + "You need to specify the name of the role!").queue();
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String roleName = String.join(" ", args);
        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);
            if (!guildData.getDisabledRoles().contains(role.getId())) {
                event.getChannel().sendMessage(EmoteReference.ERROR + "This role isn't disabled!").queue();
                return;
            }
            guildData.getDisabledRoles().remove(role.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.CORRECT + "Allowed role " + role.getName() + " to execute commands.").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 -> {
                if (!guildData.getDisabledRoles().contains(role.getId())) {
                    event.getChannel().sendMessage(EmoteReference.ERROR + "This role isn't disabled!").queue();
                    return;
                }
                guildData.getDisabledRoles().remove(role.getId());
                dbGuild.saveAsync();
                event.getChannel().sendMessage(EmoteReference.CORRECT + "Allowed role " + role.getName() + " to execute commands.").queue();
            });
        }
    });
    registerOption("server:ignorebots:autoroles:toggle", "Bot autorole ignore", "Toggles between ignoring bots on autorole assign and not.", (event) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        boolean ignore = guildData.isIgnoreBotsAutoRole();
        guildData.setIgnoreBotsAutoRole(!ignore);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Set bot autorole ignore to: **" + guildData.isIgnoreBotsAutoRole() + "**").queue();
    });
    registerOption("server:ignorebots:joinleave:toggle", "Bot join/leave ignore", "Toggles between ignoring bots on join/leave message.", (event) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        boolean ignore = guildData.isIgnoreBotsWelcomeMessage();
        guildData.setIgnoreBotsWelcomeMessage(!ignore);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Set bot autorole ignore to: **" + guildData.isIgnoreBotsWelcomeMessage() + "**").queue();
    });
    registerOption("levelupmessages:toggle", "Level-up toggle", "Toggles level up messages, remember that after this you have to set thee channel and the message!", "Toggles level up messages", event -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        boolean ignore = guildData.isEnabledLevelUpMessages();
        guildData.setEnabledLevelUpMessages(!ignore);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Set level up messages to: **" + guildData.isEnabledLevelUpMessages() + "**").queue();
    });
    registerOption("levelupmessages:message:set", "Level-up message", "Sets the message to display on level up", "Sets the level up message", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String levelUpMessage = String.join(" ", args);
        guildData.setLevelUpMessage(levelUpMessage);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Server level-up message set to: " + levelUpMessage).queue();
    });
    registerOption("levelupmessages:message:clear", "Level-up message clear", "Clears the message to display on level up", "Clears the message to display on level up", (event, args) -> {
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        guildData.setLevelUpMessage(null);
        dbGuild.saveAsync();
        event.getChannel().sendMessage(EmoteReference.CORRECT + "Cleared level-up message!").queue();
    });
    registerOption("levelupmessages:channel:set", "Level-up message channel", "Sets the channel to display level up messages", "Sets the channel to display level up messages", (event, args) -> {
        if (args.length == 0) {
            onHelp(event);
            return;
        }
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        GuildData guildData = dbGuild.getData();
        String channelName = args[0];
        Consumer<TextChannel> consumer = textChannel -> {
            guildData.setLevelUpChannel(textChannel.getId());
            dbGuild.saveAsync();
            event.getChannel().sendMessage(EmoteReference.OK + "The level-up channel has been set to: " + textChannel.getAsMention()).queue();
        };
        TextChannel channel = Utils.findChannelSelect(event, channelName, consumer);
        if (channel != null) {
            consumer.accept(channel);
        }
    });
}
Also used : Role(net.dv8tion.jda.core.entities.Role) InteractiveOperations(net.kodehawa.mantarobot.core.listeners.operations.InteractiveOperations) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Option(net.kodehawa.mantarobot.options.annotations.Option) Utils(net.kodehawa.mantarobot.utils.Utils) HashMap(java.util.HashMap) DiscordUtils(net.kodehawa.mantarobot.utils.DiscordUtils) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Consumer(java.util.function.Consumer) OptsCmd(net.kodehawa.mantarobot.commands.OptsCmd) List(java.util.List) 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) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) OptionType(net.kodehawa.mantarobot.options.core.OptionType) OptionRegistryEvent(net.kodehawa.mantarobot.options.event.OptionRegistryEvent) Operation(net.kodehawa.mantarobot.core.listeners.operations.core.Operation) OptionHandler(net.kodehawa.mantarobot.options.core.OptionHandler) OptsCmd.optsCmd(net.kodehawa.mantarobot.commands.OptsCmd.optsCmd) GuildData(net.kodehawa.mantarobot.db.entities.helpers.GuildData) Role(net.dv8tion.jda.core.entities.Role) TextChannel(net.dv8tion.jda.core.entities.TextChannel) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild) SimpleCommand(net.kodehawa.mantarobot.core.modules.commands.SimpleCommand) Subscribe(com.google.common.eventbus.Subscribe)

Example 30 with DBGuild

use of net.kodehawa.mantarobot.db.entities.DBGuild in project MantaroBot by Mantaro.

the class DiscordUtils method selectInt.

public static Future<Void> selectInt(GuildMessageReceivedEvent event, int max, IntConsumer valueConsumer, Consumer<Void> cancelConsumer) {
    return InteractiveOperations.createOverriding(event.getChannel(), 30, (e) -> {
        if (!e.getAuthor().equals(event.getAuthor()))
            return Operation.IGNORED;
        // Replace prefix because people seem to think you have to add the prefix before literally everything.
        DBGuild dbGuild = MantaroData.db().getGuild(event.getGuild());
        String message = e.getMessage().getContentRaw();
        if (message.equalsIgnoreCase("&cancel")) {
            e.getChannel().sendMessage(EmoteReference.CORRECT + "Cancelled operation.").queue();
            cancelConsumer.accept(null);
            return Operation.COMPLETED;
        }
        for (String s : config.prefix) {
            if (message.toLowerCase().startsWith(s)) {
                message = message.substring(s.length());
            }
        }
        String guildCustomPrefix = dbGuild.getData().getGuildCustomPrefix();
        if (guildCustomPrefix != null && !guildCustomPrefix.isEmpty() && message.toLowerCase().startsWith(guildCustomPrefix)) {
            message = message.substring(guildCustomPrefix.length());
        }
        try {
            int choose = Integer.parseInt(message);
            if (choose < 1 || choose > max)
                return Operation.IGNORED;
            valueConsumer.accept(choose);
            return Operation.COMPLETED;
        } catch (Exception ignored) {
        }
        return Operation.IGNORED;
    });
}
Also used : DBGuild(net.kodehawa.mantarobot.db.entities.DBGuild)

Aggregations

DBGuild (net.kodehawa.mantarobot.db.entities.DBGuild)30 MantaroData (net.kodehawa.mantarobot.data.MantaroData)18 GuildData (net.kodehawa.mantarobot.db.entities.helpers.GuildData)18 EmoteReference (net.kodehawa.mantarobot.utils.commands.EmoteReference)18 Utils (net.kodehawa.mantarobot.utils.Utils)15 Subscribe (com.google.common.eventbus.Subscribe)14 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)14 List (java.util.List)12 EmbedBuilder (net.dv8tion.jda.core.EmbedBuilder)11 SimpleCommand (net.kodehawa.mantarobot.core.modules.commands.SimpleCommand)11 Slf4j (lombok.extern.slf4j.Slf4j)10 Category (net.kodehawa.mantarobot.core.modules.commands.base.Category)10 Permission (net.dv8tion.jda.core.Permission)9 PermissionException (net.dv8tion.jda.core.exceptions.PermissionException)9 DiscordUtils (net.kodehawa.mantarobot.utils.DiscordUtils)9 Collectors (java.util.stream.Collectors)8 MantaroBot (net.kodehawa.mantarobot.MantaroBot)8 CommandRegistry (net.kodehawa.mantarobot.core.CommandRegistry)8 Module (net.kodehawa.mantarobot.core.modules.Module)8 TimeUnit (java.util.concurrent.TimeUnit)7