From 98b5c0cbe3a54a78934f309493a980f4ee8a710b Mon Sep 17 00:00:00 2001 From: Mina Choi Date: Tue, 27 Oct 2026 13:14:30 +0900 Subject: [PATCH] =?UTF-8?q?feat:=20=ED=8F=AC=EC=8A=A4=ED=8A=B8=EB=A5=BC=20?= =?UTF-8?q?=EB=A7=8C=EB=93=A4=20=EB=95=8C=20=EB=82=A0=EC=94=A8=EA=B0=81=20?= =?UTF-8?q?=EC=BA=90=EB=A6=AD=ED=84=B0(=ED=95=B4=EB=8B=98=C2=B7=EA=B5=AC?= =?UTF-8?q?=EB=A6=84=C2=B7=EB=8B=AC=EB=8B=98)=20=EB=8C=93=EA=B8=80=201~2?= =?UTF-8?q?=EA=B0=9C=20=E2=80=94=20'=EB=82=A0=EC=94=A8=EA=B0=81'=20?= =?UTF-8?q?=ED=91=9C=EC=8B=9C,=20=EC=8B=A0=EA=B3=A0=C2=B7=EC=B0=A8?= =?UTF-8?q?=EB=8B=A8=20=EB=A9=94=EB=89=B4=20=EC=97=86=EC=9D=8C,=20?= =?UTF-8?q?=EC=9D=B4=EB=AF=B8=20=EB=A7=8C=EB=93=A0=20=EB=82=A0=EC=9D=80=20?= =?UTF-8?q?scripts/fill=5Fbot=5Fcomments.py?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- TODO.md | 3 + backend/common/database/model/models.py | 1 + backend/crud/feed_crud.py | 20 +- backend/postgres-init/init.sql | 3 + backend/router/v1/card/card.py | 3 + backend/router/v1/reaction/protocol.py | 1 + backend/router/v1/reaction/reaction.py | 2 +- backend/scripts/fill_bot_comments.py | 26 + backend/services/bot_comment.json | 648 ++++++++++++++++++++++++ backend/services/bot_comment.py | 50 ++ backend/services/feed_service.py | 3 + backend/services/reaction_service.py | 4 + backend/tests/conftest.py | 9 + backend/tests/test_anon_like.py | 1 + backend/tests/test_auth_reaction.py | 1 + backend/tests/test_bot_comment.py | 82 +++ backend/tests/test_post_scope.py | 1 + frontend/src/b/Sheets.tsx | 4 +- shared/api/client/types.gen.ts | 6 + 19 files changed, 864 insertions(+), 4 deletions(-) create mode 100644 backend/scripts/fill_bot_comments.py create mode 100644 backend/services/bot_comment.json create mode 100644 backend/services/bot_comment.py create mode 100644 backend/tests/test_bot_comment.py diff --git a/TODO.md b/TODO.md index 86e6a9f..9afb3a6 100644 --- a/TODO.md +++ b/TODO.md @@ -63,6 +63,9 @@ | [ ] | **[결정 필요]** 쇼츠 문구 검토: '소리 켜기'/'소리 끄기' (줄 제목은 없앰) | 화면 문구 규칙 | `frontend/src/b/Shorts.tsx` | | [ ] | 쇼츠를 올린 직후 목록 갱신(`ShortsService.refresh`) 부르기 — 지금은 워커가 07·12·18시 10분에만 받아 18시 넘어 올리면 다음 날 아침에 뜸. 자동 업로드면 끝난 뒤 호출, 손으로 올리면 관리자 갱신 API | 올리는 방식 확인 필요 | `backend/services/shorts_service.py`, `backend/worker_main.py` | | [ ] | 쇼츠 자동재생 아이폰 사파리 실기기 확인 — 소리 꺼도 자동재생을 막는다는 보고 있음 | 헤드리스 크롬에서만 확인 | `frontend/src/b/Shorts.tsx` | +| [x] | 단풍 명소 `남이섬`이 두 번 들어감(절정 10-25·10-27) — 10-27(화목원) 쪽 지움, 67곳 | 10/27 전체 점검 | `frontend/seo/foliage_2026.json` | +| [x] | 날짜 따라 깨지던 테스트 2개 — 노을 칸은 그날 해 지는 시각으로, 방위각은 한 해 범위(240~300°)로 확인 | 10/27 전체 점검 | `backend/tests/test_weather_today.py`, `backend/tests/test_sky_api.py` | +| [x] | 빈 댓글 보완 — 포스트마다 날씨각 캐릭터(해님·구름·달님) 댓글 1~2개, '날씨각' 표시. 사람인 척하는 가짜 계정·부풀린 숫자는 안 함 | 10/27 결정 | `backend/services/bot_comment.py`, `backend/services/bot_comment.json` | | [ ] | 인스타 운영 관리자 페이지(자동 게시 전 승인 메일) + 초기 이야기형 피드(각 100개·빨래각·소맥각·점수 산정법) | 10/21 회의 | | | [ ] | 레이어 공유 아이디어 — 사용자 사진 위에 날씨각 정보를 얹어 공유(캐시워크식), 앱 기능으로 | 10/21 회의 (황 본부장 의견, 대표 방향) | | | [ ] | iOS 개발자 계정 — 소장에게 기존 계정 확인, 어려우면 회사 계정 새로 만들기. 안드로이드 앱 계속 준비 | 10/21 회의 결정 | | diff --git a/backend/common/database/model/models.py b/backend/common/database/model/models.py index b2eb5be..880047a 100644 --- a/backend/common/database/model/models.py +++ b/backend/common/database/model/models.py @@ -399,6 +399,7 @@ class Comment(Base): user_id: Mapped[Optional[uuid.UUID]] = mapped_column(UUID(as_uuid=True), nullable=True) ip_hash: Mapped[Optional[str]] = mapped_column(String(64), nullable=True) region_name: Mapped[Optional[str]] = mapped_column(String(20), nullable=True) + bot: Mapped[Optional[str]] = mapped_column(String(10), nullable=True) body: Mapped[str] = mapped_column(String(60)) like_count: Mapped[int] = mapped_column(Integer, default=0) report_count: Mapped[int] = mapped_column(Integer, default=0) diff --git a/backend/crud/feed_crud.py b/backend/crud/feed_crud.py index fe4bd1c..9893332 100644 --- a/backend/crud/feed_crud.py +++ b/backend/crud/feed_crud.py @@ -1,11 +1,11 @@ from datetime import date from typing import Optional -from sqlalchemy import select +from sqlalchemy import exists, select, update from sqlalchemy.dialects.postgresql import insert from sqlalchemy.ext.asyncio import AsyncSession -from common.database.model.models import Post +from common.database.model.models import Comment, Post class FeedCRUD: @@ -21,6 +21,22 @@ class FeedCRUD: if rows: await s.execute(insert(Post).values(rows).on_conflict_do_nothing()) + async def without_bot(self, s: AsyncSession, day: date) -> list[Post]: + """그날 포스트 중 캐릭터 댓글이 아직 없는 것.""" + has_bot = exists().where(Comment.post_id == Post.post_id, Comment.bot.is_not(None)) + return list((await s.scalars(select(Post).where(Post.feed_date == day, Post.deleted.is_(False), ~has_bot))).all()) + + async def add_bot_comments(self, s: AsyncSession, lines: dict[int, list[tuple[str, str]]]) -> None: + """캐릭터 댓글을 넣고 포스트 댓글 수를 늘린다. 같은 포스트·캐릭터는 한 번만 (동시에 불려도 겹치지 않게).""" + rows = [{"post_id": post_id, "bot": bot, "body": body} for post_id, x in lines.items() for bot, body in x] + if not rows: + return + added = (await s.execute(insert(Comment).values(rows).on_conflict_do_nothing().returning(Comment.post_id))).scalars().all() + for n in (1, 2): + ids = [post_id for post_id in set(added) if added.count(post_id) == n] + if ids: + await s.execute(update(Post).where(Post.post_id.in_(ids)).values(comment_count=Post.comment_count + n)) + async def get(self, s: AsyncSession, post_id: int) -> Optional[Post]: post = await s.get(Post, post_id) return post if post is not None and not post.deleted else None diff --git a/backend/postgres-init/init.sql b/backend/postgres-init/init.sql index 5ef7a02..b2f337b 100644 --- a/backend/postgres-init/init.sql +++ b/backend/postgres-init/init.sql @@ -266,6 +266,9 @@ ALTER TABLE public.comment ALTER COLUMN user_id DROP NOT NULL; ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS ip_hash VARCHAR(64) NULL; ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS region_name VARCHAR(20) NULL; CREATE INDEX IF NOT EXISTS idx_comment_ip ON public.comment (ip_hash, created_at) WHERE user_id IS NULL; +-- 날씨각 캐릭터(해님 sun·구름 cloud·달님 moon)가 포스트를 만들 때 단 댓글. user_id·ip_hash 는 비고 화면엔 '날씨각' 표시가 붙는다 +ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS bot VARCHAR(10) NULL; +CREATE UNIQUE INDEX IF NOT EXISTS uq_comment_bot ON public.comment (post_id, bot) WHERE bot IS NOT NULL; ALTER TABLE public.users ADD COLUMN IF NOT EXISTS terms_agreed_at TIMESTAMPTZ NULL; ALTER TABLE public.comment ADD COLUMN IF NOT EXISTS report_count INTEGER NOT NULL DEFAULT 0; diff --git a/backend/router/v1/card/card.py b/backend/router/v1/card/card.py index 2e5251f..5f0ccd8 100644 --- a/backend/router/v1/card/card.py +++ b/backend/router/v1/card/card.py @@ -13,7 +13,9 @@ from common.logger import LOG from common.models.errors import error_info from common.utils.kma_time import KST, kst_midnight, now_kst from crud.card_crud import CardCRUD +from crud.feed_crud import FeedCRUD from router.v1.card.protocol import CardItem, Req_CardCreate, Res_Card, Res_CardList +from services.bot_comment import fill_bot_comments from services.external import instagram from services.feed_service import _FEED_DAY_START, clear_feed_cache, feed_day @@ -59,6 +61,7 @@ async def _publish(card_id: int) -> tuple[ErrorType, Res_Card]: return err, Res_Card(result=error_info(err)) if card is None: return ErrorType.NOT_FOUND, Res_Card(result=error_info(ErrorType.NOT_FOUND)) + await fill_bot_comments(day, FeedCRUD()) await clear_feed_cache() LOG.info(f"[card] publish {card_id} → post {card.post_id}") return ErrorType.SUCCESS, Res_Card(card_id=card.card_id, status=CardStatus(card.status), post_id=card.post_id) diff --git a/backend/router/v1/reaction/protocol.py b/backend/router/v1/reaction/protocol.py index 25dd97b..08b6ab3 100644 --- a/backend/router/v1/reaction/protocol.py +++ b/backend/router/v1/reaction/protocol.py @@ -39,6 +39,7 @@ class CommentData(WebPacketProtocol): like_count: int liked: bool mine: bool + official: bool = Field(default=False, description="날씨각 캐릭터(해님·구름·달님)가 단 댓글. 이름 옆에 '날씨각' 표시") created_at: datetime diff --git a/backend/router/v1/reaction/reaction.py b/backend/router/v1/reaction/reaction.py index 2647f24..2f536a5 100644 --- a/backend/router/v1/reaction/reaction.py +++ b/backend/router/v1/reaction/reaction.py @@ -21,7 +21,7 @@ router = APIRouter(prefix="/v1/reaction", tags=["reaction"]) def _comment(v: CommentView) -> CommentData: c = v.comment - return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, created_at=c.created_at.astimezone(KST)) + return CommentData(comment_id=c.comment_id, nickname=v.nickname, character=v.character, color=v.color, mood=v.mood, body=c.body, like_count=c.like_count, liked=v.liked, mine=v.mine, official=v.official, created_at=c.created_at.astimezone(KST)) async def _like(post_id: int, who: Liker, on: bool, service: ReactionService) -> Res_PostLike: diff --git a/backend/scripts/fill_bot_comments.py b/backend/scripts/fill_bot_comments.py new file mode 100644 index 0000000..aff9d5f --- /dev/null +++ b/backend/scripts/fill_bot_comments.py @@ -0,0 +1,26 @@ +"""이미 만든 그날 포스트에 캐릭터 댓글을 단다 (기능을 넣은 날 한 번). 이미 달린 포스트는 건너뛴다. +python scripts/fill_bot_comments.py 2026-10-27""" +import asyncio +import os +import sys +from datetime import date + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from common.database.db_session_manager import DB_SESSION_MNG # noqa: E402 +from common.enums import ErrorType # noqa: E402 +from crud.feed_crud import FeedCRUD # noqa: E402 +from services.bot_comment import fill_bot_comments # noqa: E402 +from services.feed_service import clear_feed_cache # noqa: E402 + + +async def main(day: date) -> int: + err = await fill_bot_comments(day, FeedCRUD()) + await clear_feed_cache() + await DB_SESSION_MNG.stop() + print(f"bot comments {day}: {err.name}") + return 0 if err is ErrorType.SUCCESS else 1 + + +if __name__ == "__main__": + sys.exit(asyncio.run(main(date.fromisoformat(sys.argv[1])))) diff --git a/backend/services/bot_comment.json b/backend/services/bot_comment.json new file mode 100644 index 0000000..4aaa5ea --- /dev/null +++ b/backend/services/bot_comment.json @@ -0,0 +1,648 @@ +{ + "WEATHER": [ + [ + [ + "sun", + "옷차림 정하기 전에 한 번 보고 가요 ☀️" + ], + [ + "cloud", + "저는 하루 종일 하늘에서 구경할게요" + ] + ], + [ + [ + "cloud", + "시간마다 기온 보고 겉옷 챙길지 정해요" + ], + [ + "sun", + "아침이랑 낮 차이를 꼭 보세요!" + ] + ], + [ + [ + "sun", + "좋은 하루 시작해요! 오늘도 날씨각이 챙길게요" + ], + [ + "moon", + "저는 밤에 다시 올게요 🌙" + ] + ] + ], + "ALERT": [ + [ + [ + "cloud", + "나가기 전에 꼭 한 번 보고 가요" + ], + [ + "sun", + "다들 조심히 다녀요" + ] + ], + [ + [ + "cloud", + "챙길 것 미리 챙겨 두면 든든해요" + ], + [ + "moon", + "퇴근길도 조심히 오세요" + ] + ], + [ + [ + "sun", + "오늘은 실내 일정도 같이 생각해 봐요" + ], + [ + "cloud", + "무리하지 말아요" + ] + ] + ], + "GAK": [ + [ + [ + "sun", + "오늘 이거 할 사람 손! 🙋" + ], + [ + "cloud", + "저는 구경만 할게요" + ] + ], + [ + [ + "sun", + "계산 근거 누르면 왜 이 점수인지 나와요" + ], + [ + "moon", + "저녁엔 순위가 바뀌기도 해요 🌙" + ] + ], + [ + [ + "cloud", + "오늘 뭐 할지 고민될 땐 여기부터 봐요" + ], + [ + "sun", + "같이 갈 사람한테 보내 봐요!" + ] + ] + ], + "SUNSET": [ + [ + [ + "moon", + "노을 지면 제가 나올 차례예요 🌙" + ], + [ + "sun", + "저 퇴근할 때 손 흔들어 주세요 🌇" + ] + ], + [ + [ + "sun", + "해 지는 시간 맞춰 나가 봐요" + ], + [ + "cloud", + "구름이 조금 있어야 더 붉게 물든대요" + ] + ], + [ + [ + "moon", + "노을 사진 찍으면 저도 보여 주세요 📸" + ], + [ + "sun", + "저도요!" + ] + ] + ], + "TOMORROW": [ + [ + [ + "moon", + "내일 입을 옷은 미리 꺼내 두고 자요 🌙" + ], + [ + "sun", + "내일 아침에 봬요!" + ] + ], + [ + [ + "sun", + "내일 일정 잡기 전에 한 번 보고 가요" + ], + [ + "cloud", + "저도 내일 계획 세우는 중이에요" + ] + ], + [ + [ + "moon", + "오늘도 수고했어요. 내일 날씨는 여기 있어요" + ], + [ + "cloud", + "푹 자요" + ] + ] + ], + "WEEK": [ + [ + [ + "sun", + "이번 주 빨래할 날 미리 찍어 둬요 ☀️" + ], + [ + "cloud", + "제가 오는 날은 피해 주세요" + ] + ], + [ + [ + "cloud", + "주중 약속 잡을 때 참고하세요" + ], + [ + "sun", + "주말까지 쭉 봐 두면 편해요" + ] + ], + [ + [ + "sun", + "이번 주도 힘내요!" + ], + [ + "moon", + "밤마다 응원할게요 🌙" + ] + ] + ], + "EVENT": [ + [ + [ + "sun", + "같이 갈 사람한테 보내 봐요 🎉" + ], + [ + "moon", + "밤에 하는 거면 저도 갈게요 🌙" + ] + ], + [ + [ + "cloud", + "가기 전에 그날 날씨 한 번 더 봐요" + ], + [ + "sun", + "날씨 맞으면 바로 가요!" + ] + ], + [ + [ + "sun", + "이번 주에 하나쯤은 가 봐요" + ], + [ + "cloud", + "실내 행사면 제가 와도 괜찮아요" + ] + ] + ], + "SEASON": [ + [ + [ + "sun", + "이맘때만 볼 수 있는 이야기예요" + ], + [ + "cloud", + "놓치기 전에 한 번 가 봐요" + ] + ], + [ + [ + "moon", + "계절이 바뀌는 게 느껴져요" + ], + [ + "sun", + "그러게요!" + ] + ], + [ + [ + "sun", + "읽고 나면 나가 보고 싶어져요" + ], + [ + "cloud", + "저도요" + ] + ] + ], + "TIP": [ + [ + [ + "cloud", + "오, 이건 몰랐어요" + ], + [ + "sun", + "친구한테 아는 척하기 좋아요 ☀️" + ] + ], + [ + [ + "moon", + "알아 두면 쓸모 있는 이야기예요" + ], + [ + "cloud", + "저장해 둘게요" + ] + ], + [ + [ + "sun", + "오늘의 상식 하나 챙겨 가요!" + ], + [ + "moon", + "내일 또 하나 알려 줄게요" + ] + ] + ], + "QUOTE": [ + [ + [ + "moon", + "오늘 마음에 남는 말이네요 🌙" + ], + [ + "sun", + "저장해 두고 또 봐요" + ] + ], + [ + [ + "sun", + "이 말 들고 하루 시작해요" + ], + [ + "cloud", + "좋다…" + ] + ], + [ + [ + "cloud", + "천천히 한 번 더 읽어 봤어요" + ], + [ + "moon", + "저도요" + ] + ] + ], + "WEEKEND_PLAN": [ + [ + [ + "sun", + "주말 약속 정할 때 이거 보여 줘요" + ], + [ + "cloud", + "제가 오는 날은 실내로 가요" + ] + ], + [ + [ + "sun", + "벌써 주말이 기다려져요 ☀️" + ], + [ + "moon", + "저도요 🌙" + ] + ], + [ + [ + "moon", + "계획 세워 두면 주말이 더 길어요" + ], + [ + "sun", + "맞아요!" + ] + ] + ], + "AIR": [ + [ + [ + "cloud", + "창문 열기 전에 한 번 보고 가요" + ], + [ + "sun", + "환기는 공기 좋을 때 짧게!" + ] + ], + [ + [ + "sun", + "마스크 챙길지 여기서 정해요 😷" + ], + [ + "cloud", + "챙겨서 손해 볼 건 없어요" + ] + ], + [ + [ + "cloud", + "바람이 불면 공기가 좀 나아져요" + ], + [ + "moon", + "밤에 한 번 더 확인해 봐요" + ] + ] + ], + "DAY_TRIP": [ + [ + [ + "sun", + "주말에 훌쩍 떠나 볼까요? 🚗" + ], + [ + "cloud", + "저 없는 곳으로 가면 딱이에요" + ] + ], + [ + [ + "moon", + "돌아오는 길 노을도 챙겨 봐요 🌇" + ], + [ + "sun", + "좋아요!" + ] + ], + [ + [ + "sun", + "같이 갈 사람한테 보내 봐요!" + ], + [ + "cloud", + "운전 조심해요" + ] + ] + ], + "MOON_FULL": [ + [ + [ + "moon", + "오늘은 제가 제일 동그란 날이에요 🌕" + ], + [ + "sun", + "소원 하나씩 빌어요!" + ] + ], + [ + [ + "moon", + "고개 들어 한 번 봐 주세요" + ], + [ + "cloud", + "오늘은 안 가릴게요… 아마도" + ] + ] + ], + "MOON_NEW": [ + [ + [ + "moon", + "오늘은 제가 쉬는 날이에요. 별 구경 하세요 ✨" + ], + [ + "sun", + "별 사진 찍으면 보여 주세요!" + ] + ], + [ + [ + "moon", + "제가 없는 밤이라 별이 더 잘 보여요" + ], + [ + "cloud", + "저도 오늘은 얌전히 있을게요" + ] + ] + ], + "MOON": [ + [ + [ + "moon", + "오늘 밤 저 한 번 올려다봐 주세요 🌙" + ], + [ + "cloud", + "제가 가리면 미안해요" + ] + ], + [ + [ + "moon", + "하루하루 모양이 바뀌는 걸 보는 재미가 있어요" + ], + [ + "sun", + "내일은 또 다르겠네요" + ] + ], + [ + [ + "moon", + "다음 보름까지 같이 세어 봐요" + ], + [ + "sun", + "좋아요!" + ] + ] + ], + "UV": [ + [ + [ + "sun", + "오늘은 제가 좀 세요. 선크림 꼭 바르세요 ☀️" + ], + [ + "cloud", + "모자도 챙기면 좋아요" + ] + ], + [ + [ + "sun", + "낮에 나가면 그늘로 다녀요" + ], + [ + "cloud", + "물도 자주 마시고요" + ] + ], + [ + [ + "cloud", + "흐려도 자외선은 와요. 선크림 잊지 마세요" + ], + [ + "sun", + "맞아요!" + ] + ] + ], + "HERO": [ + [ + [ + "sun", + "오늘 날씨 어때요? ☀️" + ], + [ + "cloud", + "창밖 한 번 보고 와요" + ] + ], + [ + [ + "moon", + "오늘도 날씨각이 먼저 챙겨 볼게요" + ], + [ + "sun", + "같이 봐요!" + ] + ], + [ + [ + "sun", + "출근길 날씨 같이 봐요!" + ], + [ + "cloud", + "우산은 여기서 확인해요" + ] + ] + ], + "TODAY_GAK": [ + [ + [ + "sun", + "오늘 1위 해 본 사람? 🙋" + ], + [ + "cloud", + "저는 집콕이 좋아요" + ] + ], + [ + [ + "sun", + "누르면 왜 이 점수인지 나와요" + ], + [ + "moon", + "저녁엔 순위가 바뀌기도 해요 🌙" + ] + ] + ], + "FOLIAGE": [ + [ + [ + "sun", + "단풍 보러 어디 가세요? 🍁" + ], + [ + "cloud", + "위에서 보면 정말 예뻐요" + ] + ], + [ + [ + "moon", + "절정 지나기 전에 꼭 가 봐요" + ], + [ + "sun", + "가까운 곳부터 찾아봐요" + ] + ] + ], + "EVENTS_BAND": [ + [ + [ + "sun", + "이번 주 뭐 하고 놀지 여기서 골라요 🎉" + ], + [ + "cloud", + "가기 전에 날씨도 같이 봐요" + ] + ] + ], + "SEASON_BAND": [ + [ + [ + "moon", + "예년 이맘때 이야기 읽는 재미가 있어요" + ], + [ + "sun", + "계절 바뀌는 거 같이 느껴 봐요" + ] + ] + ], + "CARD": [ + [ + [ + "sun", + "오늘 카드 저장해 두고 또 봐요 ✨" + ], + [ + "cloud", + "저는 두 번째 장이 좋아요" + ] + ], + [ + [ + "moon", + "친구한테도 보내 줘요" + ], + [ + "sun", + "같이 보면 더 재밌어요!" + ] + ] + ] +} diff --git a/backend/services/bot_comment.py b/backend/services/bot_comment.py new file mode 100644 index 0000000..3f62b3f --- /dev/null +++ b/backend/services/bot_comment.py @@ -0,0 +1,50 @@ +"""날씨각 캐릭터(해님·구름·달님)가 포스트를 만들 때 다는 댓글. 문구는 bot_comment.json 에 글 종류마다 1~2줄 세트로 있다. +포스트는 시도마다 하나라 구마다 내용이 달라, 문구엔 숫자나 그날 날씨를 단정하는 말을 넣지 않는다.""" +import json +import random +from datetime import date, datetime, time, timedelta +from pathlib import Path + +from common.database.db_session_manager import DB_SESSION_MNG +from common.enums import ErrorType, PostType +from common.logger import LOG +from common.utils.kma_time import KST +from crud.feed_crud import FeedCRUD +from services.calc.moon import nearest + +BOT_NAMES = {"sun": "해님", "cloud": "구름", "moon": "달님"} +BOT_COLORS = {"sun": "orange", "cloud": "blue", "moon": "purple"} +_COPY: dict[str, list[list[list[str]]]] = json.loads((Path(__file__).parent / "bot_comment.json").read_text(encoding="utf-8")) + + +def _moon_key(day: date) -> str: + """그날 밤(정오~다음 날 정오)에 보름이나 삭이 있으면 그 이야기. 달 포스트(FeedService._moon)와 같은 기준.""" + start = datetime.combine(day, time(12), tzinfo=KST) + tonight = start + timedelta(hours=10) + if start <= nearest(tonight, True) < start + timedelta(days=1): + return "MOON_FULL" + if start <= nearest(tonight, False) < start + timedelta(days=1): + return "MOON_NEW" + return "MOON" + + +def bot_lines(post_type: PostType, day: date, seed: int) -> list[tuple[str, str]]: + """포스트에 달 (캐릭터, 문구) 1~2줄. 세트 하나를 고르고 1줄이면 첫 줄만, 2줄이면 둘째 줄이 첫 줄에 답한다. 같은 seed 면 늘 같다.""" + sets = _COPY.get(_moon_key(day) if post_type is PostType.MOON else post_type.name) + if not sets: + return [] + rng = random.Random(seed) + pick = rng.choice(sets) + return [(bot, body) for bot, body in pick[: rng.randint(1, len(pick))]] + + +async def fill_bot_comments(day: date, crud: FeedCRUD) -> ErrorType: + """그날 포스트 중 캐릭터 댓글이 없는 것에 단다. 여러 번 불러도 한 번만 달린다.""" + err, posts = await DB_SESSION_MNG.execute_lambda(lambda s: crud.without_bot(s, day)) + if err is not ErrorType.SUCCESS: + return err + lines = {p.post_id: bot_lines(PostType(p.post_type), p.feed_date, p.post_id) for p in posts or []} + lines = {post_id: x for post_id, x in lines.items() if x} + err = await DB_SESSION_MNG.execute_lambda_run([lambda s: crud.add_bot_comments(s, lines)]) + LOG.info(f"[feed] bot comments {day} posts {len(lines)}: {err.name}") + return err diff --git a/backend/services/feed_service.py b/backend/services/feed_service.py index 3de6aca..e109dd2 100644 --- a/backend/services/feed_service.py +++ b/backend/services/feed_service.py @@ -27,6 +27,7 @@ from router.v1.feed.protocol import ( ) from services.air_service import GRADE_LABEL as AIR_GRADE_LABEL from services.air_service import pm10_grade, pm25_grade +from services.bot_comment import fill_bot_comments from services.calc.day_slot import NIGHT_AFTER_SUNSET, slot_of from services.calc.index_calc import rank_score from services.calc.moon import MoonNight, nearest, night, view_line @@ -315,6 +316,8 @@ async def build_feed_day(day: date, crud: FeedCRUD, season_crud: SeasonCRUD, reg }) err = await DB_SESSION_MNG.execute_lambda_run([lambda s: crud.insert_day(s, rows)]) LOG.info(f"[feed] build {day} posts {len(rows)}: {err.name}") + if err is ErrorType.SUCCESS: + err = await fill_bot_comments(day, crud) return err diff --git a/backend/services/reaction_service.py b/backend/services/reaction_service.py index f651ef6..404e874 100644 --- a/backend/services/reaction_service.py +++ b/backend/services/reaction_service.py @@ -13,6 +13,7 @@ from common.utils.kma_time import kst_midnight, now_kst from crud.feed_crud import FeedCRUD from crud.reaction_crud import ReactionCRUD from crud.region_crud import RegionCRUD +from services.bot_comment import BOT_COLORS, BOT_NAMES from services.talk_service import _LINK, _PHONE COMMENT_MAX = 60 @@ -31,6 +32,7 @@ class CommentView: mood: Optional[str] liked: bool mine: bool + official: bool = False @dataclass @@ -87,6 +89,8 @@ class ReactionService: @staticmethod def _view(c: Comment, nickname: Optional[str], character: Optional[str], color: Optional[str], mood: Optional[str], liked: bool, who: Liker) -> CommentView: + if c.bot is not None: + return CommentView(comment=c, nickname=BOT_NAMES.get(c.bot, "날씨각"), character=c.bot, color=BOT_COLORS.get(c.bot, ANON_COLOR), mood=None, liked=liked, mine=False, official=True) if c.user_id is None: mine = who.user_id is None and c.ip_hash == who.ip_hash return CommentView(comment=c, nickname=f"{c.region_name} 익명" if c.region_name else "익명", character=ANON_CHARACTER, color=ANON_COLOR, mood=None, liked=liked, mine=mine) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index b51c635..124a808 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -73,6 +73,15 @@ def _no_seoul_crawl(monkeypatch): monkeypatch.setattr(week_service, "fetch_seoul_festivals", lambda *a: _async([])) +@pytest.fixture +def no_bot_comments(monkeypatch): + """사람이 단 댓글·좋아요만 세는 테스트용: 포스트를 만들 때 캐릭터 댓글을 달지 않는다 (캐릭터 댓글은 test_bot_comment).""" + import services.feed_service as feed_service + from common.enums import ErrorType + + monkeypatch.setattr(feed_service, "fill_bot_comments", lambda *a: _async(ErrorType.SUCCESS)) + + @pytest.fixture def offline(monkeypatch): """외부 API 를 모두 맑고 잔잔한 가짜 값으로 바꾼다.""" diff --git a/backend/tests/test_anon_like.py b/backend/tests/test_anon_like.py index 2edf9d2..d50a31b 100644 --- a/backend/tests/test_anon_like.py +++ b/backend/tests/test_anon_like.py @@ -4,6 +4,7 @@ from httpx import ASGITransport, AsyncClient from router.router import app REGION = "1144000000" +pytestmark = pytest.mark.usefixtures("no_bot_comments") IP_A = {"X-Forwarded-For": "203.0.113.10"} IP_B = {"X-Forwarded-For": "203.0.113.20"} diff --git a/backend/tests/test_auth_reaction.py b/backend/tests/test_auth_reaction.py index 1cbd838..984adca 100644 --- a/backend/tests/test_auth_reaction.py +++ b/backend/tests/test_auth_reaction.py @@ -4,6 +4,7 @@ from httpx import ASGITransport, AsyncClient from router.router import app REGION = "1144000000" +pytestmark = pytest.mark.usefixtures("no_bot_comments") def client(): diff --git a/backend/tests/test_bot_comment.py b/backend/tests/test_bot_comment.py new file mode 100644 index 0000000..32b8d5b --- /dev/null +++ b/backend/tests/test_bot_comment.py @@ -0,0 +1,82 @@ +from datetime import date, datetime + +import pytest +from httpx import ASGITransport, AsyncClient +from sqlalchemy import text + +from common.database.db_session_manager import DB_SESSION_MNG +from common.enums import PostType +from common.utils.kma_time import KST +from crud.feed_crud import FeedCRUD +from router.router import app +from services.bot_comment import _COPY, BOT_NAMES, _moon_key, bot_lines, fill_bot_comments +from services.feed_service import LINEUP + +DAY = date(2001, 1, 2) + + +def test_every_post_type_has_lines_from_known_characters(): + for t in {x[1] for x in LINEUP} | {PostType.CARD}: + assert bot_lines(t, DAY, 1), t + for sets in _COPY.values(): + for s in sets: + assert 1 <= len(s) <= 2 and len({bot for bot, _ in s}) == len(s) + assert all(bot in BOT_NAMES and 0 < len(body) <= 60 for bot, body in s) + + +def test_lines_are_one_or_two_and_same_for_same_post(): + counts = {len(bot_lines(PostType.GAK, DAY, post_id)) for post_id in range(40)} + assert counts == {1, 2} + assert bot_lines(PostType.GAK, DAY, 7) == bot_lines(PostType.GAK, DAY, 7) + + +def test_moon_lines_follow_full_and_new_moon_nights(): + assert _moon_key(date(2025, 10, 7)) == "MOON_FULL" # 보름 10.07 12:47 + assert _moon_key(date(2024, 4, 8)) == "MOON_NEW" # 삭 04.09 03:21, 그 전날 밤 + assert _moon_key(date(2025, 10, 4)) == "MOON" + full = {body for s in _COPY["MOON_FULL"] for _, body in s} + assert bot_lines(PostType.MOON, date(2025, 10, 7), 3)[0][1] in full + + +@pytest.fixture +async def day_posts(): + async def wipe(): + await DB_SESSION_MNG.execute_lambda_run([ + lambda s: s.execute(text(f"DELETE FROM comment WHERE post_id IN (SELECT post_id FROM post WHERE feed_date = '{DAY}')")), + lambda s: s.execute(text(f"DELETE FROM post WHERE feed_date = '{DAY}'")), + ]) + await wipe() + rows = [{"feed_date": DAY, "position": i, "scope": "00", "post_type": t.value, "ref_type": 1, "published_at": datetime(2001, 1, 2, 3, tzinfo=KST)} + for i, t in enumerate([PostType.WEATHER, PostType.GAK, PostType.MOON, PostType.SUNSET], 1)] + await DB_SESSION_MNG.execute_lambda_run([lambda s: FeedCRUD().insert_day(s, rows)]) + yield + await wipe() + + +async def _counts(): + sql = f"""SELECT p.post_id, p.comment_count, count(c.comment_id) FROM post p LEFT JOIN comment c ON c.post_id = p.post_id AND c.bot IS NOT NULL + WHERE p.feed_date = '{DAY}' GROUP BY p.post_id, p.comment_count ORDER BY p.post_id""" + _, rows = await DB_SESSION_MNG.execute_lambda(lambda s: s.execute(text(sql))) + return [tuple(r) for r in rows.all()] + + +@pytest.mark.anyio +async def test_fill_adds_one_or_two_comments_once_and_counts_them(day_posts): + await fill_bot_comments(DAY, FeedCRUD()) + first = await _counts() + assert len(first) == 4 and all(1 <= n <= 2 and count == n for _, count, n in first) + await fill_bot_comments(DAY, FeedCRUD()) + assert await _counts() == first + + post_id = first[0][0] + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + comments = (await c.get(f"/v1/reaction/post/{post_id}/comment/list")).json()["comments"] + assert comments and all(x["official"] and x["nickname"] in BOT_NAMES.values() and not x["mine"] for x in comments) + + +@pytest.mark.anyio +async def test_feed_build_puts_character_comments_on_new_posts(offline): + async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as c: + feed = (await c.get("/v1/feed", params={"region": "1144000000"})).json() + assert feed["hero_post"]["comment_count"] >= 1 + assert all(p["comment_count"] >= 1 for p in feed["posts"]) diff --git a/backend/tests/test_post_scope.py b/backend/tests/test_post_scope.py index 14df053..57a45d2 100644 --- a/backend/tests/test_post_scope.py +++ b/backend/tests/test_post_scope.py @@ -17,6 +17,7 @@ from router.router import app from services.feed_service import LINEUP, NATIONAL_SCOPE, NATIONAL_TYPES, build_feed_day, feed_day, sido_of SEOUL_A, SEOUL_B, BUSAN = "1111000000", "1114000000", "2611000000" +pytestmark = pytest.mark.usefixtures("no_bot_comments") REGION_CSV = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "seed", "region.csv") diff --git a/frontend/src/b/Sheets.tsx b/frontend/src/b/Sheets.tsx index 05a4d6b..ba32d8c 100644 --- a/frontend/src/b/Sheets.tsx +++ b/frontend/src/b/Sheets.tsx @@ -801,6 +801,7 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o

{c.nickname} + {c.official && 날씨각} {c.body}

@@ -813,7 +814,8 @@ function CommentRow({ c, postId, onNotice }: { c: CommentData; postId: number; o )} - {!c.mine && } + {/* 날씨각 캐릭터 댓글은 운영 문구라 신고·차단 메뉴가 없다 */} + {!c.mine && !c.official && }