Micro.blog via AppleScript

On the latest Core Intuition, Daniel and I talk about the just-released FastScripts 3, his app for quickly running scripts. He mentioned that even though AppleScript hasn’t had any attention in years, it’s still useful as a complement to Shortcuts and other workflows. Daniel said:

It’s like learning a little bit of French when you go to France. You don’t have to do it, but you’re going to have such an easier time if you do. And in my opinion, learning — even now, even in its state of relative neglect — learning a little bit of AppleScript on the Mac is like learning a little bit of French in France. You’re going to get a lot farther with everything you want to do.

Micro.blog doesn’t have AppleScript support, but it does have a URL scheme for starting a new blog post. For example, I wrote the AppleScript below to play around with FastScripts 3. You could trigger it with a keyboard shortcut from FastScripts to start a new blog post using a link for an open Safari tab.

-- we'll need access to AppKit for NSString's URL encoding
use framework "Foundation"
use scripting additions

-- global variables that we'll set later
set the_url to ""
set the_title to ""

-- helper function to URL-encode the text we'll pass to Micro.blog
on urlEncode(input)
	tell current application's NSString to set raw_url to stringWithString_(input)
	set the_encoded_url to raw_url's stringByAddingPercentEscapesUsingEncoding:4 -- 4 is NSUTF8StringEncoding
	return the_encoded_url as Unicode text
end urlEncode

-- ask Safari for the current tab's URL and page title
tell application "Safari"
	set the_url to URL of current tab of window 1
	set the_title to name of current tab of window 1
end tell

-- make a Markdown string like [title](url)
set s to "[" & the_title & "](" & the_url & ")"
set the_mb_url to "microblog://post?text=" & urlEncode(s)

-- start a new post with Micro.blog for Mac
open location the_mb_url

My AppleScript knowledge is very rusty, and it took more than a few web searches to cobble this together, mostly because of the URL encoding. Now that it’s working it could be the basis for other automation with Micro.blog.

Manton Reece @manton