ParseCommand() public static method

public static ParseCommand ( string input, CommandMap map, IEnumerable &commands, int &endPos ) : bool
input string
map CommandMap
commands IEnumerable
endPos int
return bool
Ejemplo n.º 1
0
        public void Install(DiscordSocketClient client)
        {
            Client = client;
            Config.Lock();

            if (Config.HelpMode != HelpMode.Disabled)
            {
                CreateCommand("help")
                .Parameter("command", ParameterType.Multiple)
                .Hide()
                .Description("Returns information about commands.")
                .Do(async e =>
                {
                    var replyChannel = Config.HelpMode == HelpMode.Public ? e.Channel : await e.User.GetOrCreateDMChannelAsync().ConfigureAwait(false);
                    if (e.Args.Length > 0)     //Show command help
                    {
                        var map = _map.GetItem(string.Join(" ", e.Args));
                        if (map != null)
                        {
                            await ShowCommandHelp(map, e.User, e.Channel, replyChannel).ConfigureAwait(false);
                        }
                        else
                        {
                            await replyChannel.SendMessageAsync("Unable to display help: Unknown command.").ConfigureAwait(false);
                        }
                    }
                    else     //Show general help
                    {
                        await ShowGeneralHelp(e.User, e.Channel, replyChannel).ConfigureAwait(false);
                    }
                });
            }

            client.MessageReceived += async e =>
            {
                if (_allCommands.Count == 0)
                {
                    return;
                }
                if (e.Author == null || e.Author.Id == Client.CurrentUser.Id)
                {
                    return;
                }

                string msg = e.Content;
                if (msg.Length == 0)
                {
                    return;
                }

                // Check ignored before doing work
                if (_getIgnoredChannelFlag != null ? _getIgnoredChannelFlag(e.Channel, e.Author) : false)
                {
                    return;
                }

                var self = client.CurrentUser;
                //Check for command char if one is provided
                var  chars      = Config.CommandChars;
                bool mentionreq = Config.MentionCommandChar >= 1;
                bool priv       = e.Channel is IPrivateChannel;
                if (chars.Any() || mentionreq)
                {
                    bool hasCommandChar = chars.Contains(msg[0]);
                    if (!hasCommandChar && (priv ? Config.RequireCommandCharInPrivate : Config.RequireCommandCharInPublic))
                    {
                        var tag = e.Tags.FirstOrDefault(t => t.Type == TagType.UserMention && t.Key == self.Id);
                        if (mentionreq && tag != null)
                        {
                            string neko = !priv && !string.IsNullOrEmpty((await(e.Channel as IGuildChannel).Guild.GetUserAsync(self.Id)).Nickname) ? $"<@!{self.Id}>" : $"<@{self.Id}>";
                            if (neko.Length + 2 > msg.Length)
                            {
                                NonCommands(e);
                                return;
                            }
                            if (tag.Index == 0)
                            {
                                msg = msg.Substring(neko.Length + 1);
                            }
                            else
                            {
                                int index = Config.MentionCommandChar > 1 ? msg.LastIndexOf(neko) : -1;
                                if (index == -1)
                                {
                                    NonCommands(e);
                                    return;
                                }
                                msg = msg.Substring(0, index - 1);
                            }
                            // Ideally, don't let the command know that we were mentioned, if this is the only mention

                            /*if (msg.IndexOf(neko) != -1)
                             * {
                             *  e.Message.MentionedUsers = e.Message.MentionedUsers.Where(u => u == e.Server.CurrentUser);
                             *  e.Message.IsMentioningMe = false;
                             * }*/
                        }
                        else
                        {
                            NonCommands(e);
                            return;
                        }
                    }
                    else if (hasCommandChar)
                    {
                        msg = msg.Substring(1);
                    }
                }

                //Parse command
                CommandParser.ParseCommand(msg, _map, out var commands, out int argPos);
                if (commands == null)
                {
                    CommandEventArgs errorArgs = new CommandEventArgs(e, null, null);
                    await OnCommandError(CommandErrorType.UnknownCommand, errorArgs);

                    NonCommands(e);
                    return;
                }
                else
                {
                    foreach (var command in commands)
                    {
                        //Parse arguments
                        var error = CommandParser.ParseArgs(msg, argPos, command, out var args);
                        if (error != null)
                        {
                            if (error == CommandErrorType.BadArgCount)
                            {
                                continue;
                            }
                            else
                            {
                                var errorArgs = new CommandEventArgs(e, command, null);
                                await OnCommandError(error.Value, errorArgs);

                                return;
                            }
                        }

                        var eventArgs = new CommandEventArgs(e, command, args);

                        // Check permissions
                        if (!command.CanRun(eventArgs.User, eventArgs.Channel, out var errorText))
                        {
                            await OnCommandError(CommandErrorType.BadPermissions, eventArgs, errorText != null?new Exception(errorText) : null);

                            return;
                        }
                        // Check flags
                        if (!priv && command.NsfwFlag && !(_getNsfwFlag != null ? _getNsfwFlag(e.Channel) : false))
                        {
                            await OnCommandError(CommandErrorType.BadPermissions, eventArgs, new NsfwFlagException());

                            return;
                        }
                        if (priv && command.MusicFlag && !(_getMusicFlag != null ? _getMusicFlag(e.Author as IVoiceState) : false))
                        {
                            await OnCommandError(CommandErrorType.BadPermissions, eventArgs, new MusicFlagException());

                            return;
                        }

                        // Run the command
                        try
                        {
                            OnCommand(eventArgs);
                            await command.Run(eventArgs).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            await OnCommandError(CommandErrorType.Exception, eventArgs, ex);
                        }
                        return;
                    }
                    var errorArgs2 = new CommandEventArgs(e, null, null);
                    await OnCommandError(CommandErrorType.BadArgCount, errorArgs2);
                }
            };
        }
Ejemplo n.º 2
0
        void IService.Install(DiscordClient client)
        {
            Client = client;
            Config.Lock();

            if (Config.HelpMode != HelpMode.Disabled)
            {
                CreateCommand("help")
                .Parameter("command", ParameterType.Multiple)
                .Hide()
                .Description("Returns information about commands.")
                .Do(async e =>
                {
                    Channel replyChannel = Config.HelpMode == HelpMode.Public ? e.Channel : await e.User.CreatePMChannel().ConfigureAwait(false);
                    if (e.Args.Length > 0)     //Show command help
                    {
                        var map = _map.GetItem(string.Join(" ", e.Args));
                        if (map != null)
                        {
                            await ShowCommandHelp(map, e.User, e.Channel, replyChannel).ConfigureAwait(false);
                        }
                        else
                        {
                            await replyChannel.SendMessage("Unable to display help: Unknown command.").ConfigureAwait(false);
                        }
                    }
                    else     //Show general help
                    {
                        await ShowGeneralHelp(e.User, e.Channel, replyChannel).ConfigureAwait(false);
                    }
                });
            }

            client.MessageReceived += async(s, e) =>
            {
                if (_allCommands.Count == 0)
                {
                    return;
                }
                if (e.Message.User == null || e.Message.User.Id == Client.CurrentUser.Id)
                {
                    return;
                }

                string msg = e.Message.RawText;
                if (msg.Length == 0)
                {
                    return;
                }

                // Check ignored before doing work
                if (_getIgnoredChannelFlag != null ? _getIgnoredChannelFlag(e.Message.Channel, e.User) : false)
                {
                    return;
                }

                //Check for command char if one is provided
                var  chars      = Config.CommandChars;
                bool mentionreq = Config.MentionCommandChar >= 1;
                if (chars.Any() || mentionreq)
                {
                    bool hasCommandChar = chars.Contains(msg[0]);
                    if (!hasCommandChar && (e.Message.Channel.IsPrivate ? Config.RequireCommandCharInPrivate : Config.RequireCommandCharInPublic))
                    {
                        if (mentionreq && e.Message.IsMentioningMe())
                        {
                            string neko = !string.IsNullOrEmpty(e.Server.CurrentUser.Nickname) ? client.CurrentUser.NicknameMention : client.CurrentUser.Mention;
                            if (neko.Length + 2 > msg.Length)
                            {
                                NonCommands(e);
                                return;
                            }
                            if (msg.StartsWith(neko))
                            {
                                msg = msg.Substring(neko.Length + 1);
                            }
                            else
                            {
                                int index = Config.MentionCommandChar > 1 ? msg.LastIndexOf(neko) : -1;
                                if (index == -1)
                                {
                                    NonCommands(e);
                                    return;
                                }
                                msg = msg.Substring(0, index - 1);
                            }
                            // Ideally, don't let the command know that we were mentioned, if this is the only mention

                            /*if (msg.IndexOf(neko) != -1)
                             * {
                             *  e.Message.MentionedUsers = e.Message.MentionedUsers.Where(u => u == e.Server.CurrentUser);
                             *  e.Message.IsMentioningMe = false;
                             * }*/
                        }
                        else
                        {
                            NonCommands(e);
                            return;
                        }
                    }
                    else if (hasCommandChar)
                    {
                        msg = msg.Substring(1);
                    }
                }

                //Parse command
                IEnumerable <Command> commands;
                int argPos;
                CommandParser.ParseCommand(msg, _map, out commands, out argPos);
                if (commands == null)
                {
                    CommandEventArgs errorArgs = new CommandEventArgs(e.Message, null, null);
                    OnCommandError(CommandErrorType.UnknownCommand, errorArgs);
                    NonCommands(e);
                    return;
                }
                else
                {
                    foreach (var command in commands)
                    {
                        //Parse arguments
                        string[] args;
                        var      error = CommandParser.ParseArgs(msg, argPos, command, out args);
                        if (error != null)
                        {
                            if (error == CommandErrorType.BadArgCount)
                            {
                                continue;
                            }
                            else
                            {
                                var errorArgs = new CommandEventArgs(e.Message, command, null);
                                OnCommandError(error.Value, errorArgs);
                                return;
                            }
                        }

                        var eventArgs = new CommandEventArgs(e.Message, command, args);

                        // Check permissions
                        string errorText;
                        if (!command.CanRun(eventArgs.User, eventArgs.Channel, out errorText))
                        {
                            OnCommandError(CommandErrorType.BadPermissions, eventArgs, errorText != null ? new Exception(errorText) : null);
                            return;
                        }
                        // Check flags
                        bool nsfwAllowed = _getNsfwFlag != null?_getNsfwFlag(e.Message.Channel) : false;

                        if (!nsfwAllowed && !e.Channel.IsPrivate && command.NsfwFlag)
                        {
                            OnCommandError(CommandErrorType.BadPermissions, eventArgs, new NsfwFlagException());
                            return;
                        }
                        bool isInMusicChannel = _getMusicFlag != null?_getMusicFlag(e.Message.User) : false;

                        if (command.MusicFlag && !isInMusicChannel)
                        {
                            OnCommandError(CommandErrorType.BadPermissions, eventArgs, new MusicFlagException());
                            return;
                        }

                        // Run the command
                        try
                        {
                            OnCommand(eventArgs);
                            await command.Run(eventArgs).ConfigureAwait(false);
                        }
                        catch (Exception ex)
                        {
                            OnCommandError(CommandErrorType.Exception, eventArgs, ex);
                        }
                        return;
                    }
                    var errorArgs2 = new CommandEventArgs(e.Message, null, null);
                    OnCommandError(CommandErrorType.BadArgCount, errorArgs2);
                }
            };
        }