Fix AppleScript Stopped Working on macOS Monterey

applescriptmontereysystem-settings

An AppleScript I use to auto adjust the brightness for iMacs stopped working when migrated to 10.12 Monterey. Any suggestions for a fix?
Here is the original script:

tell application "System Preferences"
    if it is running then
        quit
    end if
end tell
delay 10.0
activate application "System Preferences"
tell application "System Events"
    tell process "System Preferences"
        click button "Displays" of scroll area 1 of window "System Preferences"
        delay 1
        click radio button "Display" of tab group 1 of window "Built-in Retina Display"
        set value of value indicator 1 of slider 1 of tab group 1 of window "Built-in Retina Display" to 0.57
    end tell
    quit application "System Preferences"
end tell

Right off the bat you can see the windows look different from the operating systems. I tried loosing "tab group 1" because I don't see tabs anymore. Also, I changed the name of the window from "Built-in Retina Display" to "Displays".enter image description here

enter image description here

I ended up using "UI Browser" to determine the path to element. However, I still can't get the brightness to adjust. As proof it is navigating properly in that window, I have included a line to click on the radio button "Scaled".

activate application "System Preferences"
tell application "System Events"
    tell process "System Preferences"
        click button "Displays" of scroll area 1 of window "System Preferences"
        delay 2
        # click radio button 2 of radio group 1 of group 1 of window 1
        set value of value indicator 1 of slider 1 of group 1 of window 1 to 0.25
    end tell
end tell

UI Browser

Best Answer

activate application "System Preferences"
tell application "System Events"
    tell process "System Preferences"
        click button "Displays" of scroll area 1 of window "System Preferences"
        delay 2
        set value of value indicator 1 of slider 1 of group 1 of window 1 to 0.25
    end tell
end tell

I went to test this code (after also finding the aforementioned lines from a past OS). And I swear I was crazy because it started working after I had switched group 1 and slider 1 (then compiled and tested with error) and then I switched it back to the original and it started to work.

Luckily I screen recorded this behavior, note I kept forgetting to quit System Preferences but that is a different error.

https://youtu.be/NGVU0vpEGsU