42 lines
1.2 KiB
Python
42 lines
1.2 KiB
Python
from __future__ import annotations
|
|
|
|
from typing import Any
|
|
|
|
import httpx
|
|
|
|
from .settings import get_settings
|
|
|
|
|
|
async def subscribe_newsletter(
|
|
*,
|
|
email: str,
|
|
name: str = "",
|
|
list_ids: list[int] | None = None,
|
|
city_slug: str = "",
|
|
) -> dict[str, Any]:
|
|
settings = get_settings()
|
|
if not settings.listmonk_api_key:
|
|
return {"ok": False, "error": "newsletter_not_configured"}
|
|
|
|
payload: dict[str, Any] = {
|
|
"email": email.strip(),
|
|
"name": name.strip() or email.split("@")[0],
|
|
"status": "enabled",
|
|
"lists": list_ids or settings.listmonk_default_list_ids,
|
|
"preconfirm_subscriptions": True,
|
|
}
|
|
if city_slug:
|
|
payload["attribs"] = {"city": city_slug}
|
|
|
|
headers = {"Authorization": f"token {settings.listmonk_api_key}"}
|
|
async with httpx.AsyncClient(timeout=20.0) as client:
|
|
response = await client.post(
|
|
f"{settings.listmonk_api_url.rstrip('/')}/api/subscribers",
|
|
json=payload,
|
|
headers=headers,
|
|
)
|
|
if response.status_code >= 400:
|
|
return {"ok": False, "error": response.text[:300]}
|
|
data = response.json()
|
|
return {"ok": True, "subscriber": data.get("data")}
|