56 lines
1.8 KiB
Python
56 lines
1.8 KiB
Python
import requests,dictdata,os.path,re,traceback
|
|
from bot import IRCLine
|
|
|
|
BOT = None
|
|
def say(target,msg):
|
|
if not BOT: return
|
|
BOT.socket.send(IRCLine("PRIVMSG",target,":"+msg))
|
|
|
|
def unshorten(url):
|
|
r = requests.get(url,allow_redirects=False)
|
|
return r.headers["Location"]
|
|
|
|
UNSHORTEN_URL = dictdata.DictData("UNSHORTEN_urls.json")
|
|
URL = re.compile(r"((?:https?://)?[^\s/$.?#]\.[^\s]*)")
|
|
|
|
from urllib.parse import urlparse
|
|
shorteners = "0x0.st ttm.sh bit.ly".split()
|
|
def is_shortened(url):
|
|
return urlparse(url).hostname in shorteners
|
|
|
|
def on_privmsg(event):
|
|
matches = [url for url in URL.findall(event.message) if is_shortened(url)]
|
|
if not matches: return
|
|
target = event.target if event.target.startswith("#") else event.hostmask.nick
|
|
url = matches[-1]
|
|
UNSHORTEN_URL[target]=url
|
|
|
|
def on_unshorten(event):
|
|
if not BOT: return
|
|
url = None
|
|
target = event.target if event.target.startswith("#") else event.hostmask.nick
|
|
if len(event.parts)>1:
|
|
say(target,(event.hostmask.nick+": " if target!=event.hostmask.nick else '')+"Usage: "+BOT.prefix+"unshorten [url]")
|
|
return
|
|
elif len(event.parts)==1:
|
|
matches = [url for url in URL.findall(event.message) if is_shortened(url)]
|
|
if len(matches)>0: url=matches[-1]
|
|
elif len(event.parts)==0:
|
|
if target not in UNSHORTEN_URL:
|
|
say(target,(event.hostmask.nick+": " if target!=event.hostmask.nick else '')+"I haven't seen a URL here to unshorten.")
|
|
return
|
|
url=UNSHORTEN_URL[target]
|
|
try:
|
|
new_url = unshorten(url)
|
|
except:
|
|
say(target,"Unable to unshorten the URL")
|
|
traceback.print_exc()
|
|
return
|
|
say(target,(event.hostmask.nick+": " if target!=event.hostmask.nick else '')+"Unshortened URL: "+new_url)
|
|
|
|
def register(bot):
|
|
global BOT
|
|
BOT = bot
|
|
bot.event_manager.on("privmsg",on_privmsg)
|
|
bot.event_manager.on("command_unshorten",on_unshorten)
|