Search in sources :

Example 1 with Command

use of ml.duncte123.skybot.objects.command.Command 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 2 with Command

use of ml.duncte123.skybot.objects.command.Command in project SkyBot by duncte123.

the class GenerateCommandList method inPHP.

public static void inPHP() throws Exception {
    File phpFile = new File("commandList.php");
    if (!phpFile.exists()) {
        phpFile.createNewFile();
        Thread.sleep(500);
    } else {
        phpFile.delete();
        phpFile.createNewFile();
        Thread.sleep(500);
    }
    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(phpFile), "UTF-8"));
    writer.write("<?php");
    writer.newLine();
    writer.append("$commands = [");
    writer.newLine();
    List<String> names = new ArrayList<>();
    AirUtils.COMMAND_MANAGER.getCommands().forEach(c -> names.add(c.getName()));
    Collections.sort(names);
    for (String n : names) {
        Command cmd = AirUtils.COMMAND_MANAGER.getCommand(n);
        if (!cmd.getCategory().equals(CommandCategory.UNLISTED)) {
            writer.append("\t").append('"').append(cmd.getName()).append('"').append(" => ").append('"').append(cmd.help().replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll("`(.*)`", "<code>$1</code>").replaceAll("\\n", "<br />").replaceAll("\\*\\*(.*)\\*\\*", "<strong>$1</strong>"));
            if (cmd.getAliases().length > 0) {
                writer.append("<br />").append("Aliases: ").append(Settings.PREFIX).append(StringUtils.join(cmd.getAliases(), ", " + Settings.PREFIX));
            }
            writer.append("\",");
            writer.newLine();
        }
    }
    writer.newLine();
    writer.append("];");
    writer.close();
}
Also used : Command(ml.duncte123.skybot.objects.command.Command) FileOutputStream(java.io.FileOutputStream) ArrayList(java.util.ArrayList) OutputStreamWriter(java.io.OutputStreamWriter) File(java.io.File) BufferedWriter(java.io.BufferedWriter)

Example 3 with Command

use of ml.duncte123.skybot.objects.command.Command in project SkyBot by duncte123.

the class CommandManager method runCommand.

/**
 * This will run the command when we need them
 *
 * @param event the event for the message
 */
public void runCommand(GuildMessageReceivedEvent event) {
    final String[] split = event.getMessage().getContentRaw().replaceFirst("(?i)" + Pattern.quote(Settings.PREFIX) + "|" + Pattern.quote(Settings.OTHER_PREFIX) + "|" + Pattern.quote(GuildSettingsUtils.getGuild(event.getGuild()).getCustomPrefix()), "").split("\\s+");
    final String invoke = split[0].toLowerCase();
    Command cmd = getCommand(invoke);
    if (cmd != null) {
        try {
            cmd.executeCommand(invoke, Arrays.copyOfRange(split, 1, split.length), event);
        } catch (Throwable ex) {
            ComparatingUtils.execCheck(ex);
        }
    }
}
Also used : Command(ml.duncte123.skybot.objects.command.Command)

Example 4 with Command

use of ml.duncte123.skybot.objects.command.Command 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)

Example 5 with Command

use of ml.duncte123.skybot.objects.command.Command in project SkyBot by duncte123.

the class AnnounceCommand method executeCommand.

@Override
public void executeCommand(String invoke, String[] args, GuildMessageReceivedEvent event) {
    Permission[] perms = { Permission.ADMINISTRATOR };
    if (!event.getMember().hasPermission(perms)) {
        MessageUtils.sendMsg(event, "I'm sorry but you don't have permission to run this command.");
        return;
    }
    if (event.getMessage().getMentionedChannels().size() < 1) {
        MessageUtils.sendMsg(event, "Correct usage is `" + PREFIX + getName() + " [#Channel] [Message]`");
        return;
    }
    try {
        TextChannel targetChannel = event.getMessage().getMentionedChannels().get(0);
        if (!targetChannel.getGuild().getSelfMember().hasPermission(targetChannel, Permission.MESSAGE_WRITE, Permission.MESSAGE_READ)) {
            MessageUtils.sendMsg(event, "I can not talk in " + targetChannel.getAsMention());
            MessageUtils.sendError(event.getMessage());
            return;
        }
        String msg = event.getMessage().getContentRaw().split("\\s+", 3)[2];
        @SinceSkybot(version = "3.52.3") EmbedBuilder embed = EmbedUtils.defaultEmbed().setDescription(msg).setFooter(null, "");
        if (!event.getMessage().getAttachments().isEmpty()) {
            event.getMessage().getAttachments().stream().filter(Message.Attachment::isImage).findFirst().ifPresent(attachment -> {
                if (invoke.endsWith("2"))
                    embed.setThumbnail(attachment.getUrl());
                else
                    embed.setImage(attachment.getUrl());
            });
        }
        MessageUtils.sendEmbed(targetChannel, embed.build());
        MessageUtils.sendSuccess(event.getMessage());
    } catch (ArrayIndexOutOfBoundsException ex) {
        MessageUtils.sendErrorWithMessage(event.getMessage(), "Please! You either forgot the text or to mention the channel!");
        ComparatingUtils.execCheck(ex);
    } catch (Exception e) {
        MessageUtils.sendMsg(event, "WHOOPS: " + e.getMessage());
        e.printStackTrace();
    }
}
Also used : TextChannel(net.dv8tion.jda.core.entities.TextChannel) EmbedBuilder(net.dv8tion.jda.core.EmbedBuilder) SinceSkybot(ml.duncte123.skybot.SinceSkybot) Permission(net.dv8tion.jda.core.Permission)

Aggregations

Command (ml.duncte123.skybot.objects.command.Command)4 Pattern (java.util.regex.Pattern)2 EvalCommand (ml.duncte123.skybot.commands.essentials.eval.EvalCommand)2 GuildSettings (ml.duncte123.skybot.objects.guild.GuildSettings)2 Permission (net.dv8tion.jda.core.Permission)2 TextChannel (net.dv8tion.jda.core.entities.TextChannel)2 GuildMessageReceivedEvent (net.dv8tion.jda.core.events.message.guild.GuildMessageReceivedEvent)2 Test (org.junit.Test)2 LavalinkManager (fredboat.audio.player.LavalinkManager)1 BufferedWriter (java.io.BufferedWriter)1 File (java.io.File)1 FileOutputStream (java.io.FileOutputStream)1 OutputStreamWriter (java.io.OutputStreamWriter)1 ArrayList (java.util.ArrayList)1 Arrays (java.util.Arrays)1 HashMap (java.util.HashMap)1 Executors (java.util.concurrent.Executors)1 ScheduledExecutorService (java.util.concurrent.ScheduledExecutorService)1 TimeUnit (java.util.concurrent.TimeUnit)1 Consumer (java.util.function.Consumer)1