MacBook – Dim screen brightness of MBP, using AppleScript (and while using a secondary monitor)

applescriptdisplaymacbook proscreen

I just got a secondary monitor to use with my MacBook Pro (13" Retina Early-2015). I previously had AppleScripts for dimming and for increasing the brightness of the MBP screen—either to no bars or to about 75%—but now they aren't working for some reason (w/ or w/o the external monitor plugged in). I also tried using Shades but both screens keep flashing every 2-3 seconds (I'd rather use an AppleScript as well).

Basically, my external monitor is my main screen and I want to be able to dim my MBP screen using an AppleScript to either no bars or about 75% (of which the scripts will then be redirected to keyboard shortcuts with an application).

What AppleScript code would be needed to do this?

EDIT:
Here is the old that worked really well before, but for some reason stopped (with out without an external monitor plugged in).

tell application "System Events"
    repeat 16 times
        key code 107
    end repeat
end tell

and

tell application "System Events"
    repeat 11 times
        key code 113
    end repeat
end tell

Best Answer

Having a secondary monitor was not the issue, it was that I also needed an external keyboard.

When using an external keyboard, the brightness key codes change from 107 and 113 to 145 and 144 respectively, to lower/raise the brightness level.

For anyone interested, the correct key code events that works with an external keyboard (tested/works with an external Apple keyboard) are:

To lower the brightness all the way use:

tell application "System Events"
    repeat 16 times
        key code 145
    end repeat
end tell

The above code will lower the brightness all the way, regardless of where it's currently set. If it's already set at anything below 100%, any extra lower key code events, while still executed, are done so harmlessly and are just ignored when the above code runs.

To raise the brightness to, e.g. 75%, use:

tell application "System Events"
    repeat 12 times
        key code 144
    end repeat
end tell

Note that if you want a smother transition, add a delay 0.02 command to each repeat loop, otherwise the transition can appear quite abrupt.