Automating a Mac using AppleScript
Tags: beginners, automation, scripting, macos
Published: 2020-06-15 18:47:35

While in the process of creating a wallpaper automation project using python, I found the easiest way to change the wallpaper on my MacBook was using AppleScript. The command I found was:

```python
# the %s is the path to an image file stored locally
command = """/usr/bin/osascript<<END
    tell application "Finder"
        set desktop picture to POSIX file "%s"
    end tell
    END"""
```

Digging into this code, the beginning path directs to the osascript file which allows us to run AppleScript and other OSA language scripts. Then the code is fairly self-explanatory: I tell the application Finder to set the desktop wallpaper to a file saved on our computer. I then end the tell and and the script.

Given how easy the script was to read and understand, my curiosity of AppleScript was piqued. So I decided to learn some basic commands and keywords in AppleScript to make automation on my Mac easier in the future.

<h2>AppleScript Editor</h2>

To begin playing around with AppleScript, the Mac has an application under Applications/Utilities called Script Editor. Open that up and you should see the following:

![AppleScript Editor](https://dev-to-uploads.s3.amazonaws.com/i/flvz5rifiuqowvsylfwa.png)

If there is already a script written in the main body, just open a new window using ⌘N or File>New. Once the body is blank, we're ready to start scripting.

Once we have a script written, we can compile the code using the hammer icon (saving the file also compiles the code) and press the play button to run the script.

<h2>Hello World!</h2>

![Scripting Mac to audibly say "Hello World!"](https://dev-to-uploads.s3.amazonaws.com/i/i3h0355kfowt0r8ylzwo.png)

AppleScript has the command 'say' that will audibly say the string we type after. Try it out by typing say and whatever string in quotations you want your computer to say, compiling the code, and pressing play. Your Mac should have the default voice speak whatever you typed in quotes.

Apple has another way of saying "Hello World" with it's recognizable muted 'beep' sound. Try trying the word beep on a new line and running the script.

![Using beep on AppleScript](https://dev-to-uploads.s3.amazonaws.com/i/od7hmd39jzd3ur2qonxp.png)

<h2>Popup 'OK' or 'Cancel' Options</h2>

We can also use the 'display dialog' command to open up an option menu for the user to select OK or Cancel.

![Display Dialog Command](https://dev-to-uploads.s3.amazonaws.com/i/x95zripi4z7hsr83iz8h.png)

When the code is run, a window will pop up. Try running the code twice so you can see the difference in output depending on the selection. There are many use cases where you may want to receive confirmation before completing a task, and this command makes that process a snap.

<h2>Variables</h2>

We can also create and assign variables in AppleScript. The syntax looks like:

```applescript
set myName to "Laura"
```

After setting this variable, I can add it to strings using the & operator. In the following script, I use the say command so my computer says "Welcome back, Laura" as well as printing it out to the results on line 3 (note that we don't use print or any other keyword).

![Assigning Variables in AppleScript](https://dev-to-uploads.s3.amazonaws.com/i/bzikpxv6fxwznunuw9fa.png)

<h2>Interacting with Applications</h2>

In the script I used to change wallpaper, I interacted with an application - Finder. We can use AppleScript to interact with any scriptable applications on a Mac. <a href="https://eastmanreference.com/complete-list-of-applescript-key-codes">Here is a link to all the key codes AppleScript uses that make interacting with applications easier as well as notes on using the command 'keystroke' instead.</a> Using these key codes, we can go to specific websites, input information, click on items, search for info, etc. Basically anything we can do manually using our keyboards we can do through AppleScript.

In order to open an application, the command 'activate' is used.

```applescript
tell application "iTunes" to activate
activate application "Spotify"
```

Both of the commands above are a valid way to open an application and/or bring it to the front. To run commands through an application, we use the command 'tell.'

```applescript
tell application "Finder"
	set desktop picture to POSIX file "%s"
end tell
```

To change desktop wallpaper on a Mac, we tell Finder to set the desktop picture to a image file at a given path. We then end the tell. We can run multiple commands within the tell block. Different scritable applications accept different commands.

In order to know what applications are scriptable and what commands we can use, all we need to do is open the dictionary included in the Script Editor.

![Dictionary for the script editor](https://dev-to-uploads.s3.amazonaws.com/i/cr2to1tlwld4thphvidf.png)

I have Spotify downloaded and it's included in the dictionary, so I will use that as an example. There are a lot of commands that listed in the dictionary, but I'm going to use play track and pause. Using play track instead of just play, I can specify a specific song or album using unique Spotify URIs. these can be found by right clicking on a song or album, navigating to share, and then copy Spotify URI. I will also be utilizing delay which telling AppleScript to wait a given number of seconds before executing the next line.

```applescript
activate application "Spotify"
tell application "Spotify"
	play track "spotify:track:4OBZT9EnhYIV17t4pGw7ig"
	delay 60
	play track "spotify:track:3898C4AbdbptwYet6547e5"
end tell
```

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/kwn5mwud1wuimxgxfeyx.png)

After 60 seconds, Best Part by H.E.R is paused. Then we tell Spotify to play "The Girl from Ipanema" by João Gilberto and Astrud Gilberto.

![Alt Text](https://dev-to-uploads.s3.amazonaws.com/i/2jmwn7r3py0jyhayoia5.png)

Note that we don't actually need to pause the previous song to switch. That line is only there to show another command in Spotify.

If you have any favorite uses of AppleScript, let me know in the comments! I've just begun exploring the documentation and am excited to continue deepening my AppleScript knowledge.

If you're curious about what can be done using Google Chrome, <a href="https://www.youtube.com/watch?v=EAZlFptgEPQ"/>here is a fun video about using AppleScript to automate following users on Instagram through a Chrome browzer.</a> Disclaimer, I don't recommend botting on Instagram and neither does the video.