"""날씨각 캐릭터(해님·구름·달님)가 포스트를 만들 때 다는 댓글. 문구는 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