Search in sources :

Example 6 with Role

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

use of net.dv8tion.jda.core.entities.Role 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 8 with Role

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

the class Events method onGuildMemberJoin.

@Override
public void onGuildMemberJoin(GuildMemberJoinEvent event) {
    if (event.getMember().getUser().isBot() || event.getMember().getUser().isFake())
        return;
    PlayerCache cache = flareBot.getPlayerCache(event.getMember().getUser().getId());
    cache.setLastSeen(LocalDateTime.now());
    GuildWrapper wrapper = FlareBotManager.instance().getGuild(event.getGuild().getId());
    if (wrapper == null)
        return;
    if (wrapper.isBlocked())
        return;
    if (flareBot.getManager().getGuild(event.getGuild().getId()).getWelcome() != null) {
        Welcome welcome = wrapper.getWelcome();
        if ((welcome.getChannelId() != null && Getters.getChannelById(welcome.getChannelId()) != null) || welcome.isDmEnabled()) {
            if (welcome.getChannelId() != null && Getters.getChannelById(welcome.getChannelId()) != null && welcome.isGuildEnabled()) {
                TextChannel channel = Getters.getChannelById(welcome.getChannelId());
                if (channel == null || !channel.canTalk()) {
                    welcome.setGuildEnabled(false);
                    MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Cannot send welcome messages in " + (channel == null ? welcome.getChannelId() : channel.getAsMention()) + " due to this, welcomes have been disabled!");
                    return;
                }
                if (welcome.isGuildEnabled()) {
                    String guildMsg = VariableUtils.parseVariables(welcome.getRandomGuildMessage(), wrapper, null, event.getUser());
                    // Deprecated values
                    guildMsg = guildMsg.replace("%user%", event.getMember().getUser().getName()).replace("%guild%", event.getGuild().getName()).replace("%mention%", event.getMember().getUser().getAsMention());
                    channel.sendMessage(guildMsg).queue();
                    if (guildMsg.contains("%user%") || guildMsg.contains("%guild%") || guildMsg.contains("%mention%")) {
                        MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Your guild welcome message contains deprecated variables! " + "Please check the docs at the link below for a list of all the " + "variables you can use!\n" + "https://docs.flarebot.stream/variables");
                    }
                }
            }
            if (welcome.isDmEnabled()) {
                // We can't DM other bots.
                if (event.getMember().getUser().isBot())
                    return;
                String dmMsg = VariableUtils.parseVariables(welcome.getRandomDmMessage(), wrapper, null, event.getUser());
                // Deprecated values
                dmMsg = dmMsg.replace("%user%", event.getMember().getUser().getName()).replace("%guild%", event.getGuild().getName()).replace("%mention%", event.getMember().getUser().getAsMention());
                MessageUtils.sendPM(event.getMember().getUser(), dmMsg);
                if (dmMsg.contains("%user%") || dmMsg.contains("%guild%") || dmMsg.contains("%mention%")) {
                    MessageUtils.sendPM(event.getGuild().getOwner().getUser(), "Your DM welcome message contains deprecated variables! " + "Please check the docs at the link below for a list of all the " + "variables you can use!\n" + "https://docs.flarebot.stream/variables");
                }
            }
        } else
            welcome.setGuildEnabled(false);
    }
    if (event.getMember().getUser().isBot())
        return;
    if (!wrapper.getAutoAssignRoles().isEmpty()) {
        Set<String> autoAssignRoles = wrapper.getAutoAssignRoles();
        List<Role> roles = new ArrayList<>();
        for (String s : autoAssignRoles) {
            Role role = event.getGuild().getRoleById(s);
            if (role != null) {
                roles.add(role);
            } else
                autoAssignRoles.remove(s);
        }
        try {
            event.getGuild().getController().addRolesToMember(event.getMember(), roles).queue((n) -> {
            }, e1 -> handle(e1, event, roles));
            StringBuilder sb = new StringBuilder("```\n");
            for (Role role : roles) {
                sb.append(role.getName()).append(" (").append(role.getId()).append(")\n");
            }
            sb.append("```");
            ModlogHandler.getInstance().postToModlog(wrapper, ModlogEvent.FLAREBOT_AUTOASSIGN_ROLE, event.getUser(), new MessageEmbed.Field("Roles", sb.toString(), false));
        } catch (Exception e1) {
            handle(e1, event, roles);
        }
    }
}
Also used : MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) ArrayList(java.util.ArrayList) PlayerCache(stream.flarebot.flarebot.objects.PlayerCache) InsufficientPermissionException(net.dv8tion.jda.core.exceptions.InsufficientPermissionException) GuildWrapper(stream.flarebot.flarebot.objects.GuildWrapper) Role(net.dv8tion.jda.core.entities.Role) TextChannel(net.dv8tion.jda.core.entities.TextChannel) Welcome(stream.flarebot.flarebot.objects.Welcome)

Example 9 with Role

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

the class GuildWrapper method getMutedRole.

@Nullable
public Role getMutedRole() {
    if (mutedRoleID == null) {
        Role mutedRole = GuildUtils.getRole("Muted", getGuild()).isEmpty() ? null : GuildUtils.getRole("Muted", getGuild()).get(0);
        if (mutedRole == null) {
            if (!getGuild().getSelfMember().hasPermission(Permission.MANAGE_ROLES, Permission.MANAGE_PERMISSIONS))
                return null;
            try {
                mutedRole = getGuild().getController().createRole().setName("Muted").submit().get();
                if (!getGuild().getSelfMember().getRoles().isEmpty())
                    getGuild().getController().modifyRolePositions().selectPosition(mutedRole).moveTo(getGuild().getSelfMember().getRoles().get(0).getPosition() - 1).queue();
                mutedRoleID = mutedRole.getId();
                handleMuteChannels(mutedRole);
                return mutedRole;
            } catch (InterruptedException | ExecutionException e) {
                FlareBot.LOGGER.error("Error creating role!", e);
                return null;
            }
        } else {
            mutedRoleID = mutedRole.getId();
            handleMuteChannels(mutedRole);
            return mutedRole;
        }
    } else {
        Role mutedRole = getGuild().getRoleById(mutedRoleID);
        if (mutedRole == null) {
            mutedRoleID = null;
            return getMutedRole();
        } else {
            handleMuteChannels(mutedRole);
            return mutedRole;
        }
    }
}
Also used : Role(net.dv8tion.jda.core.entities.Role) ExecutionException(java.util.concurrent.ExecutionException) Nullable(javax.annotation.Nullable)

Example 10 with Role

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

the class AccesslistModificationCommand method execute.

@Override
protected void execute() {
    // Check if the input actually had enough arguments
    if (input.size() < 1) {
        handleError(String.format("You didn't supply the ID of the entity to %s!\nPlease use `+%s <idTo%s>`.", getActionDescription("%s", "remove from the %s"), primaryCommandName, StringUtils.capitalize(targetAccesslist)));
        return;
    }
    // Get the input after the arguments as one string representation
    String target = Utils.drainQueueToString(input);
    String[] targetParts = target.split(":", 2);
    String targetType = targetParts[0];
    String targetName = targetParts.length > 1 ? targetParts[1] : null;
    // Identify what the input was targeting
    switch(targetType) {
        case "user":
            {
                // Retrieve a list of users which could be targeted by the search
                List<Member> candidates = ev.getGuild().getMembersByEffectiveName(targetName, true);
                // See if there were any search results
                if (candidates.size() <= 0) {
                    handleError(String.format("No user was found in this server having name **%s**!", targetName));
                    return;
                }
                // Otherwise, generate a selector and let the user decide what the target was
                if (candidates.size() == 1) {
                    performAccesslistModification(new BannableUser(candidates.get(0).getUser()));
                } else {
                    LinkedHashMap<String, BannableEntity> candidateMap = new LinkedHashMap<>();
                    candidates.forEach(c -> candidateMap.put(Utils.userAsString(c.getUser()), new BannableUser(c.getUser())));
                    new SelectorBuilder<>(this).setOptionMap(candidateMap).build();
                }
                break;
            }
        case "role":
            {
                // Retrieve a list of roles which could be targeted by the search
                List<Role> candidates = ev.getGuild().getRolesByName(targetName, true);
                // See if there were any search results
                if (candidates.size() <= 0) {
                    handleError(String.format("No role was found in this server having name **%s**!", targetName));
                    return;
                }
                // Otherwise, generate a selector and let the user decide what the target was
                if (candidates.size() == 1) {
                    performAccesslistModification(new BannableRole(candidates.get(0)));
                } else {
                    LinkedHashMap<String, BannableEntity> candidateMap = new LinkedHashMap<>();
                    candidates.forEach(c -> candidateMap.put(c.getName(), new BannableRole(c)));
                    new SelectorBuilder<>(this).setOptionMap(candidateMap).build();
                }
                break;
            }
        default:
            BannableEntity targetEntity = null;
            // Test if the id was targeting a role or user. If not, throw an error, otherwise whitelist the target
            if (ev.getGuild().getRoles().stream().anyMatch(role -> role.getId().equals(target))) {
                targetEntity = new BannableRole(target);
            }
            if (ev.getGuild().getMembers().stream().anyMatch(member -> member.getUser().getId().equals(target))) {
                targetEntity = new BannableUser(target);
            }
            if (targetEntity == null) {
                handleError(String.format("The ID you supplied (`%s`) was neither a role or user in this server!", target));
                return;
            }
            // Detect if the id specified is already blacklisted
            if (performActionCheck(ev.getGuild(), targetEntity)) {
                handleError(String.format("The entity you tried to %s is already %sed for this server!", getActionDescription("%s", "remove from the %s"), targetAccesslist));
                return;
            }
            performAccesslistModification(targetEntity);
            break;
    }
}
Also used : Role(net.dv8tion.jda.core.entities.Role) Logger(org.slf4j.Logger) DiscordController(st.photonbur.Discord.Bot.lightbotv3.controller.DiscordController) BannableRole(st.photonbur.Discord.Bot.lightbotv3.entity.bannable.BannableRole) StringUtils(st.photonbur.Discord.Bot.lightbotv3.misc.StringUtils) Member(net.dv8tion.jda.core.entities.Member) Utils(st.photonbur.Discord.Bot.lightbotv3.misc.Utils) Command(st.photonbur.Discord.Bot.lightbotv3.command.Command) SelectionEvent(st.photonbur.Discord.Bot.lightbotv3.misc.menu.selector.SelectionEvent) LinkedHashMap(java.util.LinkedHashMap) Guild(net.dv8tion.jda.core.entities.Guild) BannableEntity(st.photonbur.Discord.Bot.lightbotv3.entity.bannable.BannableEntity) List(java.util.List) BannableUser(st.photonbur.Discord.Bot.lightbotv3.entity.bannable.BannableUser) Permission(net.dv8tion.jda.core.Permission) User(net.dv8tion.jda.core.entities.User) LoggerUtils(st.photonbur.Discord.Bot.lightbotv3.main.LoggerUtils) SelectorBuilder(st.photonbur.Discord.Bot.lightbotv3.misc.menu.selector.SelectorBuilder) Selector(st.photonbur.Discord.Bot.lightbotv3.misc.menu.selector.Selector) CommandAliasCollectionBuilder(st.photonbur.Discord.Bot.lightbotv3.command.alias.CommandAliasCollectionBuilder) BannableUser(st.photonbur.Discord.Bot.lightbotv3.entity.bannable.BannableUser) BannableEntity(st.photonbur.Discord.Bot.lightbotv3.entity.bannable.BannableEntity) List(java.util.List) LinkedHashMap(java.util.LinkedHashMap) BannableRole(st.photonbur.Discord.Bot.lightbotv3.entity.bannable.BannableRole)

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