You need a Web Firewall that can filter bad traffic at DNS level.
Using Sucuri, enable aggresive bot filter at Firewall settings. It can help.
If you are using Cloudflare there is a better way to handle this problem.
For example, if you want to block specific domain referer traffic. You can implement this way.
Cloudflare > Firewall
I blocked the user agent of the bad user as it showed there in firewall using block user agent in firewall menu. Will that do the trick as well?
As most spam was coming from 2 specific useragent of mozilla and python where as my usual traffic is mostly chrome and safari