minerbot2/plugins/memegen.py

58 lines
1.8 KiB
Python

import requests,plugin,traceback,sys
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()
def fixUp(text):
if not text: return "_" # escape empty string
text = text.replace("_","__") # escape underscores
text = text.replace(" ","_") # escape spaces
text = text.replace("-","--") # escape dashes
text = text.replace("''",'"') # escape double quote
text = text.replace("?","~q") # escape question marks
text = text.replace("%","~p") # escape question marks
text = text.replace("#","~h") # escape question marks
text = text.replace("/","~s") # escape question marks
return text
def memegen(bot,channel,nick,template="help",*msg):
if template=="help":
say(channel,f"{nick}: Usage: {bot.prefix}memegen <template> [top text |] <bottom text>")
return
if nick=="jan6": return
if not msg: return
msg = " ".join(msg)
if "|" in msg:
top, bottom = msg.split("|")
else:
top, bottom = "", msg
top = fixUp(top)
bottom = fixUp(bottom)
if "://" in template: # URL
url = "https://api.memegen.link/images/custom/{}/{}.png?background={}".format(top,bottom,template)
else:
url = "https://api.memegen.link/images/{}/{}/{}.png".format(template,top,bottom)
url = shorten(url)
say(channel,"{}: {}".format(nick,url))
def on_memegen(event):
if not BOT: return
channel = event.target if event.target.startswith("#") else event.hostmask.nick
try:
memegen(BOT,channel,event.hostmask.nick,*event.parts)
except Exception as e:
say(channel,traceback.format_exception_only(*sys.exc_info()[:2])[0])
def register(bot):
global BOT
BOT = bot
bot.event_manager.on("command_memegen",on_memegen)