webexmemebot/app/img.py
Luke Tainton 13097b36fb
Some checks failed
Security / sonarqube (push) Failing after 36s
Security / snyk (push) Successful in 1m1s
fix(lint): Fix linting issues (#487)
This pull request focuses on improving the documentation and readability of the Webex meme bot application by adding docstrings and minor formatting adjustments. Here's a breakdown of the changes:

*   **Docstrings:**
    *   Added module-level docstrings to `app/close.py`, `app/img.py`, and `app/main.py` providing a high-level overview of the purpose of each module.
    *   Added docstrings to classes (`ExitCommand`, `MakeMemeCommand`, `MakeMemeCallback`) describing their role.
    *   Added docstrings to methods within those classes (`__init__`, `pre_execute`, `execute`, `post_execute`) explaining their functionality, arguments, and return values where applicable. The `get_templates` and `format_meme_string` functions in `app/img.py` have been documented as well.
*   **Formatting:**
    *   Added a line break before the return type annotation in function definitions (e.g., `def execute(...) -> Response:`).
    *   Added the disable comment `# pylint: disable=line-too-long` to a line in `app/meme.py` to disable pylint for that line.
    *   Added the disable comment `# pylint: disable=unused-argument` to the `pre_execute`, `execute`, and `post_execute` methods to disable pylint checks about unused arguments. This is because these methods are part of an interface and must have the same signature even if some arguments are unused.
*   **Variable Naming:**
    *   Renamed the `vars` dictionary to `env_vars` in `tests/test_config.py` for better clarity.
*   **Test Update:**
    *   Added a docstring to the `test_config` function in `tests/test_config.py` to explain its functionality.
*   **Imports Update:**
    *   Updated imports in `tests/test_config.py` to disable pylint for wrong-import-position errors using `# pylint: disable=wrong-import-position`.

In essence, these changes enhance the maintainability and understandability of the codebase through comprehensive documentation and minor code style improvements.

Reviewed-on: #487
2025-06-06 19:39:11 +02:00

85 lines
2.4 KiB
Python

"""Generates meme images using the memegen.link API."""
import requests
CHAR_REPLACEMENTS: list = [
["_", "__"],
["-", "--"],
[" ", "_"],
["?", "~q"],
["&", "~a"],
["%", "~p"],
["#", "~h"],
["/", "~s"],
["\\", "~b"],
["<", "~l"],
[">", "~g"],
['"', "''"],
]
def get_templates() -> list[dict]:
"""Fetches available meme templates from the memegen.link API.
Returns:
list[dict]: A list of dictionaries containing meme template information.
"""
url: str = "https://api.memegen.link/templates"
req: requests.Response = requests.get(url=url, timeout=10)
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
def format_meme_string(input_string: str) -> str:
"""Formats a string for use in a meme image URL.
Args:
input_string (str): The string to format.
Returns:
str: The formatted string suitable for meme image URLs.
"""
# https://memegen.link/#special-characters
out_string: str = input_string
for char_replacement in CHAR_REPLACEMENTS:
out_string: str = out_string.replace(char_replacement[0], char_replacement[1])
return out_string
def generate_api_url(template: str, top_str: str, btm_str: str) -> str:
"""Generates a meme image URL using the memegen.link API.
Args:
template (str): The template identifier in the format "name.ext".
top_str (str): The text for the top line of the meme.
btm_str (str): The text for the bottom line of the meme.
Returns:
str: The complete URL for the meme image.
"""
tmpl_name: str
tmpl_ext: str
tmpl_name, tmpl_ext = template.split(".")
top_str = format_meme_string(top_str)
btm_str = format_meme_string(btm_str)
url: str = f"https://api.memegen.link/images/{tmpl_name}/{top_str}/{btm_str}.{tmpl_ext}"
return url