The best place of the code for creating a robots.txt file

You are underestimating the complexity of robots file handling in WordPress. The presence of physical file is one of two cases.

If physical file is not present during template load is_robots() checks is performed and in positive case do_robots() runs, generating and serving the “file” on the fly.

Just going ahead and creating robots.txt in arbitrary site might very well wreck havoc with related code that is making use of virtual file and hooks in it.

Answering direct question — I am not sure which goals you are pursuing by this functionality so it is a little hard to tell what would work best for timing. The simples might be to run it on visiting theme’s options page (in same way as visiting native permalink settings performs permalink flush).

tech