Пример #1
0
 public CommandContext(CommandHandler handler, Command cmd, SentCommand scmd)
 {
     this.Handler = handler;
     this.Command = cmd;
     this.Request = scmd.AssociatedRequest;
     this.Token   = scmd.Token;
 }
        public async Task <CommandResult> TryRunCommandAsync(SentCommand scmd)
        {
            if (!this.Commands.ContainsKey(scmd.Name))
            {
                return(new CommandResult(false, "Unknown command."));
            }

            Command cmd        = this.Commands[scmd.Name];
            bool    authorized = AuthService.IsAuthorized(scmd.Token);

            if (cmd.NeedsLogin && !authorized)
            {
                return(new CommandResult(false, "You are not logged in. Login using the \"login\" command."));
            }

            // Refresh the token to last longer
            if (authorized)
            {
                AuthService.RefreshToken(scmd.Token);
            }

            CommandContext ctx        = new CommandContext(this, cmd, scmd);
            List <string>  parameters = scmd.Parameters.ToList();

            // If first parameter is empty string remove it
            if (parameters.Count == 1 && string.IsNullOrWhiteSpace(parameters[0]))
            {
                parameters.RemoveAt(0);
            }

            if (parameters.Count > cmd.ArgumentCount)
            {
                return(new CommandResult(false, $"Too many arguments\n{ctx.BadUsage}"));
            }
            else if (parameters.Count < cmd.ArgumentCount)
            {
                return(new CommandResult(false, $"Too few arguments\n{ctx.BadUsage}"));
            }

            CommandResult result = await cmd.RunAsync(ctx, parameters.ToArray());

            result.Result = result.Result ?? string.Empty;

            return(result);
        }