Automating macOS with AppleScript

File: osascript.lisp

macOS exposes Mail, Calendar, Reminders, Messages, and Safari to AppleScript, and the osascript utility runs AppleScript from the command line. From Lisp, each of those apps is one uiop:run-program call away.

The code

  1 ;;;; osascript.lisp -- tiny macOS automation via osascript.
  2 ;;;; A library, not a script: (load "osascript.lisp") in a REPL,
  3 ;;;; then try the calls in the Examples comment at the bottom.
  4 ;;;; Needs Automation permission for your terminal:
  5 ;;;; System Settings > Privacy & Security.
  6 ;;;; READ-RECENT-IMESSAGES also needs Full Disk Access; SAFARI-LOGIN
  7 ;;;; needs Safari > Develop > Allow JavaScript from Apple Events.
  8 ;;;; Keep credentials out of this file.
  9 (require :asdf)
 10 
 11 (defun osascript (script)
 12   (multiple-value-bind (out err code)
 13       (uiop:run-program (list "osascript" "-e" script)
 14                         :output :string
 15                         :error-output :string
 16                         :ignore-error-status t)
 17     (flet ((trim (s) (string-trim '(#\Space #\Newline #\Return) s)))
 18       (if (zerop code)
 19           (trim out)
 20           (error "osascript: ~a" (trim err))))))
 21 
 22 ;;; ~S quotes Lisp strings as valid AppleScript and JavaScript literals.
 23 (defun mail-unread-count ()
 24   (parse-integer
 25    (osascript
 26     "tell application \"Mail\" to return unread count of inbox")))
 27 
 28 (defun get-todays-events ()
 29   (remove ""
 30           (uiop:split-string
 31            (osascript "tell application \"Calendar\"
 32   set t0 to current date
 33   set time of t0 to 0
 34   set out to {}
 35   repeat with c in calendars
 36     set out to out & (summary of every event of c ¬
 37       whose start date >= t0 and start date < t0 + days)
 38   end repeat
 39   set AppleScript's text item delimiters to \"|\"
 40   return out as string
 41 end tell") :separator "|") :test #'string=))
 42 
 43 (defun send-imessage (phone message)
 44   (osascript
 45    (format nil
 46     (concatenate
 47      'string
 48      "tell application \"Messages\" to send ~S to buddy ~S "
 49      "of (1st service whose service type = iMessage)")
 50     message phone)))
 51 
 52 (defun add-reminder (name)
 53   (osascript
 54    (format nil
 55     (concatenate
 56      'string
 57      "tell application \"Reminders\" to return id of "
 58      "(make new reminder with properties {name:~S})")
 59     name)))
 60 
 61 (defun read-recent-imessages (&optional (limit 5))
 62   (check-type limit (integer 1))
 63   (let ((db (namestring
 64              (merge-pathnames "Library/Messages/chat.db"
 65                               (user-homedir-pathname))))
 66         (sql (format nil
 67               (concatenate
 68                'string
 69                "SELECT m.is_from_me, h.id AS sender, m.text "
 70                "FROM message m LEFT JOIN handle h ON "
 71                "m.handle_id = h.ROWID WHERE m.text IS NOT NULL "
 72                "ORDER BY m.date DESC LIMIT ~d;")
 73               limit)))
 74     (uiop:run-program (list "sqlite3" "-json" db sql)
 75                       :output :string)))
 76 
 77 (defun safari-login (url user password
 78                      &key (user-id "username")
 79                           (password-id "password")
 80                           (form-id "login-form")
 81                           (timeout 30))
 82   (let ((js (format nil
 83              (concatenate
 84               'string
 85               "document.getElementById(~S).value = ~S; "
 86               "document.getElementById(~S).value = ~S; "
 87               "document.getElementById(~S).submit();")
 88              user-id user password-id password form-id)))
 89     (osascript (format nil "tell application \"Safari\"
 90   set d to make new document with properties {URL:~S}
 91   repeat ~d times
 92     delay 0.5
 93     if (do JavaScript \"document.readyState\" in d) is \"complete\" then
 94       return (do JavaScript ~S in d)
 95     end if
 96   end repeat
 97 end tell
 98 error \"Safari page did not load within ~d seconds\""
 99                        url (* 2 timeout) js timeout))))
100 
101 ;;; Examples
102 ;; (osascript "return 1 + 10")
103 ;; (mail-unread-count)
104 ;; (get-todays-events)
105 ;; (add-reminder "Buy milk")
106 ;; (send-imessage "+15551234567" "Hello from Lisp")
107 ;; (read-recent-imessages 3)
108 ;; (safari-login "https://leanpub.com/author/royalties/summary"
109 ;;               (uiop:getenv "LEANPUB_USER")
110 ;;               (uiop:getenv "LEANPUB_PASSWORD"))

How it works

  • osascript (the Lisp function) captures stdout, stderr, and the exit code with multiple-value-bind; a non-zero exit signals a Lisp error that carries AppleScript’s own error message.
  • The ~S format directive handles quoting in this file: it prints a Lisp string as a quoted, escaped string literal, which is also valid AppleScript (and JavaScript) syntax. That makes it safe to insert strings into scripts.
  • get-todays-events shows a common AppleScript pattern: build a list, set text item delimiters to a separator, return the list as a string, then split it in Lisp with uiop:split-string.
  • send-imessage uses the older buddy/service terms from the Messages scripting dictionary. Recent macOS releases also accept the newer participant/account terms; if your version rejects buddy, open the Messages dictionary in Script Editor and adjust the one line.
  • read-recent-imessages skips AppleScript and queries the Messages SQLite database with sqlite3 -json, which is why it needs Full Disk Access. check-type guards the limit parameter that the function inserts into the SQL. On recent macOS versions, many message bodies sit in the binary attributedBody column with text set to NULL, so the query misses some messages. The function returns the raw JSON string to keep the file free of Quicklisp dependencies; parse it with jzon if you have it loaded.
  • safari-login opens a page, checks document.readyState every half second until the page loads (or signals an error after timeout seconds), then runs JavaScript that fills in the username and password fields and submits the form.

Running it

This is the one file in the book that is a library rather than a script: load it in a REPL, since the examples at the bottom are comments. Grant your terminal Automation permission (macOS asks the first time), grant Full Disk Access for read-recent-imessages, and turn on Safari → Develop → Allow JavaScript from Apple Events for safari-login.

1 * (load "osascript.lisp")
2 * (osascript "return 1 + 10")
3 "11"

I ran the call above, and "11" is its real output. The other functions appear as calls, not transcripts, because their results depend on your machine’s state (inbox count, today’s calendar) or change it (sending a message, adding a reminder), so try them in your own REPL.

Using it

Use this chapter as a template: you can wrap any AppleScript you find online the same way. Keep credentials in environment variables (as the last example shows), not in source. These functions combine well with the LLM chapters: summarize today’s calendar, send yourself an iMessage when a script finishes, or check your Leanpub royalties on a schedule.