I doubt that making friends with other faculty is an important consideration. Some people like to get such duties out of the way to permit the rest of the day to be open to other activities. It can actually be disruptive to other activities to have to teach a course at what seems like a more popular time. We are well-known to be absent minded of course.
The department head/chair is responsible to assure that all required slots are filled. They will, in rational cases, ask for preferences and try to fulfill them when possible. (For purposes of a novel, though, a vindictive head might do ... whatever.) But they might have to go outside preferences in some cases. They might (probably do) have the power to bribe faculty in some simple way to get them to fill a slot they don't prefer, perhaps with promises for the future.
Another option you might see is for unpopular time slots to be filled by new faculty. Or even by old and about to retire faculty who are no longer especially active in research.
Sometimes the "sections" may not be what you think. A "section" of 30 or so might be assigned to a teaching assistant, but the actual lectures are given to 300 (or more) in a vast lecture hall. The professor does most of the lecturing and the TAs do the individual contact that students need.
Note that I say "most" of the lecturing, as a TA might get the chance to do a lecture as part of their training. The professor might be present to give them feedback.
At an R1 that I was once associated with, the professors were required to lecture to two groups, usually three times a week each. A "group" might be a section of 30 (or fewer) or a huge lecture of 300 or so. The large lectures were, as you guess, early courses in the curriculum and the small groups more likely to be advanced courses.
The large groups might be largely general education students who need a few courses in a particular field, but outside their main focus (major). The small groups more likely to be majors only.
And, advanced TAs might be given the opportunity to actually teach a small section of some elementary course after they have had some experience and are trusted to do so. And, that opportunity might be associated with an unpopular time slot, assuming such exist.