The reason that Hashem's perfection necessitates His only doing good is, because logic dictates that to do something there needs to be a reason, meaning, an objective that is met that would not be met without the act.
Therefore, doing good contains such a benefit - for the recipient of the good. But doing bad has no benefit for the recipient of the bad. People only do bad because they themselves benefit from it. And since Hashem does not benefit from anything, He cannot do bad. But there is a benefit to the recipients of the good if He does good.
As far as pain, we need pain as a deterrent. Since in order to fulfill Hashem's plan of bestowing good, we need people to choose to do good via free will, therefore, pain is a benefit, because if there would be no pain (punishment) for doing bad, there would be many more people doing bad. And the alternative to pain, i.e. forcing people not to do bad, would not meet the requirements for Hashem's plan, i.e. freee will. (See the Bechirah forum for details on why we need free will.)