Search in sources :

Example 1 with GuildSettings

use of ml.duncte123.skybot.objects.guild.GuildSettings in project SkyBot by duncte123.

the class GuildInfoCommand method sendGuildInfoEmbed.

private void sendGuildInfoEmbed(GuildMessageReceivedEvent event, String inviteString) {
    Guild g = event.getGuild();
    double[] ratio = GuildUtils.getBotRatio(g);
    EmbedBuilder eb = EmbedUtils.defaultEmbed();
    GuildSettings settings = GuildSettingsUtils.getGuild(g);
    if (settings.getServerDesc() != null && !"".equals(settings.getServerDesc())) {
        eb.addField("Server Description", settings.getServerDesc() + "\n", false);
    }
    eb.setThumbnail(event.getGuild().getIconUrl() != null ? event.getGuild().getIconUrl() : "https://i.duncte123.ml/blob/b1nzyblob.png").addField("Basic Info", "**Owner:** " + g.getOwner().getEffectiveName() + "\n" + "**Name:** " + g.getName() + "\n" + "**Prefix:** " + settings.getCustomPrefix() + "\n" + "**Region:** " + g.getRegion().getName() + "\n" + "**Created at:** " + g.getCreationTime().format(DateTimeFormatter.RFC_1123_DATE_TIME) + "\n" + "**Verification level:** " + GuildUtils.verificationLvlToName(g.getVerificationLevel()) + "\n" + inviteString, false).addField("Member Stats", "**Total members:** " + g.getMemberCache().size() + "\n" + "**(Possible) Nitro users:** " + GuildUtils.countAnimatedAvatars(g).get() + "\n" + "**Bot to user ratio:** " + ratio[1] + "% is a bot and " + ratio[0] + "% is a user (total users " + g.getMemberCache().size() + ")", false);
    MessageUtils.sendEmbed(event, eb.build());
}
Also used : EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) Guild(net.dv8tion.jda.core.entities.Guild) GuildSettings(ml.duncte123.skybot.objects.guild.GuildSettings)

Example 2 with GuildSettings

use of ml.duncte123.skybot.objects.guild.GuildSettings in project SkyBot by duncte123.

the class SettingsCommand method executeCommand.

@Override
public void executeCommand(String invoke, String[] args, GuildMessageReceivedEvent event) {
    // noinspection deprecation
    if (!event.getMember().hasPermission(Permission.MANAGE_SERVER) && !event.getAuthor().getId().equals(Settings.wbkxwkZPaG4ni5lm8laY[0])) {
        sendMsg(event, "You don't have permission to run this command");
        return;
    }
    GuildSettings settings = getSettings(event.getGuild());
    boolean isEnabled;
    switch(invoke) {
        case "settings":
        case "options":
            // true <:check:314349398811475968>
            // false <:xmark:314349398824058880>
            TextChannel logChan = AirUtils.getLogChannel(settings.getLogChannel(), event.getGuild());
            TextChannel welcomeLeaveChannel = AirUtils.getLogChannel(settings.getWelcomeLeaveChannel(), event.getGuild());
            MessageEmbed message = EmbedUtils.embedMessage("Here are the settings from this guild.\n" + "**Show join/leave messages:** " + boolToEmoji(settings.isEnableJoinMessage()) + "\n" + "**Swearword filter:** " + boolToEmoji(settings.isEnableSwearFilter()) + "\n" + "**Announce next track:** " + boolToEmoji(settings.isAnnounceTracks()) + "\n" + "**Auto de-hoist:** " + boolToEmoji(settings.isAutoDeHoist()) + "\n" + "**Filter Discord invites:** " + boolToEmoji(settings.isFilterInvites()) + "\n" + "**Join message:** " + settings.getCustomJoinMessage() + "\n" + "**Leave message:** " + settings.getCustomLeaveMessage() + "\n" + "**AutoRole:** " + (settings.getAutoroleRole() == null || settings.getAutoroleRole().equals("") ? "Not Set" : event.getGuild().getRoleById(settings.getAutoroleRole()).getAsMention()) + "\n" + "**Current prefix:** " + settings.getCustomPrefix() + "\n" + "**Modlog Channel:** " + (logChan != null ? logChan.getAsMention() : "none") + "\n" + "**Welcome/Leave channel:** " + (welcomeLeaveChannel != null ? welcomeLeaveChannel.getAsMention() : "none"));
            sendEmbed(event, message);
            break;
        case "setprefix":
            if (args.length < 1) {
                sendMsg(event, "Correct usage is `" + PREFIX + "setPrefix <new prefix>`");
                return;
            }
            String newPrefix = StringUtils.join(args, " ");
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setCustomPrefix(newPrefix));
            sendMsg(event, "New prefix has been set to `" + newPrefix + "`");
            break;
        case "setjoinmessage":
        case "setwelcomenmessage":
            if (args.length < 1) {
                sendMsg(event, "Correct usage is `" + PREFIX + "setJoinMessage <new join message>`");
                return;
            }
            String newJoinMessage = event.getMessage().getContentRaw().split("\\s+", 2)[1].replaceAll("\n", "\\\\n");
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setCustomJoinMessage(newJoinMessage));
            sendMsg(event, "The new join message has been set to `" + newJoinMessage + "`");
            break;
        case "setleavemessage":
            if (args.length < 1) {
                sendMsg(event, "Correct usage is `" + PREFIX + "setleavemessage <new join message>`");
                return;
            }
            String newLeaveMessage = event.getMessage().getContentRaw().split("\\s+", 2)[1].replaceAll("\n", "\\\\n");
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setCustomLeaveMessage(newLeaveMessage));
            sendMsg(event, "The new leave message has been set to `" + newLeaveMessage + "`");
            break;
        case "enablejoinmessage":
        case "disablejoinmessage":
        case "togglejoinmessage":
            isEnabled = settings.isEnableJoinMessage();
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setEnableJoinMessage(!isEnabled));
            sendMsg(event, "The join and leave messages have been " + (!isEnabled ? "enabled" : "disabled") + ".");
            break;
        case "enableswearfilter":
        case "disableswearfilter":
        case "toggleswearfilter":
            isEnabled = settings.isEnableSwearFilter();
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setEnableSwearFilter(!isEnabled));
            sendMsg(event, "The swearword filter has been " + (!isEnabled ? "enabled" : "disabled") + ".");
            break;
        case "setlogchannel":
            if (args.length < 1) {
                sendMsg(event, "Incorrect usage: `" + PREFIX + "setLogChannel [text channel]`");
                return;
            }
            if (event.getMessage().getMentionedChannels().size() > 0) {
                TextChannel tc = event.getMessage().getMentionedChannels().get(0);
                if (!tc.getGuild().getSelfMember().hasPermission(tc, Permission.MESSAGE_WRITE, Permission.MESSAGE_READ)) {
                    sendError(event.getMessage());
                    sendMsg(event, "I'm sorry but I have to be able to talk in that channel.");
                    return;
                }
                GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setLogChannel(tc.getId()));
                sendMsg(event, "The new log channel has been set to " + tc.getAsMention());
                return;
            }
            TextChannel tc = AirUtils.getLogChannel(StringUtils.join(args), event.getGuild());
            if (tc == null) {
                sendMsg(event, "This channel could not be found.");
                return;
            }
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setLogChannel(tc.getId()));
            sendMsg(event, "The new log channel has been set to " + tc.getAsMention());
            break;
        case "setwelcomechannel":
        case "setleavechannel":
            if (args.length < 1) {
                sendMsg(event, "Incorrect usage: `" + PREFIX + "setwelcomechannel [text channel]`");
                return;
            }
            if (event.getMessage().getMentionedChannels().size() > 0) {
                TextChannel welcomeChannel = event.getMessage().getMentionedChannels().get(0);
                if (!welcomeChannel.getGuild().getSelfMember().hasPermission(welcomeChannel, Permission.MESSAGE_WRITE, Permission.MESSAGE_READ)) {
                    sendError(event.getMessage());
                    sendMsg(event, "I'm sorry but I have to be able to talk in that channel.");
                    return;
                }
                GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setWelcomeLeaveChannel(welcomeChannel.getId()));
                sendMsg(event, "The new welcome channel has been set to " + welcomeChannel.getAsMention());
                return;
            }
            TextChannel welcomeChannel = AirUtils.getLogChannel(StringUtils.join(args), event.getGuild());
            if (welcomeChannel == null) {
                sendMsg(event, "This channel could not be found.");
                return;
            }
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setWelcomeLeaveChannel(welcomeChannel.getId()));
            sendMsg(event, "The new welcome channel has been set to " + welcomeChannel.getAsMention());
            break;
        case "autorole":
            if (!event.getGuild().getSelfMember().hasPermission(Permission.MANAGE_ROLES)) {
                sendMsg(event, "I need the _Manage Roles_ permission in order for this feature to work.");
                return;
            }
            if (args.length == 0) {
                sendMsg(event, "Incorrect usage: `" + PREFIX + "autorole <role name/disable>`");
                return;
            }
            if ("disable".equals(args[0])) {
                sendMsg(event, "AutoRole feature has been disabled");
                GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setAutoroleRole(""));
                return;
            }
            List<Role> rolesFound = event.getGuild().getRolesByName(StringUtils.join(args, " "), true);
            if (rolesFound.size() == 0) {
                if (event.getMessage().getMentionedRoles().size() > 0) {
                    rolesFound.add(event.getMessage().getMentionedRoles().get(0));
                } else {
                    sendMsg(event, "I could not find any roles with that name");
                    return;
                }
            }
            if (rolesFound.get(0).getPosition() >= event.getGuild().getSelfMember().getRoles().get(0).getPosition()) {
                sendMsg(event, "I'm sorry but I can't give that role to people, move my role above the role and try again.");
                return;
            }
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setAutoroleRole(rolesFound.get(0).getId()));
            sendMsg(event, "AutoRole has been set to " + rolesFound.get(0).getAsMention());
            break;
        case "setdescription":
            if (args.length < 1) {
                sendError(event.getMessage());
                sendMsg(event, "Incorrect usage\n" + "Correct usage : `" + PREFIX + invoke + " <description>`");
                return;
            } else if ("null".equals(args[0])) {
                GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setServerDesc(null));
                sendMsg(event, "Description has been reset.");
                return;
            }
            String description = event.getMessage().getContentRaw().split("\\s+", 2)[1].replaceAll("\n", "\\\\n");
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setServerDesc(description));
            sendMsg(event, "Description has been updated, check `" + PREFIX + "guildinfo` to see your description");
            break;
        case "toggleannouncetracks":
            boolean shouldAnnounceTracks = !settings.isAnnounceTracks();
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setAnnounceTracks(shouldAnnounceTracks));
            sendMsg(event, "Announcing the next track has been **" + (shouldAnnounceTracks ? "enabled" : "disabled") + "**");
            break;
        case "togglefilterinvites":
            boolean shouldFilterInvites = !settings.isFilterInvites();
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setFilterInvites(shouldFilterInvites));
            sendMsg(event, "Filtering discord invites has been **" + (shouldFilterInvites ? "enabled" : "disabled") + "**");
            break;
        case "toggleautodehoist":
            boolean shouldAutoDeHoist = !settings.isAutoDeHoist();
            GuildSettingsUtils.updateGuildSettings(event.getGuild(), settings.setAutoDeHoist(shouldAutoDeHoist));
            sendMsg(event, "Auto de-hoisting has been **" + (shouldAutoDeHoist ? "enabled" : "disabled") + "**");
            break;
    }
}
Also used : Role(net.dv8tion.jda.core.entities.Role) TextChannel(net.dv8tion.jda.core.entities.TextChannel) MessageEmbed(net.dv8tion.jda.core.entities.MessageEmbed) GuildSettings(ml.duncte123.skybot.objects.guild.GuildSettings)

Example 3 with GuildSettings

use of ml.duncte123.skybot.objects.guild.GuildSettings in project SkyBot by duncte123.

the class GuildSettingsUtils method loadGuildSettings.

/**
 * This will get the settings from our database and store them in the {@link AirUtils#guildSettings settings}
 */
private static void loadGuildSettings() {
    logger.debug("Loading Guild settings.");
    String dbName = AirUtils.DB.getName();
    Connection database = AirUtils.DB.getConnManager().getConnection();
    try {
        Statement smt = database.createStatement();
        ResultSet res = smt.executeQuery("SELECT * FROM " + dbName + ".guildSettings");
        while (res.next()) {
            String guildId = res.getString("guildId");
            AirUtils.guildSettings.put(guildId, new GuildSettings(guildId).setEnableJoinMessage(res.getBoolean("enableJoinMessage")).setEnableSwearFilter(res.getBoolean("enableSwearFilter")).setCustomJoinMessage(replaceNewLines(res.getString("customWelcomeMessage"))).setCustomPrefix(res.getString("prefix")).setLogChannel(res.getString("logChannelId")).setWelcomeLeaveChannel(res.getString("welcomeLeaveChannel")).setCustomLeaveMessage(replaceNewLines(res.getString("customLeaveMessage"))).setAutoroleRole(res.getString("autoRole")).setServerDesc(replaceNewLines(res.getString("serverDesc"))).setAnnounceTracks(res.getBoolean("announceNextTrack")).setAutoDeHoist(res.getBoolean("autoDeHoist")).setFilterInvites(res.getBoolean("filterInvites")));
        }
        logger.debug("Loaded settings for " + AirUtils.guildSettings.keySet().size() + " guilds.");
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            database.close();
        } catch (SQLException e2) {
            e2.printStackTrace();
        }
    }
}
Also used : GuildSettings(ml.duncte123.skybot.objects.guild.GuildSettings)

Example 4 with GuildSettings

use of ml.duncte123.skybot.objects.guild.GuildSettings in project SkyBot by duncte123.

the class BotListener method onGuildMemberLeave.

@Override
public void onGuildMemberLeave(GuildMemberLeaveEvent event) {
    if (event.getMember().equals(event.getGuild().getSelfMember()))
        return;
    GuildSettings settings = GuildSettingsUtils.getGuild(event.getGuild());
    if (settings.isEnableJoinMessage()) {
        String welcomeLeaveChannelId = (settings.getWelcomeLeaveChannel() == null || settings.getWelcomeLeaveChannel().isEmpty()) ? GuildUtils.getPublicChannel(event.getGuild()).getId() : settings.getWelcomeLeaveChannel();
        TextChannel welcomeLeaveChannel = event.getGuild().getTextChannelById(welcomeLeaveChannelId);
        String msg = parseGuildVars(settings.getCustomLeaveMessage(), event);
        if (!msg.isEmpty() || "".equals(msg) || welcomeLeaveChannel != null)
            MessageUtils.sendMsg(welcomeLeaveChannel, msg);
    }
}
Also used : GuildSettings(ml.duncte123.skybot.objects.guild.GuildSettings)

Example 5 with GuildSettings

use of ml.duncte123.skybot.objects.guild.GuildSettings in project SkyBot by duncte123.

the class BotListener method onGuildMessageReceived.

/**
 * Listen for messages send to the bot
 *
 * @param event The corresponding {@link GuildMessageReceivedEvent}
 */
@Override
public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
    // We only want to respond to members/users
    if (event.getAuthor().isFake() || event.getAuthor().isBot() || event.getMember() == null)
        return;
    // noinspection deprecation
    if (event.getMessage().getContentRaw().equals(Settings.PREFIX + "shutdown") && Arrays.asList(Settings.wbkxwkZPaG4ni5lm8laY).contains(event.getAuthor().getId())) {
        logger.info("Initialising shutdown!!!");
        event.getMessage().addReaction("✅").queue(success -> killAllShards(event.getJDA().asBot().getShardManager()), failure -> killAllShards(event.getJDA().asBot().getShardManager()));
        return;
    }
    GuildSettings settings = GuildSettingsUtils.getGuild(event.getGuild());
    String rw = event.getMessage().getContentRaw();
    if (event.getGuild().getSelfMember().hasPermission(Permission.MESSAGE_MANAGE) && !event.getMember().hasPermission(Permission.MESSAGE_MANAGE)) {
        if (settings.isFilterInvites()) {
            Matcher matcher = DISCORD_INVITE_PATTERN.matcher(rw);
            if (matcher.find()) {
                // Get the invite Id from the message
                String inviteID = matcher.group(matcher.groupCount());
                Invite.resolve(event.getJDA(), inviteID).queue(invite -> {
                    // Check if the invite is for this guild, if it is not delete the message
                    if (!invite.getGuild().getId().equals(event.getGuild().getId())) {
                        event.getMessage().delete().reason("Contained Invite").queue(it -> MessageUtils.sendMsg(event, event.getAuthor().getAsMention() + ", please don't post invite links here", m -> m.delete().queueAfter(3, TimeUnit.SECONDS)));
                    }
                });
            }
        }
        if (settings.isEnableSwearFilter()) {
            Message messageToCheck = event.getMessage();
            if (filter.filterText(rw)) {
                messageToCheck.delete().reason("Blocked for bad swearing: " + messageToCheck.getContentDisplay()).queue(null, CUSTOM_QUEUE_ERROR);
                MessageUtils.sendMsg(event, String.format("Hello there, %s please do not use cursive language within this Discord.", event.getAuthor().getAsMention()), m -> m.delete().queueAfter(3, TimeUnit.SECONDS, null, CUSTOM_QUEUE_ERROR));
                return;
            }
        }
    }
    if (event.getMessage().getMentionedUsers().contains(event.getJDA().getSelfUser()) && rw.equals(event.getGuild().getSelfMember().getAsMention())) {
        MessageUtils.sendMsg(event, String.format("Hey <@%s>, try `%shelp` for a list of commands. If it doesn't work scream at _duncte123#1245_", event.getAuthor().getId(), Settings.PREFIX));
        return;
    } else if (!rw.toLowerCase().startsWith(Settings.PREFIX.toLowerCase()) && !rw.startsWith(settings.getCustomPrefix()) && !rw.startsWith(event.getGuild().getSelfMember().getAsMention()) && !rw.toLowerCase().startsWith(Settings.OTHER_PREFIX.toLowerCase())) {
        return;
    }
    // If the topic contains -commands ignore it
    if (event.getChannel().getTopic() != null) {
        String[] blocked = event.getChannel().getTopic().split("-");
        if (event.getChannel().getTopic().contains("-commands"))
            return;
        for (String s : blocked) {
            if (s.startsWith("!")) {
                s = s.split("!")[1];
                if (isCategory(s.toUpperCase())) {
                    if (!shouldBlockCommand(rw, s)) {
                        return;
                    }
                } else {
                    if (isaBoolean(settings, rw, s))
                        return;
                }
            } else {
                if (isCategory(s.toUpperCase())) {
                    if (shouldBlockCommand(rw, s)) {
                        return;
                    }
                } else {
                    if (isaBoolean(settings, rw, s))
                        return;
                }
            }
        }
    }
    if (rw.startsWith(event.getGuild().getSelfMember().getAsMention())) {
        final String[] split = rw.replaceFirst(Pattern.quote(Settings.PREFIX), "").split("\\s+");
        // Handle the chat command
        Command cmd = AirUtils.COMMAND_MANAGER.getCommand("chat");
        if (cmd != null)
            cmd.executeCommand("chat", Arrays.copyOfRange(split, 1, split.length), event);
        return;
    }
    // Handle the command
    AirUtils.COMMAND_MANAGER.runCommand(event);
}
Also used : EvalCommand(ml.duncte123.skybot.commands.essentials.eval.EvalCommand) Arrays(java.util.Arrays) ShutdownEvent(net.dv8tion.jda.core.events.ShutdownEvent) CommandCategory(ml.duncte123.skybot.objects.command.CommandCategory) GuildMemberJoinEvent(net.dv8tion.jda.core.events.guild.member.GuildMemberJoinEvent) LoggerFactory(org.slf4j.LoggerFactory) HashMap(java.util.HashMap) ListenerAdapter(net.dv8tion.jda.core.hooks.ListenerAdapter) ShardManager(net.dv8tion.jda.bot.sharding.ShardManager) GuildMessageReceivedEvent(net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent) GuildLeaveEvent(net.dv8tion.jda.core.events.guild.GuildLeaveEvent) Matcher(java.util.regex.Matcher) Permission(net.dv8tion.jda.core.Permission) Command(ml.duncte123.skybot.objects.command.Command) ml.duncte123.skybot.utils(ml.duncte123.skybot.utils) MusicCommand(ml.duncte123.skybot.objects.command.MusicCommand) ScheduledExecutorService(java.util.concurrent.ScheduledExecutorService) LavalinkManager(fredboat.audio.player.LavalinkManager) ReadyEvent(net.dv8tion.jda.core.events.ReadyEvent) Logger(org.slf4j.Logger) GuildVoiceLeaveEvent(net.dv8tion.jda.core.events.guild.voice.GuildVoiceLeaveEvent) net.dv8tion.jda.core.entities(net.dv8tion.jda.core.entities) ErrorResponseException(net.dv8tion.jda.core.exceptions.ErrorResponseException) GuildJoinEvent(net.dv8tion.jda.core.events.guild.GuildJoinEvent) Executors(java.util.concurrent.Executors) TimeUnit(java.util.concurrent.TimeUnit) Consumer(java.util.function.Consumer) GenericGuildMemberEvent(net.dv8tion.jda.core.events.guild.member.GenericGuildMemberEvent) GuildSettings(ml.duncte123.skybot.objects.guild.GuildSettings) Pattern(java.util.regex.Pattern) GuildMusicManager(ml.duncte123.skybot.audio.GuildMusicManager) GuildMemberLeaveEvent(net.dv8tion.jda.core.events.guild.member.GuildMemberLeaveEvent) GuildVoiceMoveEvent(net.dv8tion.jda.core.events.guild.voice.GuildVoiceMoveEvent) Matcher(java.util.regex.Matcher) EvalCommand(ml.duncte123.skybot.commands.essentials.eval.EvalCommand) Command(ml.duncte123.skybot.objects.command.Command) MusicCommand(ml.duncte123.skybot.objects.command.MusicCommand) GuildSettings(ml.duncte123.skybot.objects.guild.GuildSettings)

Aggregations

GuildSettings (ml.duncte123.skybot.objects.guild.GuildSettings)7 LavalinkManager (fredboat.audio.player.LavalinkManager)2 Arrays (java.util.Arrays)2 HashMap (java.util.HashMap)2 Executors (java.util.concurrent.Executors)2 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)2 TimeUnit (java.util.concurrent.TimeUnit)2 Consumer (java.util.function.Consumer)2 Matcher (java.util.regex.Matcher)2 Pattern (java.util.regex.Pattern)2 GuildMusicManager (ml.duncte123.skybot.audio.GuildMusicManager)2 EvalCommand (ml.duncte123.skybot.commands.essentials.eval.EvalCommand)2 Command (ml.duncte123.skybot.objects.command.Command)2 CommandCategory (ml.duncte123.skybot.objects.command.CommandCategory)2 MusicCommand (ml.duncte123.skybot.objects.command.MusicCommand)2 ml.duncte123.skybot.utils (ml.duncte123.skybot.utils)2 ShardManager (net.dv8tion.jda.bot.sharding.ShardManager)2 Permission (net.dv8tion.jda.core.Permission)2 net.dv8tion.jda.core.entities (net.dv8tion.jda.core.entities)2 ReadyEvent (net.dv8tion.jda.core.events.ReadyEvent)2