TextExpander: bit.ly with authentication
A quick script in response to Donald’s query 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 (in lines 6 & 7), and replace the existing script in the TextExpander experiments bundle with this one (or create a new snippet with the script).
#!/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]+);)/, '&')
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("http://api.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!
Discussion
blog comments powered by Disqus