Learning AppleScript: Creating a "Do Not Disturb" Toggle

July 10, 2010

On a whim I decided to start learning AppleScript tonight. AppleScript is one of the great features of OSX, and allows scripts to communicate pretty much with any [decently built] application.

The first use case I could think of was a little toggle for quiet time, a “Do Not Disturb” toggle. It has 2 modes, Quiet and Noisy. In Quiet mode it puts Mailplane into its own “Do Not Disturb” mode, logs out of iChat, closes Skype, turns off Growl, and turns on Caffeine (assuming this quiet time also involves concentrated looking at the screen). Noisy mode is normal; flipping that switch logs back into iChat, and turns Mailplane and Growl back on. (It doesn’t toggle all the same things; I don’t always have Skype on and Caffeine shouldn’t necessarily be turned off. More on that below.)

Here’s the code:

-- figure out: how can it REMEMBER from one run to the next (e.g. were caffeine, ichat on?)

set appName to "DoNotDisturb Toggle"  -- for display later

-- register with Growl
tell application "GrowlHelperApp"
    set the allNotificationsList to {"toggle-announce"}
    copy allNotificationsList to enabledNotificationsList
    register as application ¬
        appName all notifications allNotificationsList ¬
        default notifications enabledNotificationsList
end tell

display dialog "Noisy or Quiet?" buttons {"Noisy", "Silent"}
set doMode to button returned of result

if doMode is "Noisy" then
    tell application "Mailplane" to set doNotDisturb to false

    tell application "GrowlHelperApp"
        launch
        notify with name "toggle-announce" title appName ¬
            description "Going back to Noisy mode" application name appName
    end tell

    tell application "iChat" to log in # what if it wasn't before?

else -- Quiet
    tell application "GrowlHelperApp"
        notify with name "toggle-announce" title appName ¬
            description "Going into Quiet mode" application name appName
        quit
    end tell

    tell application "Mailplane" to set doNotDisturb to true

    tell application "Caffeine" to turn on # (turn on for quiet but don't turn off on noisy)

    tell application "iChat" to log out
    tell application "Skype" to quit

end if

I turned it into an Application (File->Save As), so it’s easy to run from the Dock.

What I need to figure out is how it can remember states from one run to the other: it should only log back into iChat, for instance, if it was logged in before going into Quiet mode. Does anyone know?