2016-03-30 18:31:23 +00:00
|
|
|
#--require-config bitly-api-key
|
|
|
|
|
2016-03-29 15:20:50 +00:00
|
|
|
import re
|
|
|
|
import Utils
|
|
|
|
|
|
|
|
URL_BITLYSHORTEN = "https://api-ssl.bitly.com/v3/shorten"
|
|
|
|
REGEX_URL = re.compile("https?://", re.I)
|
|
|
|
|
|
|
|
class Module(object):
|
2018-09-02 18:54:45 +00:00
|
|
|
def __init__(self, bot, events, exports):
|
2016-03-29 15:20:50 +00:00
|
|
|
self.bot = bot
|
2018-08-31 11:55:52 +00:00
|
|
|
self.events = events
|
|
|
|
events.on("get").on("shortlink").hook(self.shortlink)
|
|
|
|
events.on("received").on("command").on("shorten"
|
2016-04-06 11:02:44 +00:00
|
|
|
).hook(self.shorten, min_args=1, help="Shorten a URL.",
|
|
|
|
usage="<url>")
|
2016-03-29 15:20:50 +00:00
|
|
|
|
|
|
|
def shortlink(self, event):
|
2018-09-09 12:20:59 +00:00
|
|
|
url = event["url"]
|
2016-03-29 15:20:50 +00:00
|
|
|
if not re.match(REGEX_URL, url):
|
|
|
|
url = "http://%s" % url
|
|
|
|
data = Utils.get_url(URL_BITLYSHORTEN, get_params={
|
|
|
|
"access_token": self.bot.config["bitly-api-key"],
|
|
|
|
"longUrl": url}, json=True)
|
|
|
|
if data and data["data"]:
|
|
|
|
return data["data"]["url"]
|
|
|
|
|
|
|
|
def shorten(self, event):
|
2018-08-31 11:55:52 +00:00
|
|
|
link = self.events.on("get").on("shortlink"
|
2018-07-15 14:15:52 +00:00
|
|
|
).call_for_result(url=event["args"])
|
2016-03-29 15:20:50 +00:00
|
|
|
if link:
|
|
|
|
event["stdout"].write("Short URL: %s" % link)
|
|
|
|
else:
|
|
|
|
event["stderr"].write("Unable to shorten that URL.")
|