discord-havoc/jesusmemes.py

66 lines
2.5 KiB
Python

#!/usr/bin/env python3.12
import aiohttp
from typing import Optional
import regex
from regex import Pattern
import os
import random
import traceback
from urllib.parse import quote as urlquote
from catbox import Catbox
"""
Jesus Meme Generator
(requires Catbox uploader)
"""
class JesusMemeGenerator():
def __init__(self) -> None:
self.MEMEAPIURL = "https://apimeme.com/meme?meme="
self.MEMESTORAGEDIR = os.path.join(os.path.expanduser("~"),
"memes")
self.top_line_regex: Pattern = regex.compile(
r'[^\p{Letter}\p{Number}\p{Punctuation}\p{Horiz_Space}\p{Currency_Symbol}]')
self.bottom_line_regex: Pattern = regex.compile(
r'[^\p{Letter}\p{Number}\p{Punctuation}\p{Horiz_Space}\p{Currency_Symbol}]')
self.url_regex_1: Pattern = regex.compile(
r'\p{Horiz_Space}'
)
self.url_regex_2: Pattern = regex.compile(
r'#'
)
async def create_meme(self, top_line: str, bottom_line: str,
meme="Jesus-Talking-To-Cool-Dude") -> Optional[str]:
try:
if not top_line or not bottom_line:
return None
top_line = self.top_line_regex.sub('',
top_line.strip())
bottom_line = self.bottom_line_regex.sub('',
bottom_line.strip())
out_fname: Optional[str] = None
if len(top_line) < 1 or len(bottom_line) < 1:
return None
formed_url: str = f"{self.MEMEAPIURL}{meme}&top={top_line.strip()}&bottom={bottom_line.strip()}"
formed_url = self.url_regex_1.sub('+', self.url_regex_2.sub('%23', formed_url.strip()))
timeout = aiohttp.ClientTimeout(total=15)
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(formed_url) as response:
UUID = f"{random.getrandbits(8)}-{random.getrandbits(8)}"
out_fname = f"{UUID}.jpg"
with open(f"{self.MEMESTORAGEDIR}/{out_fname}", 'wb') as f:
f.write(await response.read())
if not out_fname:
uploader = Catbox()
meme_link: str = uploader.upload(f"{self.MEMESTORAGEDIR}/{out_fname}")
return meme_link
except:
print(traceback.format_exc())
pass
return None