Skip to content

Instantly share code, notes, and snippets.

@chew-z
Last active February 15, 2016 15:06
Show Gist options
  • Save chew-z/56de0c9af258f6654e13 to your computer and use it in GitHub Desktop.
Save chew-z/56de0c9af258f6654e13 to your computer and use it in GitHub Desktop.
Shorten links with Bitly API in Pythonista
#coding: utf-8
#shortens urls from clipboard using bitly
import sys
import requests
import re
import clipboard
import keychain
def shorten(long_url, token):
if re.match('\w{40,40}', token):
if long_url == '':
raise Exception('Nothing found in clipboard')
elif not re.match('http(s)?://.*', long_url):
raise Exception('Not a proper url found in clipboard')
else:
pass
else:
raise Exception('Bitly token seems wrong')
print 'Shortening url: ' + long_url + '\n'
userdata = {
'access_token': token,
'longUrl': long_url,
'format': 'json'
}
endpoint = 'https://api-ssl.bitly.com/v3/shorten?'
response = requests.get(endpoint, params = userdata)
j = response.json()
if not j['status_code'] == 200:
raise Exception('bitly returned error: '+j['status_txt'])
url = j['data']['url']
# check fails with on.wsj.com etc..
# if not re.match('http://bit.ly/\w{7,7}', url):
# raise Exception('Received not a proper bitly url')
return url
token = keychain.get_password('Bitly', 'token')
if len(sys.argv) > 1:
long_url = sys.argv[1]
else:
long_url = clipboard.get()
short_url = ''
try:
short_url = shorten(long_url, token)
except Exception, err:
import sys
sys.stderr.write('ERROR: %s\n' % str(err))
if short_url:
print short_url
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment