webexmemebot/app/img.py

62 lines
1.6 KiB
Python
Raw Permalink Normal View History

2023-07-21 23:57:14 +02:00
import requests
2023-12-14 21:55:17 +01:00
CHAR_REPLACEMENTS: list = [
["_", "__"],
["-", "--"],
[" ", "_"],
["?", "~q"],
["&", "~a"],
["%", "~p"],
["#", "~h"],
["/", "~s"],
["\\", "~b"],
["<", "~l"],
[">", "~g"],
['"', "''"],
]
2023-07-21 23:57:14 +02:00
def get_templates() -> list[dict]:
url: str = "https://api.memegen.link/templates"
2024-11-28 21:54:36 +01:00
req: requests.Response = requests.get(url=url, timeout=10)
2023-07-21 23:57:14 +02:00
req.raise_for_status()
data: dict = req.json()
templates: list = []
for tmpl in data:
if tmpl["lines"] != 2:
continue
if tmpl["id"] == "oprah":
tmpl["name"] = "Oprah You Get A..."
tmpl_ext: str = "gif" if "animated" in tmpl["styles"] else "jpg"
tmpl_data: dict = {
"id": tmpl["id"],
"name": tmpl["name"],
"ext": tmpl_ext,
"choiceval": tmpl["id"] + "." + tmpl_ext,
}
templates.append(tmpl_data)
templates = sorted(templates, key=lambda d: d["name"])
return templates
2023-07-24 17:16:30 +02:00
def format_meme_string(input_string: str) -> str:
# https://memegen.link/#special-characters
2023-12-14 21:55:17 +01:00
out_string: str = input_string
for char_replacement in CHAR_REPLACEMENTS:
out_string: str = out_string.replace(char_replacement[0], char_replacement[1])
2023-07-24 17:16:30 +02:00
return out_string
2023-07-21 23:57:14 +02:00
def generate_api_url(template: str, top_str: str, btm_str: str) -> str:
2023-07-24 17:16:30 +02:00
tmpl_name: str
tmpl_ext: str
2023-07-21 23:57:14 +02:00
tmpl_name, tmpl_ext = template.split(".")
2023-07-24 17:16:30 +02:00
top_str = format_meme_string(top_str)
btm_str = format_meme_string(btm_str)
2023-07-21 23:57:14 +02:00
2024-08-04 20:02:10 +02:00
url: str = (
f"https://api.memegen.link/images/{tmpl_name}/{top_str}/{btm_str}.{tmpl_ext}"
)
2023-07-21 23:57:14 +02:00
return url