Search code examples
applescriptmousemoveosascriptidle-timer

How can I write an apple script that moves the mouse to a certain position after being idle?


I was searching for a way to move the mouse after some time of inactivity on a MacBook, and due to some constrains, the idle setting in the OS are not accessible, nor are some software that move the mouse.


Solution

  • After hours of trying, I managed to get a working piece of code that:

    • shall be executed using osascript
    • needs cliclick to be installed (can be installed using brew)
    set initialPosition to {10, 300}
    set moveDistance to 10
    set idleThreshold to 60 -- Idle threshold in seconds
    
    set previousPosition to missing value
    set idleTime to 0
    
    -- Function to get the current mouse position using cliclick
    on getMousePosition()
        set mousePosition to {}
        try
            set mousePosition to (do shell script "/usr/local/bin/cliclick p")
            set {mouseX, mouseY} to text items of mousePosition
            return {mouseX as integer, mouseY as integer}
        on error errMsg
            return missing value
        end try
    end getMousePosition
    
    repeat
        set currentMousePosition to getMousePosition()
        
        if currentMousePosition is not equal to previousPosition then
            set idleTime to 0
            set previousPosition to currentMousePosition
        else
            set idleTime to idleTime + 5 -- Increment idle time by the delay value
        end if
        
        if idleTime > idleThreshold then
            set currentX to item 1 of initialPosition
            set currentY to item 2 of initialPosition
            
            -- Move mouse up by 10 pixels
            do shell script "/usr/local/bin/cliclick m:" & currentX & "," & (currentY + moveDistance)
            delay 1 -- Adjust delay as needed
            
            -- Move mouse down by 10 pixels
            do shell script "/usr/local/bin/cliclick m:" & currentX & "," & (currentY - moveDistance)
            delay 1 -- Adjust delay as needed
            
            -- Reset idle time
            set idleTime to 0
        end if
        
        delay 5 -- Check mouse position every 5 seconds
    end repeat