style: 格式化代码

This commit is contained in:
John Richard
2025-10-02 19:38:39 +08:00
parent d5627b0661
commit ecb02cae31
111 changed files with 2344 additions and 2316 deletions

View File

@@ -1,33 +1,33 @@
from src.common.logger import get_logger
#from ..hfc_context import HfcContext
# from ..hfc_context import HfcContext
logger = get_logger("notification_sender")
class NotificationSender:
@staticmethod
async def send_goodnight_notification(context): # type: ignore
async def send_goodnight_notification(context): # type: ignore
"""发送晚安通知"""
#try:
#from ..proactive.events import ProactiveTriggerEvent
#from ..proactive.proactive_thinker import ProactiveThinker
#event = ProactiveTriggerEvent(source="sleep_manager", reason="goodnight")
#proactive_thinker = ProactiveThinker(context, context.chat_instance.cycle_processor)
#await proactive_thinker.think(event)
#except Exception as e:
#logger.error(f"发送晚安通知失败: {e}")
# try:
# from ..proactive.events import ProactiveTriggerEvent
# from ..proactive.proactive_thinker import ProactiveThinker
# event = ProactiveTriggerEvent(source="sleep_manager", reason="goodnight")
# proactive_thinker = ProactiveThinker(context, context.chat_instance.cycle_processor)
# await proactive_thinker.think(event)
# except Exception as e:
# logger.error(f"发送晚安通知失败: {e}")
@staticmethod
async def send_insomnia_notification(context, reason: str): # type: ignore
async def send_insomnia_notification(context, reason: str): # type: ignore
"""发送失眠通知"""
#try:
#from ..proactive.events import ProactiveTriggerEvent
#from ..proactive.proactive_thinker import ProactiveThinker
# try:
# from ..proactive.events import ProactiveTriggerEvent
# from ..proactive.proactive_thinker import ProactiveThinker
#event = ProactiveTriggerEvent(source="sleep_manager", reason=reason)
#proactive_thinker = ProactiveThinker(context, context.chat_instance.cycle_processor)
#await proactive_thinker.think(event)
#except Exception as e:
#logger.error(f"发送失眠通知失败: {e}")
# event = ProactiveTriggerEvent(source="sleep_manager", reason=reason)
# proactive_thinker = ProactiveThinker(context, context.chat_instance.cycle_processor)
# await proactive_thinker.think(event)
# except Exception as e:
# logger.error(f"发送失眠通知失败: {e}")

View File

@@ -1,6 +1,6 @@
import asyncio
import random
from datetime import datetime, timedelta, date
from datetime import datetime, timedelta
from typing import Optional, TYPE_CHECKING
from src.common.logger import get_logger
@@ -21,6 +21,7 @@ class SleepManager:
它实现了一个状态机,根据预设的时间表、睡眠压力和随机因素,
在不同的睡眠状态(如清醒、准备入睡、睡眠、失眠)之间进行切换。
"""
def __init__(self):
"""
初始化睡眠管理器。
@@ -97,7 +98,7 @@ class SleepManager:
logger.info(f"进入理论休眠时间 '{activity}',开始进行睡眠决策...")
else:
logger.info("进入理论休眠时间,开始进行睡眠决策...")
if global_config.sleep_system.enable_flexible_sleep:
# --- 新的弹性睡眠逻辑 ---
if wakeup_manager:
@@ -112,7 +113,7 @@ class SleepManager:
pressure_diff = (pressure_threshold - sleep_pressure) / pressure_threshold
# 延迟分钟数,压力越低,延迟越长
delay_minutes = int(pressure_diff * max_delay_minutes)
# 确保总延迟不超过当日最大值
remaining_delay = max_delay_minutes - self.context.total_delayed_minutes_today
delay_minutes = min(delay_minutes, remaining_delay)
@@ -151,9 +152,10 @@ class SleepManager:
if wakeup_manager and global_config.sleep_system.enable_pre_sleep_notification:
asyncio.create_task(NotificationSender.send_goodnight_notification(wakeup_manager.context))
self.context.current_state = SleepState.SLEEPING
def _handle_preparing_sleep(self, now: datetime, is_in_theoretical_sleep: bool, wakeup_manager: Optional["WakeUpManager"]):
def _handle_preparing_sleep(
self, now: datetime, is_in_theoretical_sleep: bool, wakeup_manager: Optional["WakeUpManager"]
):
"""处理“准备入睡”状态下的逻辑。"""
# 如果在准备期间离开了理论睡眠时间,则取消入睡
if not is_in_theoretical_sleep:
@@ -166,16 +168,22 @@ class SleepManager:
logger.info("睡眠缓冲期结束,正式进入休眠状态。")
self.context.current_state = SleepState.SLEEPING
self._last_fully_slept_log_time = now.timestamp()
# 设置一个随机的延迟,用于触发“睡后失眠”检查
delay_minutes_range = global_config.sleep_system.insomnia_trigger_delay_minutes
delay_minutes = random.randint(delay_minutes_range[0], delay_minutes_range[1])
self.context.sleep_buffer_end_time = now + timedelta(minutes=delay_minutes)
logger.info(f"已设置睡后失眠检查,将在 {delay_minutes} 分钟后触发。")
self.context.save()
def _handle_sleeping(self, now: datetime, is_in_theoretical_sleep: bool, activity: Optional[str], wakeup_manager: Optional["WakeUpManager"]):
def _handle_sleeping(
self,
now: datetime,
is_in_theoretical_sleep: bool,
activity: Optional[str],
wakeup_manager: Optional["WakeUpManager"],
):
"""处理“正在睡觉”状态下的逻辑。"""
# 如果理论睡眠时间结束,则自然醒来
if not is_in_theoretical_sleep:
@@ -198,14 +206,16 @@ class SleepManager:
if insomnia_reason:
self.context.current_state = SleepState.INSOMNIA
# 设置失眠的持续时间
duration_minutes_range = global_config.sleep_system.insomnia_duration_minutes
duration_minutes = random.randint(*duration_minutes_range)
self.context.sleep_buffer_end_time = now + timedelta(minutes=duration_minutes)
# 发送失眠通知
asyncio.create_task(NotificationSender.send_insomnia_notification(wakeup_manager.context, insomnia_reason))
asyncio.create_task(
NotificationSender.send_insomnia_notification(wakeup_manager.context, insomnia_reason)
)
logger.info(f"进入失眠状态 (原因: {insomnia_reason}),将持续 {duration_minutes} 分钟。")
else:
# 睡眠压力正常,不触发失眠,清除检查时间点

View File

@@ -25,6 +25,7 @@ class SleepContext:
"""
睡眠上下文,负责封装和管理所有与睡眠相关的状态,并处理其持久化。
"""
def __init__(self):
"""初始化睡眠上下文,并从本地存储加载初始状态。"""
self.current_state: SleepState = SleepState.AWAKE
@@ -83,4 +84,4 @@ class SleepContext:
logger.info(f"成功从本地存储加载睡眠上下文: {state}")
except Exception as e:
logger.warning(f"加载睡眠上下文失败,将使用默认值: {e}")
logger.warning(f"加载睡眠上下文失败,将使用默认值: {e}")

View File

@@ -15,23 +15,25 @@ class TimeChecker:
self._daily_sleep_offset: int = 0
self._daily_wake_offset: int = 0
self._offset_date = None
def _get_daily_offsets(self):
"""获取当天的睡眠和起床时间偏移量,每天生成一次"""
today = datetime.now().date()
# 如果是新的一天,重新生成偏移量
if self._offset_date != today:
sleep_offset_range = global_config.sleep_system.sleep_time_offset_minutes
wake_offset_range = global_config.sleep_system.wake_up_time_offset_minutes
# 生成 ±offset_range 范围内的随机偏移量
self._daily_sleep_offset = random.randint(-sleep_offset_range, sleep_offset_range)
self._daily_wake_offset = random.randint(-wake_offset_range, wake_offset_range)
self._offset_date = today
logger.debug(f"生成新的每日偏移量 - 睡觉时间偏移: {self._daily_sleep_offset}分钟, 起床时间偏移: {self._daily_wake_offset}分钟")
logger.debug(
f"生成新的每日偏移量 - 睡觉时间偏移: {self._daily_sleep_offset}分钟, 起床时间偏移: {self._daily_wake_offset}分钟"
)
return self._daily_sleep_offset, self._daily_wake_offset
@staticmethod
@@ -82,28 +84,36 @@ class TimeChecker:
try:
start_time_str = global_config.sleep_system.fixed_sleep_time
end_time_str = global_config.sleep_system.fixed_wake_up_time
# 获取当天的偏移量
sleep_offset, wake_offset = self._get_daily_offsets()
# 解析基础时间
base_start_time = datetime.strptime(start_time_str, "%H:%M")
base_end_time = datetime.strptime(end_time_str, "%H:%M")
# 应用偏移量
actual_start_time = (base_start_time + timedelta(minutes=sleep_offset)).time()
actual_end_time = (base_end_time + timedelta(minutes=wake_offset)).time()
logger.debug(f"固定睡眠时间检查 - 基础时间: {start_time_str}-{end_time_str}, "
f"偏移后时间: {actual_start_time.strftime('%H:%M')}-{actual_end_time.strftime('%H:%M')}, "
f"当前时间: {now_time.strftime('%H:%M')}")
logger.debug(
f"固定睡眠时间检查 - 基础时间: {start_time_str}-{end_time_str}, "
f"偏移后时间: {actual_start_time.strftime('%H:%M')}-{actual_end_time.strftime('%H:%M')}, "
f"当前时间: {now_time.strftime('%H:%M')}"
)
if actual_start_time <= actual_end_time:
if actual_start_time <= now_time < actual_end_time:
return True, f"固定睡眠时间(偏移后: {actual_start_time.strftime('%H:%M')}-{actual_end_time.strftime('%H:%M')})"
return (
True,
f"固定睡眠时间(偏移后: {actual_start_time.strftime('%H:%M')}-{actual_end_time.strftime('%H:%M')})",
)
else:
if now_time >= actual_start_time or now_time < actual_end_time:
return True, f"固定睡眠时间(偏移后: {actual_start_time.strftime('%H:%M')}-{actual_end_time.strftime('%H:%M')})"
return (
True,
f"固定睡眠时间(偏移后: {actual_start_time.strftime('%H:%M')}-{actual_end_time.strftime('%H:%M')})",
)
except ValueError as e:
logger.error(f"固定的睡眠时间格式不正确,请使用 HH:MM 格式: {e}")
return False, None
return False, None

View File

@@ -1,4 +1,3 @@
import time
from src.common.logger import get_logger
from src.manager.local_store_manager import local_storage
@@ -9,6 +8,7 @@ class WakeUpContext:
"""
唤醒上下文,负责封装和管理所有与唤醒相关的状态,并处理其持久化。
"""
def __init__(self):
"""初始化唤醒上下文,并从本地存储加载初始状态。"""
self.wakeup_value: float = 0.0
@@ -42,4 +42,4 @@ class WakeUpContext:
"sleep_pressure": self.sleep_pressure,
}
local_storage[self._get_storage_key()] = state
logger.debug(f"已将唤醒上下文保存到本地存储: {state}")
logger.debug(f"已将唤醒上下文保存到本地存储: {state}")

View File

@@ -3,7 +3,6 @@ import time
from typing import Optional, TYPE_CHECKING
from src.common.logger import get_logger
from src.config.config import global_config
from src.manager.local_store_manager import local_storage
from src.chat.message_manager.sleep_manager.wakeup_context import WakeUpContext
if TYPE_CHECKING:
@@ -51,7 +50,7 @@ class WakeUpManager:
if not self.enabled:
logger.info("唤醒度系统已禁用,跳过启动")
return
self.is_running = True
if not self._decay_task or self._decay_task.done():
self._decay_task = asyncio.create_task(self._decay_loop())
@@ -88,6 +87,7 @@ class WakeUpManager:
self.context.is_angry = False
# 通知情绪管理系统清除愤怒状态
from src.mood.mood_manager import mood_manager
if self.angry_chat_id:
mood_manager.clear_angry_from_wakeup(self.angry_chat_id)
self.angry_chat_id = None
@@ -104,7 +104,9 @@ class WakeUpManager:
logger.debug(f"唤醒度衰减: {old_value:.1f} -> {self.context.wakeup_value:.1f}")
self.context.save()
def add_wakeup_value(self, is_private_chat: bool, is_mentioned: bool = False, chat_id: Optional[str] = None) -> bool:
def add_wakeup_value(
self, is_private_chat: bool, is_mentioned: bool = False, chat_id: Optional[str] = None
) -> bool:
"""
增加唤醒度值
@@ -173,6 +175,7 @@ class WakeUpManager:
# 通知情绪管理系统进入愤怒状态
from src.mood.mood_manager import mood_manager
mood_manager.set_angry_from_wakeup(chat_id)
# 通知SleepManager重置睡眠状态
@@ -194,6 +197,7 @@ class WakeUpManager:
self.context.is_angry = False
# 通知情绪管理系统清除愤怒状态
from src.mood.mood_manager import mood_manager
if self.angry_chat_id:
mood_manager.clear_angry_from_wakeup(self.angry_chat_id)
self.angry_chat_id = None