노션 수정 발생 시 해당 이벤트를 호출해서 정보를 받아온 후 해당 페이지의 간단한 정보와 URL을 mattermost로 전달하는 부분

This commit is contained in:
2025-07-22 15:01:26 +09:00
parent 0d04dd8d0a
commit 30f3806ae6
2 changed files with 64 additions and 29 deletions

View File

@ -10,16 +10,7 @@ from datetime import datetime
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from lib.config import Config
NOTION_API_BASE = "https://api.notion.com/v1"
NOTION_VERSION = "2022-06-28"
HEADERS = {
"Authorization": f"Bearer {Config.NOTION_API_SECRET}",
"Notion-Version": NOTION_VERSION,
"Content-Type": "application/json"
}
from lib.common import EVENT_TYPE_LABELS
def get_page_details(page_id: str) -> Optional[Dict]:
url = f"{NOTION_API_BASE}/pages/{page_id}"
@ -57,25 +48,25 @@ def handle_notion_event(event: dict) -> Optional[str]:
수신 이벤트를 콘솔에 출력하고,
노션 API를 호출해 상세 데이터를 가져옵니다.
"""
import logging
from datetime import datetime
# 1) 수신 이벤트 원본 로깅
logging.info("🔔 수신된 Notion 웹훅 이벤트:")
logging.info(json.dumps(event, ensure_ascii=False, indent=2))
# 2) 워크스페이스 ID 확인 및 이름 조회 (예: workspace_id 필드)
# 2) workspace_id 및 workspace_name 확인
workspace_id = event.get("workspace_id")
if not workspace_id:
logging.warning("⚠️ workspace_id 없음 - 이벤트 무시")
return None
# 3) workspace_name 확인 (노션 API로 조회 필요)
# 실제 노션 공식 API에 workspace 이름 조회 엔드포인트가 없음
# 테스트 편의를 위해 하드코딩 반환
workspace_name = get_workspace_name(workspace_id)
if workspace_name != "퍼스트가든":
logging.info(f"워크스페이스명이 '{workspace_name}'이므로 무시함")
return None
# 4) 이벤트 기본 정보
# 3) 이벤트 기본 정보
event_type = event.get("type", "unknown")
timestamp = event.get("timestamp")
readable_time = None
@ -89,30 +80,53 @@ def handle_notion_event(event: dict) -> Optional[str]:
entity_id = entity.get("id", "unknown")
entity_type = entity.get("type", "unknown")
# 4) 작성자 정보
authors = event.get("authors", [])
author = authors[0] if authors else {"id": "unknown", "type": "unknown"}
author_type = author.get("type", "unknown")
author_id = author.get("id", "unknown")
# 5) 구체적 변경사항 API 호출 (예: 페이지 상세 정보)
# 5) 노션 API로 상세 페이지 정보 조회
detail = fetch_entity_detail(entity_type, entity_id)
# detail은 dict or None
message_lines = [
f"📢 Notion 이벤트 발생: `{event_type}`",
f"- 🕒 시간: {readable_time}",
f"- 📁 워크스페이스: {workspace_name}",
f"- 📄 엔티티: `{entity_type}` / ID: `{entity_id}`",
f"- 👤 작성자: `{author_type}` / ID: `{author_id}`",
]
if not detail:
logging.warning("⚠️ 상세 페이지 정보를 가져오지 못함")
return None
if detail:
detail_str = json.dumps(detail, ensure_ascii=False, indent=2)
message_lines.append(f"- 🔍 상세 내용:\n```json\n{detail_str}\n```")
# 6) 페이지 제목 추출
page_title = "(제목 없음)"
try:
props = detail.get("properties", {})
title_prop = props.get("작업 이름", {})
if title_prop.get("type") == "title":
title_arr = title_prop.get("title", [])
if title_arr:
page_title = "".join(t.get("plain_text", "") for t in title_arr)
except Exception as e:
logging.error(f"페이지 제목 추출 중 오류: {e}")
# 7) 작성자 이름 추출 (최종 편집자 이름)
editor_name = "(알 수 없음)"
try:
last_edited_by = props.get("최종 편집자", {}).get("last_edited_by", {})
editor_name = last_edited_by.get("name", editor_name)
except Exception as e:
logging.error(f"작성자 이름 추출 중 오류: {e}")
# 8) 페이지 URL
page_url = detail.get("url", "URL 없음")
# 9) 메시지 구성
event_label = EVENT_TYPE_LABELS.get(event_type, f"📢 Notion 이벤트 발생: `{event_type}`")
message = (
f"{event_label}\n"
f"- 🕒 시간: {readable_time}\n"
f"- 📄 페이지 제목: {page_title}\n"
f"- 👤 작업자: {editor_name}\n"
f"- 🔗 [페이지 바로가기]({page_url})"
)
message = "\n".join(message_lines)
logging.info("🔔 생성된 메시지:\n" + message)
return message