9

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?

pkamb
  • 33,281
  • 23
  • 160
  • 191
Bobelev
  • 878
  • 9
  • 13

2 Answers2

18

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
regulus6633
  • 18,848
  • 5
  • 41
  • 49
  • It's almost exactly what I want, but is that working when I watching video/YouTube( which shouldn't count as idle)? – Richard Fu Jun 19 '18 at 05:04
  • 1
    @RichardFu try using "pmset -g", like https://stackoverflow.com/questions/20054722/detecting-inactivity-from-applescript – Andy K Jan 06 '22 at 19:31
3

Have a look at iAway, a small App which allows you to run Apple Script when you step away from your Mac and return. I use it to set my online status of my messenger Apps and start my screen saver when away and when return to set my online status back. The app comes with other cool features to actually detect if you are physically away utilizing computer vision.

Peter
  • 31
  • 2