Open Messenger and click Tools then Options, then Privacy.
Open Privacy and at the very top you'll see, "Allow List", put a check mark in the square that reads, "only people on my Allow list can read and send me messages".
You can click "View Now", if you'd like to see your Contact list. This can help you determine who contacts you and who doesn't.
At the bottom of the page, click Apply, then OK. Now immediately restart your computer and when it reopens there won't be any problems with people not on your Contact list getting in touch. You can always go in and modify things as you see fit, too.
Conversely, you can also do this: Ignore Anyone not on my Yahoo Contacts" option. This setting keeps ALL that crap from hitting your inbox and you never have to deal with it at all.
Messenger>> Privacy>> Ignore List>> fill in the box next to Ignore Anyone not on my Yahoo Contacts.
Click Apply, then OK and immediately restart your computer and those spammers will have to find somewhere else to go.