I want to start a script when user goes away or returns back to computer. Is there any built-in method in AppleScript to check user's state? If not what else can I use in OS X?
Which macOS version is installed? From the Apple menu in the corner of your screen, choose About This Mac. You should see the macOS name, such as macOS Monterey or macOS Big Sur, followed by its version number. If you need to know the build number as well, click the version number to see it.
Adjust the Automatic Log Out Settings Step 1: Open "System Preferences" on your Mac and then click on "Security and Privacy". Step 2: Click on the "Advanced" tab at the bottom and from the two options presented select "Log out after (n) minutes of inactivity".
Here's a command that might work for you. This will tell you how long it's been since the mouse moved or a keystroke was pressed.
set idleTime to do shell script "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'"
So you might assume that if no key was pressed or the mouse was moved for a period of time then the user is not using the computer. With some clever tracking of the idleTime you can tell when the user left the computer and also when he returned. Something like this.
Save this as an applescript application and check the "stay open after run handler" checkbox. You can quit it any time by right-clicking on the dock icon and choosing quit.
global timeBeforeComputerIsNotInUse, computerIsInUse, previousIdleTime
on run
set timeBeforeComputerIsNotInUse to 300 -- 5 minutes
set computerIsInUse to true
set previousIdleTime to 0
end run
on idle
set idleTime to (do shell script "ioreg -c IOHIDSystem | awk '/HIDIdleTime/ {print $NF/1000000000; exit}'") as number
if not computerIsInUse then
if idleTime is less than previousIdleTime then
set computerIsInUse to true
say "User is using the computer again."
end if
else if idleTime is greater than or equal to timeBeforeComputerIsNotInUse then
set computerIsInUse to false
say "User has left the computer."
end if
set previousIdleTime to idleTime
return 1
end idle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With