astrbot_plugin_private_comp.../temporal_context.py

173 行
6.5 KiB
Python

2026-07-25 01:35:56 +08:00
# -*- coding: utf-8 -*-
"""Build a small, request-scoped description of real-world conversation time."""
from __future__ import annotations
from dataclasses import dataclass
from datetime import datetime, tzinfo
from typing import Any
_DAYPARTS = ((5, "早晨"), (11, "上午"), (13, "中午"), (18, "下午"), (23, "晚上"))
_DELAY_LABELS = {
"immediate": "刚刚",
"recent": "最近",
"same_day": "同一天",
"overnight": "隔夜",
"previous_day": "隔了一天左右",
"few_days": "隔了几天",
"older": "较久以前",
}
def _as_timestamp(value: Any) -> float:
try:
timestamp = float(value)
except (TypeError, ValueError):
return 0.0
if timestamp > 10_000_000_000:
timestamp /= 1000.0
return timestamp if timestamp > 0 else 0.0
def _daypart(hour: int) -> str:
if hour < 5:
return "深夜"
if hour < 8:
return "清晨"
if hour < 12:
return "上午"
if hour < 14:
return "中午"
if hour < 18:
return "下午"
if hour < 23:
return "晚上"
return "深夜"
def _format_delay(seconds: float) -> str:
if seconds < 120:
return "不到 2 分钟"
if seconds < 3600:
return f"约 {max(2, round(seconds / 60))} 分钟"
if seconds < 86400:
return f"约 {max(1, round(seconds / 3600))} 小时"
return f"约 {max(1, round(seconds / 86400))} 天"
def classify_delay(seconds: float, *, crossed_date: bool = False) -> str:
if seconds < 0:
return "unknown"
if seconds <= 120:
return "immediate"
if seconds <= 1800:
return "recent"
if seconds <= 12 * 3600 and not crossed_date:
return "same_day"
if crossed_date and seconds <= 36 * 3600:
return "overnight"
if seconds <= 2 * 86400:
return "previous_day"
if seconds <= 7 * 86400:
return "few_days"
return "older"
@dataclass(frozen=True)
class TemporalContext:
now_ts: float
now_local: datetime
current_daypart: str
event_ts: float
event_time_source: str
last_user_message_at: float
last_companion_message_at: float
reply_delay_seconds: float
delay_label: str
delay_class: str
crossed_date: bool
topic_age_seconds: float
topic_age_label: str
topic_stale: bool
should_acknowledge_delay: bool
def extract_event_timestamp(event: Any, fallback_ts: float) -> tuple[float, str]:
candidates: list[tuple[Any, str]] = []
for attr in ("timestamp", "event_timestamp", "message_timestamp", "_private_companion_inbound_ts"):
candidates.append((getattr(event, attr, None), f"event.{attr}"))
message_obj = getattr(event, "message_obj", None)
for obj, prefix in ((message_obj, "message_obj"), (getattr(message_obj, "raw_message", None), "raw_message")):
if isinstance(obj, dict):
for key in ("time", "timestamp", "message_time", "event_time"):
candidates.append((obj.get(key), f"{prefix}.{key}"))
elif obj is not None:
for attr in ("time", "timestamp", "message_time", "event_time"):
candidates.append((getattr(obj, attr, None), f"{prefix}.{attr}"))
for value, source in candidates:
timestamp = _as_timestamp(value)
if timestamp:
return timestamp, source
return _as_timestamp(fallback_ts), "received_at_estimated"
def build_temporal_context(
*,
now_ts: float,
local_tz: tzinfo,
event: Any = None,
user: dict[str, Any] | None = None,
) -> TemporalContext:
user = user if isinstance(user, dict) else {}
now_ts = _as_timestamp(now_ts)
now_local = datetime.fromtimestamp(now_ts, local_tz)
event_ts, event_source = extract_event_timestamp(event, now_ts)
last_user = _as_timestamp(user.get("last_user_message_at"))
last_companion = _as_timestamp(user.get("last_companion_message_at"))
anchor = last_companion or _as_timestamp(user.get("last_sent"))
delay_seconds = max(0.0, event_ts - anchor) if anchor else 0.0
anchor_local = datetime.fromtimestamp(anchor, local_tz) if anchor else None
crossed_date = bool(anchor_local and anchor_local.date() != now_local.date())
delay_class = classify_delay(delay_seconds, crossed_date=crossed_date) if anchor else "unknown"
topic_stale = delay_class in {"overnight", "previous_day", "few_days", "older"}
should_ack = delay_class in {"overnight", "previous_day", "few_days", "older"}
return TemporalContext(
now_ts=now_ts,
now_local=now_local,
current_daypart=_daypart(now_local.hour),
event_ts=event_ts,
event_time_source=event_source,
last_user_message_at=last_user,
last_companion_message_at=last_companion,
reply_delay_seconds=delay_seconds,
delay_label=_format_delay(delay_seconds) if anchor else "未知",
delay_class=delay_class,
crossed_date=crossed_date,
topic_age_seconds=delay_seconds,
topic_age_label=_format_delay(delay_seconds) if anchor else "未知",
topic_stale=topic_stale,
should_acknowledge_delay=should_ack,
)
def format_temporal_prompt(context: TemporalContext, *, is_group: bool = False) -> str:
lines = [
"【现实时间与回复间隔】",
f"当前时间:{context.now_local.strftime('%Y-%m-%d %H:%M')}({context.current_daypart})",
f"本条消息时间来源:{'平台消息时间' if context.event_time_source != 'received_at_estimated' else '接收时间估算'}",
]
if context.last_companion_message_at:
lines.extend(
[
f"距离上一条她的消息:{context.delay_label}",
f"时间状态:{_DELAY_LABELS.get(context.delay_class, '未知')}",
f"是否跨日:{'是' if context.crossed_date else '否'}",
]
)
if context.topic_stale:
lines.append("旧话题提示:天气、身体、地点、正在等待等短期状态可能已经变化,先确认现在情况;项目、创作和长期计划可以继续承接。")
if context.should_acknowledge_delay and not is_group:
lines.append("表达规则:如果是在继续她之前主动提起的话题,可以自然使用“昨晚”“后来”“现在”等时间词,轻轻承认等待,不要机械责怪或每次都说“你怎么这么晚才回复”。")
else:
lines.append("没有可靠的上一条她的消息时间,不要编造具体等待时长;只依据当前消息和当前时间回复。")
return "\n".join(lines)