moar refactor
This commit is contained in:
77
util/jesusmemes.py
Normal file
77
util/jesusmemes.py
Normal file
@ -0,0 +1,77 @@
|
||||
#!/usr/bin/env python3.12
|
||||
|
||||
import aiohttp
|
||||
from typing import Optional
|
||||
import regex
|
||||
from regex import Pattern
|
||||
import os
|
||||
import random
|
||||
import logging
|
||||
import traceback
|
||||
from util.catbox import CatboxAsync
|
||||
|
||||
"""
|
||||
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]:
|
||||
"""
|
||||
Create Meme
|
||||
Args:
|
||||
top_line (str): Top line of meme
|
||||
bottom_line (str): Bottom line of meme
|
||||
meme (str): The meme to use, defaults to Jesus-Talking-To-Cool-Dude
|
||||
Returns:
|
||||
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 = CatboxAsync()
|
||||
meme_link: Optional[str] = await uploader.upload(f"{self.MEMESTORAGEDIR}/{out_fname}")
|
||||
if not meme_link:
|
||||
logging.info("Meme upload failed!")
|
||||
return None
|
||||
return meme_link
|
||||
except:
|
||||
print(traceback.format_exc())
|
||||
pass
|
||||
return None
|
Reference in New Issue
Block a user