As I continue to explore ChatGPT’s AppleScript code generation capabilities, I fed it a password generation script I came up with years ago and asked it to make it better.

The results were impressive.

My original script didn’t have error-checking or user bailout points. ChatGPT was smart enough to add them for me, along with some other smart “decisions” when it came to copying out the generated password. I did have to make a few edits for correctness.

This is the result, which I’ve opted to start using instead of my old script:

property allowedCharacters : {33, 35, 36, 37, 38, 42, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 61, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122}
property givenPasswordLength : 21

repeat while true
    try
        set givenPasswordLength to text returned of (display dialog "Enter desired password length:" with title "Password Generator" default answer givenPasswordLength)
        set givenPasswordLength to givenPasswordLength as integer
        if givenPasswordLength is not greater than 0 then error "Please enter a valid positive integer."
        exit repeat
    on error errMsg
        display alert "Error" message errMsg as warning
        return -- added to ensure proper script exit
    end try
end repeat

repeat while true
    try
        set generatedPassword to generatePassword()
        set dialogResult to (display dialog "New generated password:" & return & return & generatedPassword with title "Password Generator" buttons {"Refresh", "Copy", "Cancel"} default button "Refresh" cancel button "Cancel")
        if button returned of dialogResult is "Copy" then
            set the clipboard to generatedPassword as string
            exit repeat
        else if button returned of dialogResult is "Cancel" then
            exit repeat
        end if
    on error errMsg
        display alert "Error" message errMsg as warning
        return -- added to ensure proper script exit
    end try
end repeat

on generatePassword()
    set generatedPassword to ""
    repeat givenPasswordLength times
        set randomCharacterPosition to random number from 1 to count allowedCharacters
        set generatedPassword to generatedPassword & (ASCII character item randomCharacterPosition of allowedCharacters)
    end repeat
    return generatedPassword
end generatePassword

As always, this improved script works great with FastScripts.