Why do gases need to be cooled to liquefy/solidify?

My book states:

Gases do not liquify on compression only, although molecules come close to each other and Weak forces operate at a maximum.

Why is it that we cannot just keep on compressing gas till it solidified or liquified? Why do we need to reduce its temperature? Also, if that is true, what would happen if I kept compressing a gas, without siphoning out the excess energy?

What your book states is not generally true. Two counter-examples:

1. Ammonia ($\ce{NH3}$) will liquefy at room temperature and a pressure of approximately $\pu{10bar}$. (CRC Handbook of Chemistry and Physics 44th ed; information as cited on Wikipedia’s data page).

2. Butane ($\ce{C4H10}$) will liquefy at room temperature and a pressure of just over $\pu{2bar}$. (Same source as cited on Wikipedia’s data page).

Especially the second is well-known to all those who have a butane lighter of transparent material. If it is half-full, a clear distinction between the liquid and gaseous phases can be seen inside at room temperature. Naturally, the inside of the lighter must be under positive pressure for gas to flow out if a flame is required.

On the other hand, there are a great many gases that cannot be liquefied at room temperature by applying pressure. One of these is nitrogen ($\ce{N2}$). In this case, applying enough pressure will make the sample transform directly from the gaseous to a solid phase.

The difference between nitrogen and ammonia/butane is their thermodynamic data, most importantly their critical point. The critical point defines the last position of the liquid/solid separation of a phase diagram. If the temperature is higher than the critical temperature, no liquid phase will be observed under any compression. Likewise, if the pressure is higher than the critical pressure, a substance will not liquefy even under extreme cooling (it will go straight to the solid phase).

The critical points of the compounds mentioned herein are:

$$\begin{array}{lrr}\hline \text{Compound} & \vartheta_\text{crit} [\mathrm{^\circ C}] & p_\text{crit} [bar] \\ \hline \ce{NH3} & 132.4 & 112.8\phantom{0} \\ \ce{C4H10} & 152\phantom{.0} & 37.96\\ \ce{N2} & -146.9 & 33.90\\ \hline \end{array}$$

As you can see, the critical pressures of all compounds are well above standard pressure (hence they can be liquefied under reduced temperature). Nitrogen’s critical temperature is below room temperature, so it cannot be liquefied by compression; the others can.