I found a killer application for ChatGPT today: writing AppleScript!
I’ve been stubbornly refusing to learn AppleScript for nearly twenty years at this point. Thanks to ChatGPT I can continue not to learn it, but I can now use it to solve problems.
I wanted to figure out how to export the content of my Apple Notes notes. Here are some edited highlights from my conversation with ChatGPT:
Me:
Write applescript to loop through all of my Apple Notes and output their contents
ChatGPT:
1
tellapplication"Notes"
2
repeatwitheachNoteinevery note
3
set noteTitle tothenameof eachNote
4
set noteBody tothe body of eachNote
5
display dialog noteTitle &return&return& noteBody
6
end repeat
7
end tell
Me:
How can I turn that into a zsh script which will output the results to my terminal
ChatGPT:
1
#!/usr/bin/zsh
2
3
osascript-e'tell application "Notes"
4
repeat with eachNote in every note
5
set noteTitle to the name of eachNote
6
set noteBody to the body of eachNote
7
set output to noteTitle & "\n" & noteBody & "\n"
8
display dialog output
9
log output
10
end repeat
11
end tell'
I had to change that first line to #!/bin/zsh - then when I ran it it spammed my screen with dialog boxes.
Me:
I want to log the notes contents to the terminal, not display it in a dialog
ChatGPT:
1
#!/bin/zsh
2
3
osascript-e'tell application "Notes"
4
repeat with eachNote in every note
5
set noteTitle to the name of eachNote
6
set noteBody to the body of eachNote
7
set output to noteTitle & "\n" & noteBody & "\n"
8
log output
9
end repeat
10
end tell'
I ended up using what I learned here to build apple-notes-to-sqlite, a new Python tool which wraps osascript under the hood and uses it to export my Apple Notes data to a SQLite database.
tzs on Hacker News tipped me off to the fact that AppleScript automation can be written in JavaScript these days too.
Turns out ChatGPT knows how to translate my AppleScript to JavaScript!
My prompt:
1
tellapplication"Notes"
2
repeatwitheachNoteinevery note
3
set noteTitle tothenameof eachNote
4
set noteBody tothe body of eachNote
5
set output to noteTitle &"\n"& noteBody &"\n"
6
log output
7
end repeat
8
end tell
Write that in JavaScript that talks to Apple automation instead
ChatGPT response:
To write a script in JavaScript that talks to Apple automation, you can use the JavaScript for Automation (JXA) language. Here’s the equivalent script using JXA:
1
constNotes=Application('Notes');
2
Notes.includeStandardAdditions =true;
3
4
constnotes= Notes.notes();
5
constnoteData= [];
6
7
notes.forEach((note) => {
8
constnoteTitle= note.name();
9
constnoteBody= note.body();
10
constoutput= noteTitle +'\n'+ noteBody +'\n';
11
noteData.push(output);
12
});
13
14
noteData.forEach((data) => {
15
console.log(data);
16
});
To run this script, save it as a .scpt file with a text editor and then run it using the Script Editor app on macOS or using the command line with osascript: