2022-08-25 02:07:02 +02:00
|
|
|
from aiohttp import ClientSession
|
|
|
|
|
|
|
|
import settings
|
2022-08-29 20:24:42 +02:00
|
|
|
from database.schemas import MemeTemplate
|
2022-08-25 02:07:02 +02:00
|
|
|
from didier.exceptions.missing_env import MissingEnvironmentVariable
|
2022-08-26 20:02:54 +02:00
|
|
|
from didier.utils.http.requests import ensure_post
|
2022-08-25 02:07:02 +02:00
|
|
|
|
|
|
|
__all__ = ["generate_meme"]
|
|
|
|
|
|
|
|
|
2022-08-25 11:04:25 +02:00
|
|
|
def generate_boxes(meme: MemeTemplate, fields: list[str]) -> list[str]:
|
2022-08-25 02:07:02 +02:00
|
|
|
"""Generate the template boxes for Imgflip"""
|
|
|
|
# If a meme only has 1 field, join all the arguments together into one string
|
|
|
|
if meme.field_count == 1:
|
|
|
|
fields = [" ".join(fields)]
|
|
|
|
|
|
|
|
fields = fields[: min(20, meme.field_count)]
|
2022-08-25 11:04:25 +02:00
|
|
|
# TODO manipulate the text if necessary
|
|
|
|
return fields
|
2022-08-25 02:07:02 +02:00
|
|
|
|
|
|
|
|
2022-08-26 20:02:54 +02:00
|
|
|
async def generate_meme(http_session: ClientSession, meme: MemeTemplate, fields: list[str]) -> str:
|
2022-08-25 02:07:02 +02:00
|
|
|
"""Make a request to Imgflip to generate a meme"""
|
|
|
|
name, password = settings.IMGFLIP_NAME, settings.IMGFLIP_PASSWORD
|
|
|
|
|
|
|
|
# Ensure credentials exist
|
|
|
|
if name is None:
|
|
|
|
raise MissingEnvironmentVariable("IMGFLIP_NAME")
|
|
|
|
|
|
|
|
if password is None:
|
|
|
|
raise MissingEnvironmentVariable("IMGFLIP_PASSWORD")
|
|
|
|
|
|
|
|
boxes = generate_boxes(meme, fields)
|
2022-08-25 11:04:25 +02:00
|
|
|
payload = {"template_id": meme.template_id, "username": name, "password": password}
|
|
|
|
for i, box in enumerate(boxes):
|
|
|
|
payload[f"boxes[{i}][text]"] = box
|
2022-08-25 02:07:02 +02:00
|
|
|
|
2022-08-26 20:02:54 +02:00
|
|
|
async with ensure_post(http_session, "https://api.imgflip.com/caption_image", payload=payload) as response:
|
|
|
|
return response["data"]["url"]
|