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

34 lines
1,000 B
Python
Raw Normal View History

2011-11-20 10:23:31 +01:00
# # Lukeroge
2011-11-21 09:41:53 +01:00
from util import hook, http
2011-11-20 10:23:31 +01:00
try:
from re import match
from urllib2 import urlopen, Request, HTTPError
from urllib import urlencode
2011-11-21 09:41:53 +01:00
2011-11-20 10:23:31 +01:00
except ImportError, e:
raise Exception('Required module missing: %s' % e.args[0])
class ShortenError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
2011-11-20 10:23:31 +01:00
def tiny(url, user, apikey):
2011-11-20 10:23:31 +01:00
try:
params = urlencode({'longUrl': url, 'login': user, 'apiKey': apikey, 'format': 'json'})
2011-11-21 09:44:40 +01:00
j = http.get_json("http://api.bit.ly/v3/shorten?%s" % params)
2011-11-20 10:23:31 +01:00
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
def shorten(inp, bot = None):
".shorten <url> - Makes an j.mp/bit.ly shortlink to the url provided"
user = bot.config['api_keys']['bitly_user']
api = bot.config['api_keys']['bitly_api']
return tiny(inp, user, api)