I want to start Screen Mirroring from my MacBook to my AppleTV with a keyboard shortcut. I used Automator's Recording function ("Watch Me Do") to record the three necessary clicks (open Control Center, click on Screen Mirroring, click on Apple TV). This is the resulting code:
-- Click the “Control Centre” menu bar item.
delay 0.608482
set timeoutSeconds to 2.0
set uiScript to "click menu bar item 2 of menu bar 1 of application process \"Control Centre\""
my doWithTimeout(uiScript, timeoutSeconds)
-- Click the “<fill in title>” button.
delay 0.84342
set timeoutSeconds to 2.0
set uiScript to "click UI Element 6 of group 1 of window \"Control Centre\" of application process \"Control Centre\""
my doWithTimeout(uiScript, timeoutSeconds)
-- Click the “<fill in title>” button.
delay 1.017773
set timeoutSeconds to 2.0
set uiScript to "click UI Element 2 of group 1 of window \"Control Centre\" of application process \"Control Centre\""
my doWithTimeout(uiScript, timeoutSeconds)
on doWithTimeout(uiScript, timeoutSeconds)
    set endDate to (current date) + timeoutSeconds
    repeat
        try
            run script "tell application \"System Events\"
" & uiScript & "
end tell"
            exit repeat
        on error errorMessage
            if ((current date) > endDate) then
                error "Can not " & uiScript
            end if
        end try
    end repeat
end doWithTimeout
Now the problem is that when I execute that script, in the second step it's not Screen Mirroring that's being clicked but Focus, the element above it. So somehow the line set uiScript to "click UI Element 6 of group 1 of window \"Control Centre\" of application process \"Control Centre\"" doesn't work as expected. I tried to replace the UI Element 6 with other numbers. Most of them result in a click on Focus, others turn off Bluetooth or AirDrop ...
How can it be that a recorded action yields a different result when played back? Any ideas? I'm on macOS Ventura btw.