There are two key parts to your AppleScript, pressing a key and performing a task after inactivity.
Pressing a key
Automating a key press in AppleScript is well covered; the accepted answer to the linked question suggests:
tell application "System Events" to key code 36
Performing when inactive
The second part, performing a task when your Mac has been idle is more tricky. You can use third party software to schedule your AppleScript after inactivity, or you can use a scripted approach to extract the idle time information from the system:
ioreg -c IOHIDSystem | perl -ane 'if(/Idle/) {$idle=(pop @F)/1000000000; print $idle, "\n"; last;}'
Wrapping this up in AppleScript becomes:
set inactive_seconds to do shell script "ioreg -c IOHIDSystem | perl -ane 'if(/Idle/) {$idle=(pop @F)/1000000000; print $idle, \"
\"; last;}'"
Where inactive_seconds
contains the number of inactive seconds.
Putting it together
Putting it together depends on your looping approach. Consider a while loop that checks if the Terminal.app is running. John Gruber's article will be helpful for this, How to Determine if a Certain App Is Running Using AppleScript and Perl:
tell application "System Events"
count (every process whose name is "Terminal")
end tell
The greater while loop could be:
tell application "System Events"
repeat while ((count (every process whose name is "Terminal")) > 0)
-- check idle time and conditionally perform key press
-- wait n minutes to avoid excessive polling
end repeat
end tell