This is already done! But then the spammers would just slow their spam bots down under or near the rate limit, and it would get very annoying seeing random max length messages appear over and over again every few seconds. You could make the rate limit even more restrictive, but then you ruin the experience for normal users. It's a tough problem
The first version that I made ~6 months ago had basically zero protection against spammers/trolls/etc, and it's been a non-stop arms race since then. I could rant for long hours about the numerous types of attacks and what I've had to do to prevent them.
I like the random code idea. But you'd have to ask more than once, otherwise spammers could go through the code once and then turn on their script. So it again becomes a tradeoff of how much to worsen the experience for normal users
This gives me an idea of building a type of web application firewall that would be used for chat related sites like this that would automatically block bots/spammers/trolls.