The best solution would be to use the Flarum PHP extension API, that way you can directly listen to the built-in events you need.
If you want to write this as a separate script using the REST API, you will probably need the webhook extension so you can notify your script of relevant changes. Then you can use the POST /api/posts endpoint to write replies. You can inspect requests made by Flarum web interface to see what parameters the REST requests take as this is the same endpoints being used.