Search code examples
applescriptautomator

Working AppleScript fails when put into Workflow


As a foreword, I am very new to AppleScript.

I have a very simple, working AppleScript that always fails when run as part of a Workflow/Application in Automator. I know that the script works because I can run it within Script Editor multiple times and have no errors.

Here is the script:

activate application "Chess"

tell application "System Events" to tell process "Chess"
    click menu item "Preferences…" of menu "Chess" of menu bar item "Chess" of menu bar 1

    tell window 1
            repeat until sheet 1 exists
                delay 0.1
            end repeat
    end tell

    tell group "Speech" of sheet 1 of window 1
        set checkboxOne to checkbox "Allow Player to Speak Moves"
        set checkboxTwo to checkbox "Speak Computer Moves"
        set checkboxThree to checkbox "Speak Human Moves"

        tell checkboxOne
            set checkBoxStatus to value of checkboxOne as boolean
            if checkBoxStatus is true then click checkboxOne
        end tell
        tell checkboxTwo
            set checkBoxStatus to value of checkboxTwo as boolean
            if checkBoxStatus is true then click checkboxTwo
        end tell
        tell checkboxThree
            set checkBoxStatus to value of checkboxThree as boolean
            if checkBoxStatus is true then click checkboxThree
        end tell
    end tell

    click button "OK" of sheet 1 of window 1
end tell

Again, when run by itself, no errors. When run in Automator as part of a Workflow/Application, I get the error:

System Events got an error: Can’t get sheet 1 of window 1 of process "Chess". Invalid index.

with the highlighted line being

click button "OK" of sheet 1 of window 1

Is there something I'm missing? Why is this error occurring and how can I fix it?

Thanks in advance for any help!


Solution

  • Try wrapping that part of the code in its own tell statement with a delay. Like this:

    tell application "System Events"
        delay .2
        click button "OK" of sheet 1 of window 1
    end tell