If you want to lose the ugliness of GUI scripting, you have a few options:
FunctionFlip (http://kevingessner.com/software/functionflip/) will do what you want, but it is limited to F1-F12, and frequently only on Apple OEM keyboards; it's hit or miss on third party boards. I have it triggered with KM by double-tapping the FN key. Works great.
FNable (https://fnable.com) customizable and app-based switching
Palua (temporarily discontinued); if you can get your hands on an older copy, it was also very slick and fully customizable.
Fluor (https://github.com/Pyroh/Fluor); also very customizable.
FNToggle (https://github.com/nelsonjchen/fntoggle) one-trick pony that you can call from command line or script, KM, etc...
FWIW, you can get the current state with
defaults read "Apple Global Domain" "com.apple.keyboard.fnState"
you can toggle the state with:
defaults write "Apple Global Domain" "com.apple.keyboard.fnState" "1" ## FKeys
defaults write "Apple Global Domain" "com.apple.keyboard.fnState" "0" ## Media/Special
… but it requires a Logout or Reboot to execute, as the special process that looks for this pref cannot be safely quit/restarted to acknowledge the change (as of macOS Sierra; may no longer be true).