How to prevent bot or someone to modify any file automatically?

I’m not a security expert, but the code you include in your question roughly does this:

  1. Check if the request is not for a static page (it can’t insert anything in that)
  2. Check if the request is not from scraper bots Ahrefsbot and MJ12bot.
  3. If both checks are passed make a connection with the server at wpadminadmi.com (this happens on the line that starts with $ch = curl_init)
  4. Retrieve some code from that site.
  5. Include that code ($data) in your site.

So, your site has been hacked and you are probably distributing malware from your site to the devices of your visitors.

Your question does not include any hints as where the malware might be hiding in your own site. What you see is not the malware itself, but another piece of malware it generates.

The root problem may be anywhere, ranging from a compromised ftp-account to a malicious plugin/theme. Your best option is to wipe the site and install a backup. If you don’t have any, you’ll have to go through the motions.