Kac-Moody realization of W-algebras