From b387b15c8f2b7a591086230e56d2b5b38584224f Mon Sep 17 00:00:00 2001 From: Luke Rogers Date: Sat, 21 Apr 2012 15:55:52 +1200 Subject: [PATCH] moved bit.ly code to a new library --- plugins/shorten.py | 37 ++++++++----------------------------- plugins/util/web.py | 26 ++++++++++++++++++++++++++ 2 files changed, 34 insertions(+), 29 deletions(-) create mode 100755 plugins/util/web.py diff --git a/plugins/shorten.py b/plugins/shorten.py index 7ab07e6..63f96b8 100755 --- a/plugins/shorten.py +++ b/plugins/shorten.py @@ -1,33 +1,8 @@ # Plugin by Lukeroge -from util import hook, http -from re import match -from urllib2 import urlopen, Request, HTTPError -from urllib import urlencode - - -class ShortenError(Exception): - def __init__(self, value): - self.value = value - - def __str__(self): - return repr(self.value) - - -def bitly(url, user, apikey): - try: - if url[:8] == "https://": - pass - elif url[:7] != "http://": - url = "http://" + url - params = urlencode({'longUrl': url, 'login': user, 'apiKey': apikey, - 'format': 'json'}) - j = http.get_json("http://api.bit.ly/v3/shorten?%s" % params) - if j['status_code'] == 200: - return j['data']['url'] - raise ShortenError('%s' % j['status_txt']) - except (HTTPError, ShortenError): - return "Could not shorten %s!" % url +from util import hook +from urllib2 import HTTPError +from util.web import bitly, ShortenError @hook.command @@ -37,4 +12,8 @@ def shorten(inp, bot=None): api_key = bot.config.get("api_keys", {}).get("bitly_api", None) if api_key is None: return "error: no api key set" - return bitly(inp, api_user, api_key) + + try: + return bitly(inp, api_user, api_key) + except (HTTPError, ShortenError): + return "Could not shorten %s!" % inp diff --git a/plugins/util/web.py b/plugins/util/web.py new file mode 100755 index 0000000..1c550b5 --- /dev/null +++ b/plugins/util/web.py @@ -0,0 +1,26 @@ +""" web.py - handy functions for web services """ + +import http +from urllib import urlencode + + +class ShortenError(Exception): + def __init__(self, value): + self.value = value + + def __str__(self): + return repr(self.value) + + +def bitly(url, user, api_key): + """ shortens a URL with the bit.ly API """ + if url[:8] == "https://": + pass + elif url[:7] != "http://": + url = "http://" + url + params = urlencode({'longUrl': url, 'login': user, 'apiKey': api_key, + 'format': 'json'}) + j = http.get_json("http://api.bit.ly/v3/shorten?%s" % params) + if j['status_code'] == 200: + return j['data']['url'] + raise ShortenError('%s' % j['status_txt'])