Happiness evolved to reinforce behaviors contributing to successful reproduction. A more obvious example would be orgasms. I'm not about to go all evo-psych and go backwards from the effect to postulate the cause.
Let's let our hypothetical AI programmers be evolution. First, let's assume that the AI's behaviors should attempt to protect its existence. That's its "goal", in the same sense that reproduction is the "goal" of life. Its goal is to survive. How do we do this? Sensations reinforcing useful behaviors and reducing non-useful behaviors is a start. But for that, the AI needs a sense of "this feels good" and "this feels bad". That's simple enough. Adding a pain analogue when it does something liable to endanger it would make sense. And on the other end of the spectrum, adding a positive reinforcement for useful behaviors follows. Expanding, obtaining more processing power, "eating", so to speak. To humans, eating feels good. sleeping feels good. hell, taking a shit is satisfying. All things we need to do to survive. It's simple drives like that. It doesn't matter what the specific behaviors are, but reinforcing behaviors leading to an arbitrary goal like 'self preservation' give rise to what can be perceived as emotion.
Somehow, enjoying the company of others makes me more able to reproduce. Perhaps it's because of humans' status as social animals. Cooperation leads to good for the whole. Accomplishment? nonsexual beauty? knowledge? Concepts like that are the sort of complex things that the basic drives we have combine to create. Emergent properties. It's concepts like those that make intelligence amazing.