[feat] solution/backend: 카톡 승인 알림에 [승인] 버튼 — 연결된 계정이 권한 (Event API 2-2)

2-1 로 카톡에 글과 [수정하기] 가 오게 됐고, 이제 카톡 안에서 바로 올린다.
승인 권한은 링크가 아니라 연결된 계정이다 — 버튼이 들고 온 글 ID 는 믿지 않는다.

- kakao_bot: 알림 카드에 [승인](action: block, blockId=KAKAO_APPROVE_BLOCK_ID,
  extra={kind:approve, post_id}) 을 그리고, 클릭은 action.clientExtra 로 받는다.
  블록 ID 가 비면 버튼을 그리지 않는다(눌러도 안 되는 버튼을 보내지 않는다)
- channel.approve_post: 누른 발화자 → 사장님 → 그 가게의 미처리·기한 전 글인지 재확인 후
  approve_by_owner(메일·'바로 발행' 과 같은 경로라 재발행 잡·쓰레드 공유까지 동일).
  연결 안 됨·남의 글·이미 올림·기한 지남은 같은 안내로 끝나고 두 번 올라가지 않는다.
  답장은 "올렸습니다" + [사이트 보기](#blog). LLM 을 부르지 않는다
- 5초를 넘겨도 승인 작업은 취소하지 않는다(asyncio.shield) — 여러 번 커밋하는 작업이라
  중간에 끊기면 승인만 되고 재발행이 안 걸린 글이 남는다
- PostService._blog_url → blog_url(채널이 [사이트 보기] 에 쓴다)

test_kakao_webhook 10건 추가(구현 전 5건 실패 확인), 관련 11개 스위트 239 passed.
실제 클릭 본문(action.clientExtra 위치)은 첫 클릭의 로그로 확인한다.
This commit is contained in:
skkim committed 2026-09-29 16:50:40 +09:00
1 parent f1b473968d
commit e0155d0423
8 files changed
+333 -20

No files matched your search

+65 -10
View File
@@ -40,18 +40,33 @@ CALLBACK_DEADLINE_SEC = 45.0
_TIMEOUT_TEXT = "확인하는 데 시간이 조금 걸리네요. 잠시 뒤 다시 말씀해 주세요."
_ERROR_TEXT = "지금은 처리할 수 없어요. 잠시 뒤 다시 말씀해 주세요."
_WAIT_TEXT = "확인하고 있어요. 잠시만 기다려 주세요."
_APPROVING_TEXT = "승인하고 있어요. 잠시 뒤 사이트에서 확인해 주세요."
_DEFAULT_HINT = "아래 버튼을 눌러 주세요."
_APPROVE_HINT = "이대로 올리려면 승인, 고쳐서 올리려면 수정하기를 눌러 주세요."
# 승인 버튼의 extra 에 실리는 종류 표지. 이 값이 아닌 clientExtra 는 승인으로 읽지 않는다.
_APPROVE_KIND = "approve"
def _reply(text: str, quick_replies=None, links=None) -> dict:
def _reply(text: str, quick_replies=None, links=None, approve_post_id=None, hint=None) -> dict:
"""오픈빌더 스킬 응답(SkillResponse). ★ 카카오 형식을 아는 유일한 함수다."""
payload: dict = {"outputs": [{"simpleText": {"text": text}}]}
if links:
# 링크 버튼은 카드에만 붙는다(simpleText 에는 버튼이 없다). 본문과 따로 둬 카드 설명 길이
# 제한(글 문구가 그 안에 안 들어갈 수 있다)에 걸리지 않게 한다.
payload["outputs"].append({"textCard": {
"description": "고쳐서 올리려면 아래 버튼을 눌러 주세요.",
"buttons": [{"label": link["label"], "action": "webLink", "webLinkUrl": link["url"]} for link in links[:3]],
}})
# 버튼은 카드에만 붙는다(simpleText 에는 버튼이 없다). 본문과 따로 둬 카드 설명 길이 제한
# (글 문구가 그 안에 안 들어갈 수 있다)에 걸리지 않게 한다.
buttons = []
block_id = config.approve_block_id()
if approve_post_id and block_id:
# ★ action "block" 의 extra 는 눌렀을 때 그 블록의 스킬 요청에 action.clientExtra 로 돌아온다.
# 블록 ID 가 비어 있으면 버튼을 그리지 않는다 — 눌러도 안 되는 버튼을 사장님께 보내지 않는다.
buttons.append({
"label": "승인", "action": "block", "blockId": block_id, "messageText": "승인",
"extra": {"kind": _APPROVE_KIND, "post_id": approve_post_id},
})
buttons += [{"label": link["label"], "action": "webLink", "webLinkUrl": link["url"]} for link in (links or [])]
if buttons:
description = _APPROVE_HINT if approve_post_id and block_id else (hint or _DEFAULT_HINT)
payload["outputs"].append({"textCard": {"description": description, "buttons": buttons[:3]}})
if quick_replies:
# 바로가기는 최대 10개. 누르면 그 라벨이 **다음 발화로 그대로 들어온다** —
# channel.py 의 _YES/_NO 가 같은 문자열을 알고 있어야 먹는다.
@@ -61,6 +76,14 @@ def _reply(text: str, quick_replies=None, links=None) -> dict:
return {"version": "2.0", "template": payload}
def _reply_from(answer: dict) -> dict:
"""channel 이 돌려준(카카오를 모르는) 답을 SkillResponse 로."""
return _reply(
answer["text"], answer.get("quick_replies"), answer.get("links"),
approve_post_id=answer.get("approve_post_id"), hint=answer.get("hint"),
)
def _authorize(secret_in_path: str | None, header_secret: str | None, body: dict) -> None:
expected = config.webhook_secret()
if not expected:
@@ -88,7 +111,7 @@ async def _answer(utterance: str, speaker: str, deadline: float) -> dict:
except Exception as ex: # noqa: BLE001 — 메신저에서는 500 도 침묵으로 보인다
LOG.w(f"[agent/kakao] 처리 실패: {type(ex).__name__}")
return _reply(_ERROR_TEXT)
return _reply(answer["text"], answer.get("quick_replies"), answer.get("links"))
return _reply_from(answer)
async def _approval_notice(params: dict, speaker: str) -> dict:
@@ -107,7 +130,32 @@ async def _approval_notice(params: dict, speaker: str) -> dict:
except Exception as ex: # noqa: BLE001 — 메신저에서는 500 도 침묵으로 보인다
LOG.w(f"[agent/kakao] 승인 알림 처리 실패: {type(ex).__name__}")
return _reply(_ERROR_TEXT)
return _reply(answer["text"], answer.get("quick_replies"), answer.get("links"))
return _reply_from(answer)
def _log_task_failure(task: asyncio.Task) -> None:
if not task.cancelled() and task.exception() is not None:
LOG.w(f"[agent/kakao] 승인 처리 실패(응답 뒤): {type(task.exception()).__name__}")
async def _approve_click(extra: dict, speaker: str) -> dict:
"""[승인] 버튼 클릭. 글 ID 는 우리가 알림을 그릴 때 extra 에 실은 값이지만, 누가 무엇을
승인할 수 있는지는 channel.approve_post 가 다시 판단한다.
★ 5초를 넘겨도 **승인 작업을 취소하지 않는다.** 승인은 상태 변경 → 재발행 잡 적재 → 쓰레드
공유 순서로 여러 번 커밋해서, 중간에 끊기면 승인만 되고 재발행이 안 걸린 글이 남는다.
shield 로 응답만 먼저 돌려주고 작업은 끝까지 돈다."""
task = asyncio.ensure_future(channel.approve_post(speaker, str(extra.get("post_id") or "")))
try:
answer = await asyncio.wait_for(asyncio.shield(task), timeout=DEADLINE_SEC)
except asyncio.TimeoutError:
task.add_done_callback(_log_task_failure)
LOG.w("[agent/kakao] 승인 응답 시간 초과 — 작업은 계속 돈다")
return _reply(_APPROVING_TEXT)
except Exception as ex: # noqa: BLE001 — 메신저에서는 500 도 침묵으로 보인다
LOG.w(f"[agent/kakao] 승인 처리 실패: {type(ex).__name__}")
return _reply(_ERROR_TEXT)
return _reply_from(answer)
async def _push(callback_url: str, utterance: str, speaker: str) -> None:
@@ -133,6 +181,13 @@ async def _handle(body: dict, tasks: BackgroundTasks) -> dict:
# 발화자를 모르면 누구의 가게인지도 모른다. 여기서 끝낸다.
return _reply("사용자를 확인하지 못했어요.")
# ★ [승인] 버튼(action: block)의 extra 는 그 블록의 스킬 요청에 action.clientExtra 로 돌아온다.
# 글 ID 값은 남기지 않고 어떤 키가 왔는지만 남긴다.
extra = (body.get("action") or {}).get("clientExtra") or {}
if isinstance(extra, dict) and extra.get("kind") == _APPROVE_KIND and extra.get("post_id"):
LOG.i(f"[agent/kakao] 승인 클릭 — extra={sorted(extra)} block={(request.get('block') or {}).get('name')!r}")
return await _approve_click(extra, speaker)
# ★ 우리가 Event API 로 보낸 승인 알림이 이 요청을 시작시켰다면 params 에 글 ID 가 있다.
# 값(수정 코드는 비밀에 준한다)은 남기지 않고 어떤 키가 왔는지만 남긴다 — 실제 요청 본문이
# 문서와 같은지를 눈으로 가릴 수 있게.