minerbot2/plugins/shortenimg.py

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 shorten(url):
r = requests.post("https://ttm.sh",data=dict(url=url))
r.raise_for_status()
return r.text.strip()
IMAGE_URL = dictdata.DictData("image_urls.json")
URL = re.compile(r"((?:https?|ftp)://[^\s/$.?#].[^\s]*)")
image_exts = ".png .jpg .jpeg .gif .tif .tiff .bmp .svg .webp".split()
def is_image(url):
return os.path.splitext(os.path.basename(url))[1] in image_exts
def on_privmsg(event):
matches = [url for url in URL.findall(event.message) if is_image(url)]
if not matches: return
target = event.target if event.target.startswith("#") else event.hostmask.nick
url = matches[-1]
IMAGE_URL[target]=url
def on_shortenimg(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+"shortenimg [url]")
return
elif len(event.parts)==1:
matches = [url for url in URL.findall(event.message) if is_image(url)]
if len(matches)>0: url=matches[-1]
elif len(event.parts)==0:
if target not in IMAGE_URL:
say(target,(event.hostmask.nick+": " if target!=event.hostmask.nick else '')+"I haven't seen an image here to shorten.")
return
url=IMAGE_URL[target]
try:
new_url = shorten(url)
except:
say(target,"An error occurred!")
traceback.print_exc()
return
say(target,(event.hostmask.nick+": " if target!=event.hostmask.nick else '')+"Shortened URL: "+new_url)
def register(bot):
global BOT
BOT = bot
bot.event_manager.on("privmsg",on_privmsg)
bot.event_manager.on("command_shortenimg",on_shortenimg)