moved bit.ly code to a new library
This commit is contained in:
parent
a5aa62358c
commit
b387b15c8f
2 changed files with 34 additions and 29 deletions
|
@ -1,33 +1,8 @@
|
||||||
# Plugin by Lukeroge
|
# Plugin by Lukeroge
|
||||||
|
|
||||||
from util import hook, http
|
from util import hook
|
||||||
from re import match
|
from urllib2 import HTTPError
|
||||||
from urllib2 import urlopen, Request, HTTPError
|
from util.web import bitly, ShortenError
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
@hook.command
|
@hook.command
|
||||||
|
@ -37,4 +12,8 @@ def shorten(inp, bot=None):
|
||||||
api_key = bot.config.get("api_keys", {}).get("bitly_api", None)
|
api_key = bot.config.get("api_keys", {}).get("bitly_api", None)
|
||||||
if api_key is None:
|
if api_key is None:
|
||||||
return "error: no api key set"
|
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
|
||||||
|
|
26
plugins/util/web.py
Executable file
26
plugins/util/web.py
Executable file
|
@ -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'])
|
Reference in a new issue