---
title: 'TextExpander: bit.ly with authentication'
date: 2010-10-18 18:56
slug: textexpander-bit-ly-with-authentication
categories:
- Code
tags:
- scripting
- textexpander
- bitly
- ruby
- url shortener
---

A quick script in response to [Donald's query](http://brettterpstra.com/textexpander-experiments/#comments) on my TextExpander Experiments post. He wanted to know if I could make the bit.ly script which expands to a bit.ly-shortened version of a url in the clipboard work with an authenticated account, presumably for click tracking. Well, sure! Just adjust the script below to contain your bit.ly username and your [API key](http://bit.ly/a/your_api_key) (in lines 6 & 7), and replace the existing script in the [TextExpander experiments bundle](http://brettterpstra.com/code/?did=6 "Download the TextExpander Experiments bundle") with this one (or create a new snippet with the script).

```ruby
#!/usr/bin/env ruby -wKU

require 'open-uri'
require 'cgi'

USER_NAME = 'username' # Your login name
API_KEY = 'yourlongapikey' # http://bit.ly/a/your_api_key

def entity_escape(text)
  text.gsub(/&(?!([a-zA-Z0-9]+|#[0-9]+|#x[0-9a-fA-F]+);)/, '&amp;')
end

def make_link(text)
  case text
  when %r{\Ahttps?://.*?\.\w{2,4}.*?\z}:
    entity_escape(text)
  when %r{\A(www\..*|.*\.\w{2,4})\z}:
    "http://#{entity_escape text}"
  when %r{\A.*?\.\w{2,4}\/?.*\z}:
    "http://#{entity_escape text}"
  else
    nil
  end
end

url = make_link %x{__CF_USER_TEXT_ENCODING=$UID:0x8000100:0x8000100 pbpaste}.strip
res = open("https://api-ssl.bit.ly/v3/shorten?login=#{USER_NAME}&apiKey=#{API_KEY}&longUrl=#{CGI.escape(url)}&format=txt").read unless url.nil?

begin
  print res unless res.nil?
rescue
  exit
end
```

The API can output JSON and XML, which would be more appropriate on most occasions, but the "txt" format (which *only* includes the shortened link) is perfect for this situation. Enjoy!

---

Brett is a writer and developer living in Minnesota, USA. You can follow him as ttscoff. This content is supported by readers like you. [More about Brett](https://brettterpstra.com/contact.md), including social links.

Copyright © 2026 Brett Terpstra. All rights reserved.
