feat: main 병합 + 인스타 올리기 API(/v1/card/{id}/instagram), 관리자 올릴 곳 선택(로컬·킹서버), 만든 카드 화면

This commit is contained in:
minaChoi committed 2026-10-23 15:48:09 +09:00
commit 572b2a05c8
188 files changed
+16605 -741

No files matched your search

+84
View File
@@ -0,0 +1,84 @@
"""인스타그램 캐러셀 올리기 (Instagram API with Instagram Login, graph.instagram.com).
이미지는 인스타가 받아 갈 수 있는 공개 주소여야 한다 (우리 /v1/card/<id>/<n>.jpg 를 PUBLIC_BASE_URL 뒤에 붙인다).
순서: 장마다 컨테이너 → 캐러셀 컨테이너 → 상태 FINISHED 확인 → 게시. 문서: developers.facebook.com/docs/instagram-platform/instagram-api-with-instagram-login/content-publishing
"""
import asyncio
from typing import Optional
import httpx
from common.logger import LOG
from config.settings import settings
GRAPH = "https://graph.instagram.com/v24.0"
TIMEOUT_SEC = 30.0
MAX_ITEMS = 20
# 캐러셀 컨테이너가 FINISHED 가 될 때까지 (문서: 1분에 한 번, 5분까지)
STATUS_TRIES = 10
STATUS_WAIT_SEC = 6.0
class InstagramError(Exception):
pass
def configured() -> bool:
return bool(settings.instagram_access_token.strip() and settings.instagram_user_id.strip())
def public_image_url(path: str) -> str:
return f"{settings.public_base_url.rstrip('/')}{path}"
async def _post(client: httpx.AsyncClient, path: str, data: dict) -> dict:
res = await client.post(f"{GRAPH}/{path}", data={**data, "access_token": settings.instagram_access_token})
body = res.json() if res.content else {}
if res.status_code >= 400 or "error" in body:
msg = (body.get("error") or {}).get("message") or f"HTTP {res.status_code}"
raise InstagramError(msg)
return body
async def _status(client: httpx.AsyncClient, container_id: str) -> str:
res = await client.get(f"{GRAPH}/{container_id}", params={"fields": "status_code", "access_token": settings.instagram_access_token})
body = res.json() if res.content else {}
if res.status_code >= 400 or "error" in body:
raise InstagramError((body.get("error") or {}).get("message") or f"HTTP {res.status_code}")
return body.get("status_code", "")
async def publish_carousel(image_urls: list[str], caption: str, client: Optional[httpx.AsyncClient] = None, wait_sec: float = STATUS_WAIT_SEC) -> str:
"""공개 이미지 주소들을 캐러셀 한 개로 올리고 인스타 미디어 id 를 돌려준다."""
if not configured():
raise InstagramError("INSTAGRAM_ACCESS_TOKEN / INSTAGRAM_USER_ID 가 비어 있다")
if not 1 <= len(image_urls) <= MAX_ITEMS:
raise InstagramError(f"이미지는 1~{MAX_ITEMS}장")
user = settings.instagram_user_id.strip()
own = client is None
client = client or httpx.AsyncClient(timeout=TIMEOUT_SEC)
try:
children = []
for url in image_urls:
children.append((await _post(client, f"{user}/media", {"image_url": url, "is_carousel_item": "true"}))["id"])
if len(children) == 1:
container = (await _post(client, f"{user}/media", {"image_url": image_urls[0], "caption": caption}))["id"]
else:
container = (await _post(client, f"{user}/media", {"media_type": "CAROUSEL", "children": ",".join(children), "caption": caption}))["id"]
for _ in range(STATUS_TRIES):
status = await _status(client, container)
if status == "FINISHED":
break
if status in ("ERROR", "EXPIRED"):
raise InstagramError(f"컨테이너 상태 {status}")
await asyncio.sleep(wait_sec)
else:
raise InstagramError("컨테이너가 제때 준비되지 않았다")
media_id = (await _post(client, f"{user}/media_publish", {"creation_id": container}))["id"]
LOG.info(f"[instagram] published media {media_id} ({len(image_urls)} images)")
return media_id
except httpx.HTTPError as e:
raise InstagramError(f"{type(e).__name__}") from e
finally:
if own:
await client.aclose()