This repository has been archived on 2023-04-13. You can view files and clone it, but cannot push or open issues or pull requests.
CloudBot/plugins/shorten.py

43 lines
1.3 KiB
Python
Raw Permalink Normal View History

# Plugin by Lukeroge
# <lukeroge@gmail.com> <https://github.com/lukeroge/CloudBot/>
2011-11-21 09:41:53 +01:00
from util import hook, http
2012-02-26 10:08:36 +01:00
from re import match
from urllib2 import urlopen, Request, HTTPError
from urllib import urlencode
class ShortenError(Exception):
def __init__(self, value):
self.value = value
2012-02-29 09:29:53 +01:00
def __str__(self):
return repr(self.value)
2011-11-20 10:23:31 +01:00
def bitly(url, user, apikey):
2012-02-26 10:08:36 +01:00
try:
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
2011-11-20 10:23:31 +01:00
@hook.command
2012-02-29 09:29:53 +01:00
def shorten(inp, bot=None):
2012-02-28 03:03:43 +01:00
".shorten <url> - Makes an j.mp/bit.ly shortlink to the url provided."
2012-02-26 10:08:36 +01:00
api_user = bot.config.get("api_keys", {}).get("bitly_user", 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)
@hook.command
2012-02-29 09:29:53 +01:00
def expand(inp, bot=None):
2012-02-28 03:03:43 +01:00
".expand <url> - Gets the original URL from a shortened link."
try:
url = http.get_url(inp)
except HTTPError, e:
return "Failed to expand URL."
return url