feat: remove ops entertainment integrations

这个提交存在于:
YokiiroBW 2026-07-26 01:32:07 +08:00
父节点 6afa64bb51
当前提交 f4d160ce86
共有 19 个文件被更改,包括 1011 次插入 和 12954 次删除

文件差异内容过多而无法显示 加载差异

查看文件

@ -2862,7 +2862,6 @@ class CommandHandlersMixin:
"private_image.py",
"group_wakeup.py",
"group_observation.py",
"qzone_integration.py",
"tts_enhancement.py",
"token_budget.py",
)

查看文件

@ -12962,9 +12962,10 @@ class DailyStateMixin:
]
state = self.data.get("daily_state", {})
if isinstance(state, dict) and state.get("date") == plan_date:
lines.append(
f"\u72b6\u6001\uff1a\u80fd\u91cf {state.get('energy', 70)}/100\uff5c\u60c5\u7eea\u504f{state.get('mood_bias', '\u5e73\u7a33')}\uff5c{state.get('sleep', '\u7761\u7720\u5e73\u7a33')}"
)
energy = state.get("energy", 70)
mood_bias = state.get("mood_bias", "平稳")
sleep_state = state.get("sleep", "睡眠平稳")
lines.append(f"状态:能量 {energy}/100|情绪偏{mood_bias}|{sleep_state}")
status_labels = {
"planned": "\u8ba1\u5212\u4e2d",
"active": "\u8fdb\u884c\u4e2d",
@ -13589,13 +13590,7 @@ class DailyStateMixin:
for label, task_factory in (
("统一日程窗口结算", self._agenda_maintenance_tick),
("技能成长结算", self._maybe_settle_skill_growth),
("B站无聊观看", self._maybe_trigger_bilibili_boredom_watch),
("网页探索", self._maybe_trigger_web_exploration),
("AI日报追踪", self._maybe_track_ai_daily),
("新闻无聊阅读", self._maybe_trigger_news_boredom_read),
("夹层无聊阅读", self._maybe_trigger_jm_cosmos_boredom_read),
("QQ空间生活说说", self._maybe_publish_qzone_life_post),
("QQ空间评论收件箱", self._maybe_process_qzone_comment_inbox),
("夹层推荐请求", self._maybe_schedule_private_reading_recommendation_request),
):
try:
@ -13642,8 +13637,6 @@ class DailyStateMixin:
if isinstance(runtime, dict):
runtime["generation_disabled"] = False
runtime["generation_disabled_reason"] = ""
if self._maybe_schedule_bilibili_video_share():
self._save_data_sync()
users = list(self.data.get("users", {}).items())
for user_id, user in users:

查看文件

@ -0,0 +1,626 @@
# OPS 陪伴插件全功能盘点与删减评估
## 1. 评估范围
目标项目:运维分支 `ops-main` 的 `astrbot_plugin_private_companion_ops`。
本次评估不是普通陪伴版的功能规划,而是针对群晖 VM 运维智能体的陪伴层:
- Bot 需要有人格、现实时间、日程和自我时间线;
- Bot 需要记住用户的真实事实,但不能污染用户记忆;
- Bot 需要协助 NAS、VM、代码、故障排查和长期项目;
- Bot 的主动消息必须服务于提醒、跟进、运维状态和陪伴,而不是随机娱乐;
- 私密阅读和长期创作明确保留;
- 外部娱乐内容、社交展示和无关主动消费应从 OPS 分支剥离。
源码依据:
- `astrbot_plugin_private_companion-main/main.py`
- `astrbot_plugin_private_companion-main/_conf_schema.json`
- `astrbot_plugin_private_companion-main/command_handlers.py`
- `astrbot_plugin_private_companion-main/page_api.py`
- `astrbot_plugin_private_companion-main/README.md`
- `astrbot_plugin_private_companion-main/metadata.yaml`
- `astrbot_plugin_private_companion-main/docs/前端改造要求-Q6-Bot自有存储与用户记忆边界.md`
- `astrbot_plugin_private_companion-main/docs/Q7后端接口收口与VM验收记录.md`
当前主类仍组合了大量能力,包括日程、记忆、主动消息、群聊、图片、QQ 空间、新闻、创作、私密阅读、TTS 和外部工具,因此不能只删除一个配置开关就认为模块已经删除。
## 2. 结论先说
### 不建议删除:运维核心
这些能力构成 OPS 陪伴层的骨架:
- AstrBot 生命周期、配置迁移、运行时兼容和插件状态;
- JSON/SQLite 存储抽象和 Bot 自有存储边界;
- 现实时间、日历、双层日程、时间窗口、计划/实际对账;
- Bot 人格状态、自我时间线和主动行为审计;
- 用户身份、关系边界、用户事实和用户记忆 Bridge;
- 记忆插件协同,但只允许用户数据进入外部记忆;
- 运维提醒、主动消息限流、免打扰、休息、失败解释和发送前审核;
- Token 预算、余额感知、模型状态和插件排障;
- 私密阅读;
- 长期创作;
- 作为运维知识边界的 Worldbook/身份资料;
- 必要的文本、转发和图片输入理解能力。
### 建议删除:确定属于娱乐或外部社交展示的能力
这些能力与 NAS/VM 运维目标没有直接关系,且会带来外部账号、网络、Cookie、模型消耗和后台任务:
- QQ 空间自动发布、动态、评论收件箱和配图发布;
- B 站无聊监测、内容读取和主动分享;
- 新闻热榜、AI 日报、新闻无聊阅读和新闻主动分享;
- 无聊时主动网页搜索和搜索结果分享;
- “吃什么”菜单推荐和饭点娱乐化关心;
- 每日穿搭、自拍、生活照和主动生成图片分享;
- 以娱乐为目的的外部内容自动消费;
- 仅用于增加热闹感的群聊唤醒、插话和重复跟随;
- 旧 LivingMemory 专用兼容路径,如果运维环境已经统一使用 Memory Companion。
### 可选删除:取决于 VM 的实际使用方式
这些功能不是核心运维能力,但可能在特定使用方式下有价值:
- 群聊观察和群成员关系网;
- 跨群转述和 `AtRelay`;
- TTS、语音主动消息和本地语音播放;
- 识屏、戳一戳、语音动作等平台动作;
- 梦境、梦境碎片和 Bot 日记;
- QQ 在线状态同步;
- 食物、健康、周期、饥饿等拟人化状态;
- 技能成长模拟和表达学习;
- 个人目标系统;
- 书柜备忘便签;
- 复杂群聊 LLM、群唤醒、黑话学习和群关系图。
建议初始 OPS 配置关闭这些可选项,运行一段时间后根据真实使用再决定是否物理删除。
## 3. 全功能盘点
### 3.1 平台基础与运行维护 —— 不建议删除
对应源码:`core_store.py`、`runtime_compat.py`、`platform_compat.py`、`integration_status.py`、`config_migration.py`、`main.py`。
功能:
- AstrBot 插件加载、卸载、重载和生命周期处理;
- 配置读取、旧版配置迁移和分组配置兼容;
- JSON 主存储和可选 SQLite 后端;
- 数据默认值、存储修复、历史压缩和控制标签清理;
- 平台能力探测和降级;
- 页面 API 注册、运行状态和诊断信息;
- 服务重启后的数据恢复。
判断:必须保留。它们不是业务娱乐,而是所有 OPS 功能的运行底座。
### 3.2 现实时间、日历与日程 —— 不建议删除
对应源码:`calendar_system.py`、`agenda_contracts.py`、`agenda_runtime.py`、`schedule_reconciler.py`、`unified_agenda.py`、`planning.py`、`temporal_context.py`、`daily_state.py`。
功能:
- 现实日期、时区和带时区时间;
- Bot 自己的每日计划;
- 计划项、实际活动、时间窗口快照;
- 延期、取消、部分完成和未知状态;
- 计划与实际活动对账;
- 当前时间段、上一段和下一段上下文;
- 对话延迟和跨日回复感知;
- 日程对 Bot 回复时机、主动提醒和状态的影响;
- Bot 自有日程历史。
判断:必须保留,是 OPS 陪伴层最重要的区别之一。后续数据库优化也应优先服务这一组数据。
### 3.3 Bot 人格、状态与自我时间线 —— 不建议删除,但要去掉娱乐依赖
对应源码:`bot_self_store.py`、`self_timeline.py`、`state_views.py`、`scene_context.py`、`daily_state.py`、`astrbot_knowledge.py`。
功能:
- Bot 自有记忆和自我时间线;
- Bot 人格状态;
- Bot 做过什么、计划过什么、创作过什么;
- 当前忙碌、休息、精力和情绪上下文;
- 环境、平台、模型和当前任务感知;
- Bot 不能把自己的数据写入用户记忆插件。
判断:保留。需要删除的是其中的娱乐化数据源,而不是自我时间线本身。
建议拆分:
- 保留:任务、运维事件、代码项目、创作、阅读、提醒、状态变化;
- 可选:梦境、饭点、穿搭、周期、饥饿、纯情绪日记;
- 删除:由 B 站、新闻、QQ 空间等娱乐源制造的 Bot “见闻”。
### 3.4 用户身份、关系与用户记忆 —— 不建议删除
对应源码:`user_memory.py`、`memory_companion_adapter.py`、`remember_you_adapter.py`、`worldbook.py`、`interaction_utils.py`。
功能:
- 主要用户/次要用户区分;
- 用户 ID、平台身份和跨平台别名;
- 用户称呼、语气和关系阶段;
- 用户事实、习惯、关系观察和未完话题;
- 用户侧图片摘要;
- 通过运维记忆插件召回用户记忆;
- 记忆写入主体、时间、来源和边界保护;
- 群成员和联系人身份资料。
判断:必须保留。OPS 不是只会执行命令的工具,它仍然需要理解操作者是谁、之前做了什么和当前任务的上下文。
硬性边界:
- 用户数据进入记忆插件;
- Bot 日程、人格、创作、梦境和自我时间线不进入记忆插件;
- 不恢复旧的 Bot 数据外写降级通道;
- LivingMemory 只保留兼容迁移所需的只读检测,后续可以删除专用适配。
### 3.5 私聊陪伴和被动回复 —— 不建议删除
对应源码:`event_dispatch.py`、`prompt_surface.py`、`busy_reply_gate.py`、`user_rest_gate.py`、`temporal_context.py`、`forward_message.py`、`segmented_message.py`。
功能:
- 私聊上下文组装;
- 根据现实时间、任务、关系和状态回复;
- 休息、免打扰、忙碌和延迟回复;
- 过长消息、转发消息和图片消息处理;
- 回复前事实、隐私、平台和发送结果检查;
- 失败原因和未发送原因解释;
- 延迟较久后重新接续对话,而不是机械重复旧话题。
判断:必须保留,但要把随机闲聊和娱乐内容来源清理掉。
### 3.6 主动消息和运维提醒 —— 保留并改造
对应源码:`proactive.py`、`proactive_engine.py`、`proactive_message.py`、`proactive_chat_runtime_bridge.py`、`proactive.py`、`command_handlers.py`。
功能:
- 主动消息候选生成;
- 用户未回复后的降速和停止;
- 日程提醒、任务跟进和到期提醒;
- 运维事件、服务异常和代码任务提醒;
- 主动消息审核、风险拦截、Token 限额和发送审计;
- 与 Proactive Chat 的运行时桥接;
- 文本、图片、语音、戳一戳等多种发送动作。
判断:保留核心,但必须做来源删减。
保留的主动来源:
- Bot 日程;
- 运维任务;
- VM/NAS 事件;
- 用户明确交代的待办;
- 长期创作推进;
- 私密阅读进度;
- 用户长时间未回复时的低频关心;
- 明确的故障或安全提醒。
删除的主动来源:
- 无聊时看 B 站;
- 无聊时看新闻;
- 无聊时搜索网页;
- QQ 空间发动态;
- 每日穿搭和自拍;
- 吃什么候选;
- 仅为了制造热闹的群聊插话。
### 3.7 运维诊断、模型和成本控制 —— 不建议删除
对应源码:`token_budget.py`、`balance_awareness.py`、`integration_status.py`、`page_api.py`、`command_handlers.py`。
功能:
- Provider 和模型状态;
- Token 使用统计、预算和硬限制;
- 余额查询和余额不足提醒;
- 主动行为审计;
- 配置导出、导入、备份和恢复;
- 页面接口、排障接口和能力列表;
- 插件状态、依赖、Bridge 和降级状态。
判断:必须保留。OPS 环境的重点就是稳定运行、成本可控和故障可解释。
### 3.8 图片和视觉能力 —— 拆分保留
对应源码:`private_image.py`、`llm_tool_actions.py`、`qzone_media.py`、`pages/陪伴面板`。
不建议删除:
- 用户发送截图、报错图、NAS 面板截图时的图片理解;
- 图片摘要和短期视觉上下文;
- 运维图片证据的来源和时间记录;
- 私密阅读中必要的图片读取。
建议删除:
- 自拍和每日穿搭生成;
- 纯娱乐图片分享;
- QQ 空间自动配图;
- 与运维无关的自然语言生图入口。
可选删除:
- 识屏主动窥视;
- Poke、自动语音等平台动作;
- 外部图片 API 的备用链路。
### 3.9 TTS 与语音 —— 可选删除
对应源码:`tts_enhancement.py`、`tts_tool_sanitizer.py`、`voice_action_config` 相关配置。
保留价值:
- 运维告警通过语音播放;
- 用户在不方便阅读时接收提醒;
- 语音输入后的统一处理。
删除理由:
- 增加模型、音频缓存和平台适配复杂度;
- 对 NAS 运维不是硬依赖;
- 语音主动消息容易扩大主动行为噪声。
建议:初始关闭,保留模块;如果 VM 只使用文字运维,可在第二轮物理删除。
### 3.10 私密阅读 —— 不建议删除
对应源码:`private_reading.py`、`page_api.py` 的书柜和阅读接口、`_conf_schema.json` 中的 `enable_private_reading_*`。
功能:
- 私密阅读目录和夹层数据;
- 阅读进度、偏好和标签;
- 阅读内容在 Bot 自有上下文中的影响;
- 私密阅读与主要用户边界;
- 阅读状态和长期创作的灵感关联。
判断:用户已经明确要求保留,不能按娱乐模块删除。后续只需清理无聊自动阅读和不必要的主动推荐开关。
建议默认:
- 保留阅读数据和偏好影响;
- 关闭无聊时自动阅读;
- 关闭无明确请求的推荐;
- 保留用户主动查询和阅读进度追踪。
### 3.11 长期创作 —— 不建议删除
对应源码:`creative.py`、`page_api.py` 创作接口、`creative_projects` 和 `creative_memory_pool`。
功能:
- 长期创作项目;
- 大纲、角色、章节、草稿块和创作记忆;
- 项目阶段、版本和复盘;
- 创作上下文注入;
- 创作与 Bot 自我时间线关联;
- 作品封面生成和创作分享。
判断:核心保留。需要删减的是娱乐化的自动分享和无聊灵感触发,不是创作数据本身。
建议默认:
- 保留项目、草稿、大纲和复盘;
- 关闭无聊时自动开始新项目;
- 关闭自动公开分享;
- 封面生成设为可选,不作为核心依赖。
### 3.12 日记、梦境和拟人化生活 —— 可选删除
对应源码:`dreaming.py`、`daily_state.py`、`main.py` 中的 diary/dream 配置和命令。
保留价值:
- 为 Bot 自我时间线提供连续性;
- 让 Bot 在长期互动中有自我状态;
- 记录运维任务之外的休息和复盘。
删除或收缩理由:
- 梦境、穿搭、饥饿、周期和健康模拟与 NAS 运维没有直接关系;
- 会增加模型调用、数据量和人格噪声;
- 容易与用户真实记忆混淆。
建议方案:
- 保留轻量 Bot 日记和任务复盘;
- 删除增强梦境、亲密梦境和梦境外部分享;
- 删除每日穿搭;
- 饥饿、周期、健康等状态只保留睡眠、精力、忙碌和休息四类;
- 不把这些内容写入用户记忆插件。
### 3.13 群聊观察与群聊陪伴 —— 可选删除,不能直接整体删除
对应源码:`group_observation.py`、`group_wakeup.py`、`page_api_users_groups.py`、`worldbook.py`。
保留价值:
- 如果运维群是主要控制入口,群观察可以识别故障上下文;
- 群成员身份和权限边界可以防止误执行;
- 群话题和事件线可以辅助判断运维任务是否已完成。
建议保留:
- 群消息观察;
- 群成员身份和权限;
- 群隐私保护;
- 群中明确的运维任务和故障上下文。
建议删除:
- 群聊娱乐唤醒;
- 冷群主动找话题;
- 无关插话;
- 黑话网页搜索;
- 纯热闹型重复跟随。
如果 VM 实际只使用单人私聊,第二轮可以整组删除 `GroupWakeupMixin` 和大部分群聊主动逻辑,但先不要删除 `GroupObservationMixin`,以免误伤身份和权限判断。
### 3.14 Worldbook、身份资料和关系网 —— 不建议删除
对应源码:`worldbook.py`、`astrbot_knowledge.py`、`AtRelayMixin` 的身份解析部分。
功能:
- 用户、群成员和运维角色身份;
- 别名、平台 ID 和权限边界;
- 待确认观察;
- 群聊成员关系;
- Bot 自我注册和关系资料;
- 运维项目、服务和环境的知识入口。
判断:保留。OPS 需要知道“谁在说什么、对谁可见、谁能触发什么”,这不是娱乐功能。
需要控制:
- 待确认观察不能自动变成硬事实;
- 关系图不应扩大运维权限;
- 不把群成员资料写入外部用户长期记忆;
- World 数据只作为上下文,不直接覆盖现实日程事实。
### 3.15 AtRelay 和跨群转述 —— 可选删除
对应源码:`atrelay.py`、`forward_message.py`、`main.py` 中的 `enable_atrelay_*`。
保留价值:
- 在多个运维群之间转发故障状态;
- 把指定群的处理结果带回主控私聊;
- 统一跨平台身份和消息来源。
删除理由:
- 权限和隐私边界复杂;
- 运维系统初期可能只有一个主控会话;
- 转述错误会造成事实和责任归属混乱。
建议:默认关闭;只有确实存在多个运维群时才保留。
### 3.16 外部娱乐内容和社交发布 —— 建议删除
#### QQ 空间
对应源码:`qzone_integration.py`、`qzone_media.py`、`qzone_selection.py`、`qzone_recent_parser.py`、`page_api_qzone.py`。
删除范围:
- QQ 空间动态读取;
- 自动生活说说;
- 情绪动态;
- 生成图片动态;
- 评论收件箱;
- QQ 空间页面和命令;
- QQ 空间 Cookie、Provider 和后台任务。
判断:OPS 无需对外运营 Bot 社交账号,建议完整删除。
#### B 站
当前主要以 `main.py` 配置、主动来源和外部能力形式存在。
删除范围:
- 无聊时观看;
- 内容评分和主动分享;
- B 站定时抓取和缓存;
- B 站相关页面、配置和 Provider。
判断:建议删除。
#### 新闻、AI 日报和热点
对应源码:`news_exploration.py`、`main.py` 新闻配置、新闻页面和主动触发。
删除范围:
- 新闻源读取;
- 热榜和 AI 日报;
- 无聊时新闻阅读;
- 新闻主动分享;
- 新闻 API、Provider、缓存和定时任务。
判断:建议删除。若未来需要技术资讯,应由单独的运维资讯插件提供,不重新塞回陪伴插件。
#### 主动网页搜索
对应源码:`main.py` 的 `web_exploration_*` 配置、相关上下文和页面。
判断:建议删除陪伴插件内的“无聊搜索”和分享逻辑。真正的运维检索应由专用工具或运维 Agent 调用,保留明确请求的外部查询能力也应放到独立插件。
### 3.17 食物、穿搭和日常娱乐 —— 建议删除
功能包括:
- 吃什么候选;
- 饭点主动关心;
- 每日穿搭照片;
- 生活照分享;
- 生活化娱乐推荐。
对应配置:`enable_food_menu_recommendation`、`enable_meal_care_proactive`、`enable_daily_outfit_photo` 等。
判断:与 OPS 目标无关,建议删除配置、命令、数据字段、后台任务和页面入口。
### 3.18 QQ 状态、Poke、语音动作和识屏主动窥视 —— 可选删除
这些属于平台动作,不是运维核心:
- QQ 在线状态同步;
- Poke;
- 主动语音动作;
- 主动识屏;
- 未回复后的屏幕窥视。
建议:
- 用户主动发送图片/截图时的识图保留;
- 主动窥视、Poke 和状态同步默认关闭;
- 如果 VM 完全不需要 QQ 社交表现,可以第二轮物理删除。
## 4. 需要一起清理的配置和页面
删除娱乐模块时不能只删 Python 文件,还要清理:
- `_conf_schema.json` 中的配置项和旧兼容项;
- `main.py` 的配置读取、默认值、Provider 映射和能力别名;
- `command_handlers.py` 中对应命令;
- `page_api.py` 和 `page_api_qzone.py` 的 API;
- `pages/陪伴面板/index.html` 的页面、Tab、配置卡和诊断卡;
- `pages/陪伴面板/app.js` 的状态、请求和渲染逻辑;
- 后台定时任务、主动候选、缓存和清理逻辑;
- `data` 中不再使用的运行状态字段;
- README、CHANGELOG、metadata 和配置迁移文档;
- 测试、迁移预览和错题本中的旧能力说明。
旧数据不能直接删除,必须先:
1. 统计旧字段数量;
2. 标记来源和所属模块;
3. 对 Bot 自有数据放入 `legacy_quarantine`;
4. 对娱乐缓存做备份后再清理;
5. 确认用户记忆数据库没有被修改;
6. 通过 VM 重启和回滚验收。
## 5. 推荐的 OPS 最终功能边界
### 必须保留
- 人格和现实时间;
- 日历、日程、时间窗口和计划/实际对账;
- Bot 自有存储和自我时间线;
- 用户身份、关系和用户记忆协同;
- 私聊陪伴和时间跨度感知;
- 运维提醒、任务跟进和主动消息审核;
- Token、余额、模型、Bridge 和故障诊断;
- 私密阅读;
- 长期创作;
- 运维知识、Worldbook 和权限边界;
- 用户截图、日志图和错误图片理解;
- 配置、备份、迁移和审计。
### 建议删除
- QQ 空间完整集成;
- B 站主动阅读和分享;
- 新闻、热点、AI 日报;
- 无聊时网页搜索;
- 食物推荐、饭点娱乐关心;
- 每日穿搭、自拍和娱乐生图;
- 外部社交动态和评论收件箱;
- 纯娱乐群聊唤醒和插话。
### 可选删除
- 群聊整体能力;
- AtRelay 跨群转述;
- TTS 和语音动作;
- Poke、QQ 状态同步、主动识屏;
- 梦境和完整 Bot 日记;
- 饥饿、健康、周期等拟人化状态;
- 技能成长和表达学习;
- 个人目标和备忘便签;
- 创作封面生成;
- 外部图片 API 备用链路。
## 6. 建议执行顺序
### OPS-Trim-0:先关闭,不删代码
- 在 VM 配置中关闭确定删除项;
- 关闭所有 boredom/无聊触发;
- 关闭外部社交发布和自动分享;
- 关闭每日穿搭、食物推荐和娱乐主动源;
- 观察主动消息数量、Token 消耗、错误日志和用户体验。
### OPS-Trim-1:删除外部娱乐模块
优先删除:
1. QQ 空间完整链路;
2. B 站链路;
3. 新闻和 AI 日报;
4. 无聊搜索;
5. 食物、穿搭和娱乐图片链路。
### OPS-Trim-2:收缩主动系统
- 只保留日程、运维任务、用户待办、创作和阅读进度来源;
- 删除娱乐候选生成器;
- 删除无聊触发计时器;
- 保留主动审核、限流、免打扰和审计。
### OPS-Trim-3:收缩拟人化模块
- 保留睡眠、精力、忙碌、休息;
- 评估删除饥饿、周期、健康、梦境和穿搭;
- 保留 Bot 自我时间线,但只接收运维、创作、阅读和任务事件。
### OPS-Trim-4:按实际入口处理群聊、语音和跨群转述
- 如果 VM 只用私聊,关闭并评估删除群聊主动模块;
- 如果存在运维群,保留观察和权限边界,删除娱乐插话;
- 根据实际告警场景决定是否保留 TTS 和 AtRelay。
### OPS-Trim-5:统一前端和数据清理
- 按 `前端改造要求-Q6-Bot自有存储与用户记忆边界.md` 改造页面;
- 删除已移除功能的 Tab、配置卡和命令提示;
- 显示“运维能力”和“已关闭/已删除娱乐能力”的边界;
- 清理旧缓存和废弃字段,但保留可回滚备份。
## 7. 最终建议
当前不要直接大规模物理删除。建议先执行 `OPS-Trim-0`,观察一轮真实 VM 运行数据,再按模块拆分删除。
优先级判断:
- 第一批一定删除:QQ 空间、B 站、新闻/AI 日报、无聊搜索、食物推荐、每日穿搭、娱乐生图;
- 第一批一定保留:日程、真实时间、Bot 自有存储、用户记忆边界、私聊陪伴、运维主动提醒、诊断、私密阅读、长期创作;
- 第二批再决定:群聊、TTS、AtRelay、梦境、拟人化身体状态、技能成长、个人目标和备忘便签。
本评估只做盘点和删减方案,不在本轮直接删除源码、配置或 VM 数据。
## 本轮已执行的运维版删减(2026-07-25)
已在 `ops-main` 完成本轮源码删减,范围仅限运维分支:
- 删除 QQ 空间完整链路及页面入口:动态、评论收件箱、自动配图发布、发布接口和独立实现文件。
- 删除新闻、热点、AI 日报、B 站主动阅读/无聊监测/分享、无聊时主动搜索的独立实现入口。
- 删除主动 Poke、QQ 状态同步、主动识屏的启动入口;普通用户主动发送的图片理解不受影响。
- 删除饭点娱乐化关心和“吃什么”配置入口;日程、真实时间、运维提醒、私密阅读、长期创作保留。
- LivingMemory 不再读取数据库、不再进入页面状态和运行时召回;仅保留关闭状态字段,避免旧配置导致启动异常。
- 保留旧数据区的惰性兼容结构,不做数据删除和数据库迁移,确保现有 Bot 自有存储、用户记忆、日程数据可继续启动。
验证结果:
- `python -m compileall -q .` 通过。
- 已扫描 Python/HTML 对已删除模块的导入和页面脚本引用,无结果。
- 本地未安装 `pytest`,基线测试暂未执行;未做 VM 部署和数据删除。

查看文件

@ -153,3 +153,34 @@
- 预防规则:VM 部署后的编译检查必须使用临时字节码目录,不能把活动插件目录的旧缓存权限当成源码编译失败。
- 验证证据:Q7.5 VM 验收中临时字节码目录编译通过;`astrbot.service=active`、`NRestarts=0`。
docs\运维陪伴错题本.md
## 2026-07-25 — OPS 功能删减必须按依赖链处理
- 阶段:OPS 全功能盘点与娱乐模块删减评估
- 类型:功能行为 / API 契约 / 其他
- 现象:单看配置开关容易把 QQ 空间、新闻、图片、主动消息和群聊逻辑误认为可以独立删除,实际它们还连接了页面、Provider、后台任务、命令、缓存和主动候选。
- 根因:陪伴插件采用多个 Mixin 组合,外部娱乐能力与主动系统、图片系统和页面 API 存在交叉依赖。
- 修复或规避:先形成“保留、建议删除、可选删除”清单,删除前按源码、配置、命令、页面、任务、缓存和迁移数据逐项清理;本轮只写评估,不直接删除。
- 预防规则:任何 OPS 功能删减都必须先关闭观察,再做依赖扫描和 VM 回滚方案,不能只删除一个 `enable_*` 配置项。
- 验证证据:已盘点 `main.py` Mixin 组合、`_conf_schema.json` 开关、`command_handlers.py`、`page_api.py`、页面目录和当前 Q6/Q7 边界文档;评估落盘于 `docs/OPS陪伴插件全功能盘点与删减评估.md`。
## 2026-07-25 — 源码批量编辑时的中文编码陷阱
- 阶段:功能删减
- 类型:编码 / 环境
- 现象:Windows PowerShell 默认读取源码后再写回,中文源码被按系统编码误读,造成大范围乱码和语法错误。
- 根因:未显式使用无 BOM UTF-8 读写。
- 修复或规避:回滚受影响文件;后续统一使用 Python `Path.read_text/write_text(encoding="utf-8")` 或 .NET UTF-8 无 BOM。
- 预防规则:涉及中文源码的批量替换必须先做编码探测,并在写回后立即运行 `py_compile`。
- 验证证据:`python -m py_compile main.py page_api.py llm_tool_actions.py` 和 `python -m compileall -q .` 均通过。
## 2026-07-25 — 独立娱乐模块删除后的兼容边界
- 阶段:功能删减
- 类型:功能行为 / API契约
- 现象:QQ 空间和新闻实现被多个主类、页面、命令和配置入口引用,直接删文件会导致插件启动或页面注册失败。
- 根因:功能实现、配置 schema、页面路由和主动调度没有统一边界。
- 修复或规避:先移除 Mixin/导入/路由,再删除独立文件;保留旧数据命名空间但不再执行外部调用;主动动作开关强制关闭。
- 预防规则:删除插件能力必须同时检查导入、Mixin、路由、schema、命令、后台任务和页面脚本。
- 验证证据:独立模块文件已删除;已删除模块导入和 qzone 页面脚本残留扫描无结果;源码编译通过。

查看文件

@ -30,7 +30,6 @@ from .helpers import (
_strip_internal_message_blocks,
)
from .memo_notes import apply_memo_note_action, memo_note_sort_key, normalize_memo_note
from .qzone_selection import parse_qzone_post_selection
PHOTO_TOOL_SILENT_SENTINEL = "[[PC_PHOTO_SENT_NO_FOLLOWUP]]"
@ -195,25 +194,6 @@ class LlmToolActionsMixin:
- 查不到就自然说明没在关系网里确认过,不要编造。
""".strip()
def _qzone_tool_instruction(self, event: AstrMessageEvent | None = None) -> str:
availability = getattr(self, "_qzone_available", None)
if not (self.enabled and self.enable_qzone_integration):
return ""
if callable(availability) and not availability(event):
return ""
instruction = """
【QQ 空间动态工具】
当用户明确要求你查看说说、QQ 空间动态、点赞/评论说说,或要求你发一条说说时,可以使用 Private Companion 的 QQ 空间工具。
- 查看说说:使用 `pc_qzone_view_feed`。不知道目标 QQ 时默认当前用户;可用 `selector` 传“最新”“第2条”“最后”或 fid。
- 发布说说:使用 `pc_qzone_publish_feed`。必须把最终要发布的正文放进 `text` 参数,例如 `{"text":"今天想慢一点。"}`;如需带图,可传 `{"text":"配图说说","images":["本地图片路径或图片URL"]}`;如果用户明确要求“发布刚才/最近生成的生活说说草稿”,可传 `{"use_latest_draft":true}`;不要空调用,不要把草稿当作已发布。
- 用户说“你发的说说/你刚发了什么/我看到你发的动态”时,“你”指 Bot 自己,不是当前用户。优先直接依据下方 Bot 自己的发布记录回答,不要反问用户内容,不要让用户自己去看,也不要用默认目标为当前用户的查看工具偷换对象。
- 发布内容必须服从当前人格与世界观,但不要泄露私聊隐私、内部状态数值、关系网资料或插件实现。
- 工具失败时简短说明失败原因,不要假装已经发布或点赞。
""".strip()
context_getter = getattr(self, "_qzone_recent_self_publish_chat_context", None)
recent_context = context_getter() if callable(context_getter) else ""
return f"{instruction}\n\n{recent_context}".strip() if recent_context else instruction
def _photo_generation_tool_instruction(self) -> str:
if not getattr(self, "enabled", False):
return ""
@ -580,8 +560,6 @@ class LlmToolActionsMixin:
source = function if isinstance(function, dict) else value
name = _single_line(source.get("name") or value.get("tool_name"), 80)
known_names = {
"pc_qzone_view_feed",
"pc_qzone_publish_feed",
"pc_generate_photo",
"pc_find_reaction_image",
"pc_manage_memo",
@ -2260,192 +2238,6 @@ class LlmToolActionsMixin:
ensure_ascii=False,
)
async def _pc_qzone_view_feed_impl(
self,
event: AstrMessageEvent,
user_id: str = "",
pos: int = 0,
like: bool = False,
reply: bool = False,
selector: str = "",
fid: str = "",
) -> str:
availability = getattr(self, "_qzone_available", None)
if callable(availability) and not availability(event):
supported = getattr(self, "_qzone_platform_supported", None)
if callable(supported) and not supported(event):
message_getter = getattr(self, "_qzone_platform_unavailable_message", None)
message = message_getter() if callable(message_getter) else "当前平台不支持 QQ 空间"
return json.dumps({"status": "unsupported_platform", "message": message}, ensure_ascii=False)
return json.dumps({"status": "disabled", "message": "QQ 空间动态层未启用"}, ensure_ascii=False)
if not callable(availability) and not self.enable_qzone_integration:
return json.dumps({"status": "disabled", "message": "QQ 空间动态层未启用"}, ensure_ascii=False)
target = _single_line(user_id, 40)
if not target:
try:
target = str(event.get_sender_id())
except Exception:
target = ""
try:
selection = parse_qzone_post_selection(user_id=target, selector=selector, pos=pos, fid=fid)
if selection.fid:
candidates = await self._qzone_query_feeds(event, target_id=selection.target_id or None, pos=0, num=20, with_detail=True)
posts = [
item for item in candidates
if str(getattr(item, "tid", "") or "") == selection.fid
or str(self._qzone_post_value(item, "fid", "") or "") == selection.fid
][:1]
elif selection.is_last:
candidates = await self._qzone_query_feeds(event, target_id=selection.target_id or None, pos=0, num=10, with_detail=True)
posts = candidates[-1:] if candidates else []
else:
posts = await self._qzone_query_feeds(event, target_id=selection.target_id or None, pos=max(0, int(selection.pos or 0)), num=1, with_detail=True)
if not posts:
return json.dumps({"status": "empty", "message": "查询结果为空"}, ensure_ascii=False)
post = posts[0]
action_msg = ""
if reply:
comment = await self._qzone_comment_post(event, post)
action_msg = f"已评论:{comment}"
like_result: dict[str, Any] | None = None
if like:
like_result = await self._qzone_like_post(event, post)
like_text = "已点赞" if like_result.get("verified") else "点赞请求已受理,等待 QQ 空间同步"
action_msg = (action_msg + f";{like_text}") if action_msg else like_text
return json.dumps(
{
"status": "success",
"action": action_msg,
"like_result": like_result or {},
"author": _single_line(getattr(post, "name", ""), 60),
"uin": str(getattr(post, "uin", "") or ""),
"text": _single_line(getattr(post, "text", "") or getattr(post, "rt_con", ""), 300),
"images": list(getattr(post, "images", []) or [])[:6],
},
ensure_ascii=False,
)
except Exception as exc:
return json.dumps({"status": "error", "message": _single_line(exc, 160)}, ensure_ascii=False)
async def _pc_qzone_publish_feed_impl(self, event: AstrMessageEvent, text: str = "", **kwargs) -> str:
availability = getattr(self, "_qzone_available", None)
if callable(availability) and not availability(event):
supported = getattr(self, "_qzone_platform_supported", None)
if callable(supported) and not supported(event):
message_getter = getattr(self, "_qzone_platform_unavailable_message", None)
message = message_getter() if callable(message_getter) else "当前平台不支持 QQ 空间"
return json.dumps({"status": "unsupported_platform", "success": False, "message": message}, ensure_ascii=False)
return json.dumps({"status": "disabled", "success": False, "message": "QQ 空间动态层未启用"}, ensure_ascii=False)
content = _single_line(text or kwargs.get("content") or kwargs.get("message") or kwargs.get("draft"), 300)
images: list[str] = []
for key in ("images", "image_paths", "image_urls"):
value = kwargs.get(key)
if isinstance(value, (list, tuple)):
images.extend(str(item).strip() for item in value if str(item or "").strip())
elif isinstance(value, str) and value.strip():
images.append(value.strip())
for key in ("image", "image_path", "image_url", "path"):
value = kwargs.get(key)
if isinstance(value, str) and value.strip():
images.append(value.strip())
images = list(dict.fromkeys(images))[:9]
if not content and kwargs.get("use_latest_draft"):
state = self.data.get("qzone_integration") if isinstance(self.data.get("qzone_integration"), dict) else {}
content = _single_line(state.get("last_life_publish_draft") or state.get("last_life_publish_text"), 300)
if not content and not images:
return json.dumps(
{
"status": "need_text",
"success": False,
"message": "缺少 text 或 images 参数。请把要发布的说说正文作为 text 传入;如需带图,传 images;若要发布最近自动生成的生活草稿,传 use_latest_draft=true。",
"required_args": {"text": "要发布到 QQ 空间的说说正文", "images": "可选,本地图片路径或图片URL列表"},
},
ensure_ascii=False,
)
result = await self._publish_qzone_text(content, event, images=images, auto_generate_image=True)
return json.dumps({"status": "success" if result.get("success") else "error", **result}, ensure_ascii=False)
def _interaction_query_platform(self, event: AstrMessageEvent) -> str:
origin = str(getattr(event, "unified_msg_origin", "") or "")
platform = origin.split(":", 1)[0] if ":" in origin else ""
return platform or getattr(self, "target_platform", "") or "aiocqhttp"
def _interaction_query_private_targets(self, hint: str = "") -> list[dict[str, str]]:
query = _single_line(hint, 128)
users = self.data.get("users") if isinstance(self.data.get("users"), dict) else {}
profiles = self.data.get("worldbook_member_profiles") if isinstance(self.data.get("worldbook_member_profiles"), dict) else {}
targets: dict[str, dict[str, str]] = {}
def add(user_id: str, label: str = "", source: str = "") -> None:
user_id = _single_line(user_id, 128)
if not user_id:
return
existing = targets.setdefault(user_id, {"user_id": user_id, "label": "", "source": ""})
if label and (not existing.get("label") or existing.get("label") == user_id):
existing["label"] = label
if source and not existing.get("source"):
existing["source"] = source
if query and query.isdigit():
add(query, query, "qq")
configured_ids = set(self._configured_target_ids()) if callable(getattr(self, "_configured_target_ids", None)) else set()
for configured_id in configured_ids:
uid = _single_line(configured_id, 128)
if uid and (not query or query == uid or query in uid):
add(uid, uid, "target_config")
for user_id, user in users.items():
if not isinstance(user, dict):
continue
uid = _single_line(user.get("user_id") or user_id, 128)
try:
uid = self._canonical_private_user_id(uid)
except Exception:
pass
if not uid or not self._is_target_private_user(uid, user) or not bool(user.get("enabled", True)):
continue
tokens = [
uid,
user.get("nickname"),
user.get("display_name"),
user.get("last_display_name"),
user.get("stable_name"),
*(user.get("observed_display_names") if isinstance(user.get("observed_display_names"), list) else []),
*(user.get("aliases") if isinstance(user.get("aliases"), list) else []),
]
clean_tokens = [_single_line(token, 60) for token in tokens if _single_line(token, 60)]
if not query or any(query == token or (query and query in token) for token in clean_tokens):
label = next((token for token in clean_tokens if token and token != uid), uid)
add(uid, label, "private_user")
for user_id, profile in profiles.items():
if not isinstance(profile, dict):
continue
uid = _single_line(profile.get("linked_qq_user_id") or profile.get("user_id") or user_id, 40)
if not uid or not uid.isdigit():
continue
try:
uid = self._canonical_private_user_id(uid)
except Exception:
pass
linked_user = users.get(uid) if isinstance(users, dict) else None
configured_target = uid in configured_ids
if not configured_target and not (
isinstance(linked_user, dict)
and self._is_target_private_user(uid, linked_user)
and bool(linked_user.get("enabled", True))
):
continue
tokens = [
uid,
profile.get("name"),
*(profile.get("aliases") if isinstance(profile.get("aliases"), list) else []),
*(profile.get("observed_names") if isinstance(profile.get("observed_names"), list) else []),
]
clean_tokens = [_single_line(token, 60) for token in tokens if _single_line(token, 60)]
if not query or any(query == token or (query and query in token) for token in clean_tokens):
label = next((token for token in clean_tokens if token and token != uid), uid)
add(uid, label, "worldbook")
return list(targets.values())[:12]
async def _interaction_query_group_targets(self, event: AstrMessageEvent, hint: str = "") -> list[dict[str, str]]:
query = _single_line(hint, 80)
targets: dict[str, dict[str, str]] = {}

242
main.py
查看文件

@ -131,7 +131,6 @@ from .calendar_system import CalendarEventError
from .forward_message import ForwardMessageMixin
from .private_image import PrivateImageMixin
from .prompt_surface import PromptSurface
from .qzone_integration import QzoneMixin
from .segmented_message import flatten_component_chunks, split_plain_component_chain_detailed
from .token_budget import TokenBudgetMixin
from .balance_awareness import BalanceAwarenessMixin
@ -143,7 +142,6 @@ from .group_wakeup import GroupWakeupMixin
from .group_observation import GroupObservationMixin
from .event_dispatch import EventDispatchMixin
from .private_reading import PrivateReadingMixin
from .news_exploration import NewsExplorationMixin
try:
from .self_timeline import SelfTimelineMixin
except ModuleNotFoundError as exc:
@ -914,7 +912,6 @@ class PrivateCompanionPlugin(
MemoryCompanionAdapterMixin,
PrivateImageMixin,
ForwardMessageMixin,
QzoneMixin,
TokenBudgetMixin,
BalanceAwarenessMixin,
WorldbookMixin,
@ -935,7 +932,6 @@ class PrivateCompanionPlugin(
GroupObservationMixin,
EventDispatchMixin,
PrivateReadingMixin,
NewsExplorationMixin,
SelfTimelineMixin,
AtRelayMixin,
Star,
@ -1584,17 +1580,13 @@ class PrivateCompanionPlugin(
30.0,
self._cfg_float(c, "group_nsfw_image_review_timeout_seconds", 8.0, 3.0),
)
self.enable_screen_glance_action = self._cfg_bool(
c, "enable_screen_glance_action", bool(self._cfg_raw(c, "allow_screen_peek_action", legacy_screen_enabled))
)
self.enable_poke_action = self._cfg_bool(
c, "enable_poke_action", bool(self._cfg_raw(c, "allow_poke_action", legacy_poke_enabled))
)
self.enable_screen_glance_action = False
self.enable_poke_action = False
self.enable_voice_action = self._cfg_bool(
c, "enable_voice_action", bool(self._cfg_raw(c, "allow_voice_action", legacy_voice_enabled))
)
self.enable_qq_presence_sync = self._cfg_bool(c, "enable_qq_presence_sync", True)
self.enable_qq_custom_presence_sync = self._cfg_bool(c, "enable_qq_custom_presence_sync", False)
self.enable_qq_presence_sync = False
self.enable_qq_custom_presence_sync = False
self.poke_action_max_times = self._cfg_int(c, "poke_action_max_times", 1, 1, 3)
self.poke_action_cooldown_minutes = self._cfg_int(c, "poke_action_cooldown_minutes", 30, 0, 1440)
self.voice_action_max_chars = self._cfg_int(c, "voice_action_max_chars", 30, 6, 80)
@ -1729,8 +1721,8 @@ class PrivateCompanionPlugin(
self.enable_dialogue_episode_memory = self._cfg_bool(c, "enable_dialogue_episode_memory", True)
self.enable_open_loop_tracking = self._cfg_bool(c, "enable_open_loop_tracking", True)
self.enable_user_habit_learning = self._cfg_bool(c, "enable_user_habit_learning", True)
self.enable_food_menu_recommendation = self._cfg_bool(c, "enable_food_menu_recommendation", True)
self.enable_meal_care_proactive = self._cfg_bool(c, "enable_meal_care_proactive", True)
self.enable_food_menu_recommendation = False
self.enable_meal_care_proactive = False
self.meal_care_max_daily = self._cfg_int(c, "meal_care_max_daily", 1, 0, 3)
self.meal_care_min_interval_hours = self._cfg_int(c, "meal_care_min_interval_hours", 48, 0, 168)
self.meal_care_followup_minutes = self._cfg_int(c, "meal_care_followup_minutes", 45, 15, 180)
@ -1894,14 +1886,14 @@ class PrivateCompanionPlugin(
self.enable_memory_companion_private_recall = self._cfg_bool(c, "enable_memory_companion_private_recall", True)
self.memory_companion_context_top_k = self._cfg_int(c, "memory_companion_context_top_k", 5, 1, 10)
self.memory_companion_context_max_chars = self._cfg_int(c, "memory_companion_context_max_chars", 900, 240, 1800)
self.enable_bilibili_integration = self._cfg_bool(c, "enable_bilibili_integration", True)
self.enable_bilibili_boredom_watch = self._cfg_bool(c, "enable_bilibili_boredom_watch", True)
self.enable_bilibili_integration = False
self.enable_bilibili_boredom_watch = False
self.bilibili_boredom_min_interval_hours = self._cfg_int(c, "bilibili_boredom_min_interval_hours", 8, 2, 72)
self.bilibili_share_probability = self._cfg_unit_interval(c, "bilibili_share_probability", 0.35, 0.0)
self.bilibili_share_min_score = self._cfg_int(c, "bilibili_share_min_score", 7, 0, 10)
self.enable_news_integration = self._cfg_bool(c, "enable_news_integration", False)
self.enable_news_boredom_read = self._cfg_bool(c, "enable_news_boredom_read", True)
self.enable_news_daily_hot_read = self._cfg_bool(c, "enable_news_daily_hot_read", self._cfg_bool(c, "enable_hot_trend_sources", True))
self.enable_news_integration = False
self.enable_news_boredom_read = False
self.enable_news_daily_hot_read = False
self.news_min_interval_hours = self._cfg_int(c, "news_min_interval_hours", 6, 1, 72)
self.news_share_probability = self._cfg_unit_interval(c, "news_share_probability", 0.22, 0.0)
self.enable_external_event_self_link = self._cfg_bool(c, "enable_external_event_self_link", True)
@ -1911,49 +1903,28 @@ class PrivateCompanionPlugin(
self.news_max_items_per_source = self._cfg_int(c, "news_max_items_per_source", 5, 1, 20)
self.news_hot_sources = self._cfg_str(c, "news_hot_sources", self._cfg_str(c, "hot_trend_sources", "weibo,hackernews"))
self.news_hot_max_items = self._cfg_int(c, "news_hot_max_items", self._cfg_int(c, "hot_trend_max_items", 12, 3, 30), 3, 30)
self.enable_ai_daily_watch = self._cfg_bool(c, "enable_ai_daily_watch", True)
self.ai_daily_sources = self._cfg_str(c, "ai_daily_sources", DEFAULT_AI_DAILY_SOURCES)
self.ai_daily_source_uid = re.sub(r"\D+", "", self._cfg_str(c, "ai_daily_source_uid", "285286947")) or "285286947"
self.ai_daily_prefer_text_version = self._cfg_bool(c, "ai_daily_prefer_text_version", True)
self.news_sources = self._cfg_str(
c,
"news_sources",
DEFAULT_NEWS_SOURCES,
)
if str(self.news_sources or "").strip() in {LEGACY_DEFAULT_NEWS_SOURCES, PREVIOUS_TECH_DEFAULT_NEWS_SOURCES}:
self.news_sources = DEFAULT_NEWS_SOURCES
self.news_provider_id = self._cfg_str(c, "NEWS_PROVIDER_ID", "")
self.enable_web_exploration = self._cfg_bool(c, "enable_web_exploration", False)
self.enable_web_exploration_boredom_search = self._cfg_bool(c, "enable_web_exploration_boredom_search", True)
self.web_exploration_min_interval_hours = self._cfg_int(c, "web_exploration_min_interval_hours", 8, 1, 168)
self.web_exploration_share_probability = self._cfg_unit_interval(c, "web_exploration_share_probability", 0.18, 0.0)
self.web_exploration_max_results = self._cfg_int(c, "web_exploration_max_results", 6, 3, 20)
self.web_exploration_interests = self._cfg_str(
c,
"web_exploration_interests",
"按 Bot 人格自行决定;可偏向最近聊天、日程、人设兴趣、作品、技术、生活小知识、流行梗、时讯、新鲜事物。",
)
self.web_exploration_provider_id = self._cfg_str(c, "WEB_EXPLORATION_PROVIDER_ID", "")
self.web_exploration_api_base_url = self._cfg_str(c, "WEB_EXPLORATION_API_BASE_URL", "")
self.web_exploration_api_key = self._cfg_str(c, "WEB_EXPLORATION_API_KEY", "")
self.web_exploration_api_model = self._cfg_str(c, "WEB_EXPLORATION_API_MODEL", "")
self.enable_qzone_integration = self._cfg_bool(c, "enable_qzone_integration", True)
self.qzone_cookie = self._cfg_str(c, "QZONE_COOKIE", "")
self.enable_qzone_life_publish = self._cfg_bool(c, "enable_qzone_life_publish", False)
self.qzone_life_publish_min_interval_hours = self._cfg_int(c, "qzone_life_publish_min_interval_hours", 24, 4, 168)
self.qzone_life_publish_probability = self._cfg_unit_interval(c, "qzone_life_publish_probability", 0.18, 0.0)
self.qzone_publish_style_prompt = self._cfg_str(c, "qzone_publish_style_prompt", "")
self.enable_qzone_generated_image_publish = self._cfg_bool(c, "enable_qzone_generated_image_publish", True)
self.qzone_generated_image_probability = self._cfg_unit_interval(c, "qzone_generated_image_probability", 0.25, 0.0)
self.qzone_publish_image_style_prompt = self._cfg_str(c, "qzone_publish_image_style_prompt", "")
self.enable_qzone_comment_inbox = self._cfg_bool(c, "enable_qzone_comment_inbox", False)
self.qzone_comment_inbox_interval_minutes = self._cfg_int(c, "qzone_comment_inbox_interval_minutes", 60, 5, 1440)
self.qzone_comment_inbox_recent_posts = self._cfg_int(c, "qzone_comment_inbox_recent_posts", 5, 1, 20)
self.qzone_comment_inbox_max_replies_per_tick = self._cfg_int(c, "qzone_comment_inbox_max_replies_per_tick", 1, 1, 5)
self.enable_qzone_emotional_vent_publish = self._cfg_bool(c, "enable_qzone_emotional_vent_publish", False)
self.qzone_emotional_vent_threshold = self._cfg_int(c, "qzone_emotional_vent_threshold", 90, 40, 100)
self.qzone_emotional_vent_cooldown_hours = self._cfg_int(c, "qzone_emotional_vent_cooldown_hours", 72, 4, 336)
self.qzone_emotional_vent_probability = self._cfg_unit_interval(c, "qzone_emotional_vent_probability", 0.35, 0.0)
self.enable_ai_daily_watch = False
self.ai_daily_sources = ""
self.ai_daily_source_uid = ""
self.ai_daily_prefer_text_version = False
self.news_sources = ""
self.news_provider_id = ""
self.enable_web_exploration = False
self.enable_web_exploration_boredom_search = False
self.web_exploration_min_interval_hours = 0
self.web_exploration_share_probability = 0.0
self.web_exploration_max_results = 0
self.web_exploration_interests = ""
self.web_exploration_provider_id = ""
self.web_exploration_api_base_url = ""
self.web_exploration_api_key = ""
self.web_exploration_api_model = ""
self.enable_qzone_integration = False
self.qzone_cookie = ""
self.enable_qzone_life_publish = False
self.enable_qzone_generated_image_publish = False
self.enable_qzone_comment_inbox = False
self.enable_qzone_emotional_vent_publish = False
self.enable_jm_cosmos_integration = self._cfg_bool(
c,
"enable_private_reading_integration",
@ -2306,10 +2277,6 @@ class PrivateCompanionPlugin(
logger.info("[PrivateCompanion] 主动消息循环已启动")
if self._startup_maintenance_task is None or self._startup_maintenance_task.done():
self._startup_maintenance_task = asyncio.create_task(self._run_startup_background_maintenance())
self._create_startup_background_task(
"reset_stale_qq_presence",
self._reset_stale_qq_presence_if_needed,
)
self._create_startup_background_task("prepare_today", self._startup_prepare_today)
if self.enable_balance_awareness:
self._create_startup_background_task(
@ -2515,7 +2482,6 @@ class PrivateCompanionPlugin(
"""记录普通消息和 QQ/OneBot 撤回事件,用于撤回增强。"""
if self is None:
return
self._qzone_note_event_bot(event)
if not self.enabled:
return
self._note_inbound_activity_for_scope(event)
@ -4353,67 +4319,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
event.set_result(self._build_result_from_chain(quoted_chain))
@filter.llm_tool(name="pc_qzone_view_feed")
async def pc_qzone_view_feed(
self,
event: AstrMessageEvent,
user_id: str = "",
pos: int = 0,
like: bool = False,
reply: bool = False,
selector: str = "",
fid: str = "",
) -> str:
"""查看某位用户 QQ 空间说说,可按需点赞或评论。
Args:
user_id(string): 可选,要查看的 QQ 号;留空时默认查看当前配置账号。
pos(number): 可选,说说位置,0 表示最新一条。
like(boolean): 可选,是否给该条说说点赞。
reply(boolean): 可选,是否按工具内部规则尝试评论。
selector(string): 可选,自然语言选择器,如“最新”“第2条”“最后”;也可以填 fid。
fid(string): 可选,明确指定说说 fid。
"""
if self is None or self._proactive_only_blocks_passive_event(event, "pc_tools"):
return '{"status":"disabled","message":"主动消息专用模式下,普通被动回复不可使用 Private Companion 工具。"}'
return await self._pc_qzone_view_feed_impl(event, user_id=user_id, pos=pos, like=like, reply=reply, selector=selector, fid=fid)
@filter.llm_tool(name="pc_qzone_publish_feed")
async def pc_qzone_publish_feed(
self,
event: AstrMessageEvent,
text: str = "",
images: list[str] | None = None,
image: str = "",
image_path: str = "",
image_url: str = "",
use_latest_draft: bool = False,
**kwargs,
) -> str:
"""发布一条 QQ 空间说说。必须通过 text 参数传入最终正文;如需带图,通过 images 或 image 传入图片。
Args:
text(string): 要发布到 QQ 空间的说说正文。
images(list[string]): 可选,要随说说发布的本地图片路径或图片 URL 列表。
image(string): 可选,单张图片的本地路径或图片 URL。
image_path(string): 可选,单张本地图片路径。
image_url(string): 可选,单张图片 URL。
use_latest_draft(boolean): 可选,是否使用最近生成的生活说说草稿。
"""
if self is None or self._proactive_only_blocks_passive_event(event, "pc_tools"):
return '{"status":"disabled","message":"主动消息专用模式下,普通被动回复不可使用 Private Companion 工具。"}'
if images:
kwargs["images"] = images
if image:
kwargs["image"] = image
if image_path:
kwargs["image_path"] = image_path
if image_url:
kwargs["image_url"] = image_url
if use_latest_draft:
kwargs["use_latest_draft"] = use_latest_draft
return await self._pc_qzone_publish_feed_impl(event, text, **kwargs)
@filter.llm_tool(name="pc_generate_photo")
async def pc_generate_photo(
self,
@ -6207,31 +6112,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
mode="conditional",
metadata={"注入位置": placement, "触发原因": "livingmemory" if livingmemory_relation_context and not relation_query else "query"},
)
qzone_instruction = self._qzone_tool_instruction(event)
current_prompt = req.system_prompt or ""
current_turn_prompt = str(getattr(req, "prompt", "") or "")
qzone_marker = "<!-- private_companion_qzone_tools_v1 -->"
if qzone_instruction and qzone_marker not in current_prompt and qzone_marker not in current_turn_prompt:
if any(token in message_text for token in ("说说", "空间", "QQ空间", "动态", "点赞", "评论")):
placement = "prompt" if self._append_turn_prompt_fragment_by_position(
req,
qzone_marker,
qzone_instruction,
priority=88,
source="tools",
) else "system_prompt"
if placement == "system_prompt":
current_prompt = f"{current_prompt}\n\n{qzone_marker}\n{qzone_instruction}".strip()
req.system_prompt = current_prompt
await self._record_request_prompt_fragment(
event,
title="QQ 空间工具注入",
key="tools.qzone",
text=qzone_instruction,
source="tools",
mode="conditional",
metadata={"注入位置": placement},
)
schedule_management_instruction = self._schedule_management_tool_instruction()
current_prompt = req.system_prompt or ""
current_turn_prompt = str(getattr(req, "prompt", "") or "")
@ -10298,7 +10178,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
"""管理私聊陪伴状态、日程、记忆、风格、重要日期和可选外部动作。"""
if self is None:
return
self._qzone_note_event_bot(event)
raw_text = str(event.message_str or "")
args = raw_text.replace("\u3000", " ").split(maxsplit=2)
action = args[1].strip() if len(args) >= 2 else "帮助"
@ -10647,58 +10526,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
await self._reply(event, self._swap_external_image_api_command_text(force=force_swap))
event.stop_event()
return
if action in {"发说说", "发QQ空间", "发布说说", "空间发布", "发布空间"}:
image_sources = await self._qzone_image_sources_from_event(event)
image_sources, image_select_message = self._qzone_select_image_sources(value, image_sources)
if image_select_message:
await self._reply(event, image_select_message)
event.stop_event()
return
publish_text = self._qzone_clean_publish_text(value)
if image_sources and publish_text in {"[图片]", "【图片】", "图片"}:
publish_text = ""
if not publish_text and not image_sources:
await self._reply(event, "请这样使用:陪伴 发说说 <正文>,也可以随消息附带图片。\n这是公开发布动作,正文或图片不能为空。")
event.stop_event()
return
await self._reply(event, response)
result = await self._publish_qzone_text(publish_text, event, images=image_sources, auto_generate_image=True)
if result.get("success"):
await self._reply(
event,
"QQ 空间说说已发布。\n"
f"QQ:{result.get('uin') or '未知'}\n"
f"tid:{result.get('tid') or '未知'}\n"
f"正文:{_single_line(result.get('text'), 160) or '无'}\n"
f"图片:{len(result.get('images') or [])} 张\n"
f"校验:{_single_line(result.get('verify_message'), 120) or ('通过' if result.get('verified') else '未校验')}",
)
else:
await self._reply(event, f"发布失败:{_single_line(result.get('message'), 180)}")
event.stop_event()
return
if action in {"测试说说链路", "测试空间发布", "测试QQ空间发布", "测试qzone发布"}:
await self._reply(event, response)
await self._reply(event, await self._test_qzone_publish_tool_chain(event))
event.stop_event()
return
if action in {"测试说说配图", "测试空间配图", "测试QQ空间配图", "测试qzone配图"}:
await self._reply(event, response)
await self._reply(event, await self._test_qzone_publish_image_chain(event))
event.stop_event()
return
if action in {"AI日报", "ai日报", "日报", "AI早报", "ai早报", "早报"}:
await self._reply(event, response)
await self._maybe_track_ai_daily(force=True)
await self._reply(event, self._format_ai_daily_digest_for_command())
event.stop_event()
return
if action in {"新闻", "今日新闻", "AI新闻", "ai新闻"}:
await self._reply(event, response)
await self._perform_news_reading(reason="user_query", allow_share=False, force=True)
await self._reply(event, self._format_news_digest_for_command())
event.stop_event()
return
if action in bookshelf_password_reset_actions:
await self._reply(event, response)
if action in {"重置插件", "全部重置"}:
@ -10824,7 +10651,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
"""管理群聊陪伴状态、群友画像、群内常见词、话题线程和关系网。"""
if self is None:
return
self._qzone_note_event_bot(event)
async for result in self._group_companion_command_impl(event):
yield result
@ -10833,7 +10659,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
"""记录私聊互动、图片防抖、用户画像和主动陪伴反馈。"""
if self is None:
return
self._qzone_note_event_bot(event)
received_ts = _now_ts()
user_id = str(event.get_sender_id())
self_id = self._event_self_id(event)
@ -11678,7 +11503,6 @@ wakeup_type={_single_line(wakeup.get('type'), 40)} score={_single_line(wakeup.ge
"""观察群聊消息,维护群上下文并判断是否自然唤醒 Bot。"""
if self is None:
return
self._qzone_note_event_bot(event)
if not self._feature_enabled_or_temp_unlocked("enable_group_companion"):
return
group_id = self._extract_group_id_from_event(event)

文件差异内容过多而无法显示 加载差异

查看文件

@ -28,7 +28,6 @@ from quart import request, send_file
from .constants import DEFAULT_DAILY_PLAN_ITEMS, PAGE_FONT_NAMES, PAGE_THEME_NAMES, PLUGIN_NAME, _REASON_TEXT
from .config_migration import _ensure_config_parent_dir
from .helpers import _flat_get, _normalize_timezone_name, _redact_outbound_secrets, _safe_int, _set_into_config, _set_today_key_timezone, _strip_internal_message_blocks, _text_looks_garbled, _text_similarity, _today_key
from .page_api_qzone import PrivateCompanionPageApiQzoneMixin
from .page_api_users_groups import PrivateCompanionPageApiUsersGroupsMixin
from .planning import evaluate_daily_plan_quality, generate_daily_plan, generate_detail_enhancement
from .memo_notes import (
@ -46,9 +45,28 @@ from .q7_backend_contracts import (
)
PAGE_API_PREFIX = f"/{PLUGIN_NAME}/page"
OPS_REMOVED_CONFIG_EXACT = {
"QZONE_COOKIE", "enable_livingmemory_integration", "livingmemory_tool_name",
"enable_ai_daily_watch", "ai_daily_source_uid", "ai_daily_prefer_text_version",
"enable_food_menu_recommendation", "enable_meal_care_proactive",
"enable_poke_action", "allow_poke_action", "enable_qq_presence_sync",
"enable_qq_custom_presence_sync", "enable_screen_glance_action",
"allow_screen_peek_action", "enable_unanswered_screen_peek_followup",
}
OPS_REMOVED_CONFIG_PREFIXES = (
"qzone_", "enable_qzone_", "bilibili_", "enable_bilibili_", "news_",
"enable_news_", "web_exploration", "WEB_EXPLORATION_", "food_menu",
"meal_care", "poke_action_", "screen_peek_", "unanswered_screen_peek_",
"qq_presence_", "hot_trend_",
)
class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanionPageApiUsersGroupsMixin):
def _ops_config_key_removed(key: str) -> bool:
normalized = str(key or "").strip()
return normalized in OPS_REMOVED_CONFIG_EXACT or normalized.startswith(OPS_REMOVED_CONFIG_PREFIXES)
class PrivateCompanionPageApi(PrivateCompanionPageApiUsersGroupsMixin):
"""AstrBot 官方插件拓展页面 API。"""
IMAGE_API_RUNTIME_SETTING_KEYS = {
@ -240,30 +258,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
("/bookshelf/reading_state", self.update_bookshelf_reading_state, ["POST"], "Private Companion Page update bookshelf reading state"),
("/memo/list", self.list_memo_notes, ["GET"], "Private Companion Page list memo notes"),
("/memo/update", self.update_memo_note, ["POST"], "Private Companion Page update memo note"),
("/qzone/status", self.get_qzone_status, ["GET"], "Private Companion Page qzone status"),
("/qzone/health", self.get_qzone_status, ["GET"], "Private Companion Page qzone status alias"),
("/qzone/summary", self.get_qzone_status, ["GET"], "Private Companion Page qzone status alias"),
("/qzone/state", self.get_qzone_status, ["GET"], "Private Companion Page qzone status alias"),
("/qzone/feed", self.get_qzone_feed, ["GET"], "Private Companion Page qzone feed"),
("/qzone/feeds", self.get_qzone_feed, ["GET"], "Private Companion Page qzone feed alias"),
("/qzone/list", self.get_qzone_feed, ["GET"], "Private Companion Page qzone feed alias"),
("/qzone/detail", self.get_qzone_detail, ["GET"], "Private Companion Page qzone detail"),
("/qzone/post", self.get_qzone_detail, ["GET"], "Private Companion Page qzone detail alias"),
("/qzone/item", self.get_qzone_detail, ["GET"], "Private Companion Page qzone detail alias"),
("/qzone/refresh_cookies", self.refresh_qzone_cookies, ["POST"], "Private Companion Page qzone refresh cookies"),
("/qzone/refresh-cookies", self.refresh_qzone_cookies, ["POST"], "Private Companion Page qzone refresh cookies alias"),
("/qzone/cookies/refresh", self.refresh_qzone_cookies, ["POST"], "Private Companion Page qzone refresh cookies alias"),
("/qzone/cookie/refresh", self.refresh_qzone_cookies, ["POST"], "Private Companion Page qzone refresh cookies alias"),
("/qzone/refresh", self.refresh_qzone_cookies, ["POST"], "Private Companion Page qzone refresh cookies alias"),
("/qzone/publish", self.publish_qzone_post, ["POST"], "Private Companion Page qzone publish"),
("/qzone/post/publish", self.publish_qzone_post, ["POST"], "Private Companion Page qzone publish alias"),
("/qzone/post", self.publish_qzone_post, ["POST"], "Private Companion Page qzone publish alias"),
("/qzone/like", self.like_qzone_post, ["POST"], "Private Companion Page qzone like"),
("/qzone/post/like", self.like_qzone_post, ["POST"], "Private Companion Page qzone like alias"),
("/qzone/comment", self.comment_qzone_post, ["POST"], "Private Companion Page qzone comment"),
("/qzone/post/comment", self.comment_qzone_post, ["POST"], "Private Companion Page qzone comment alias"),
("/qzone/delete", self.delete_qzone_post, ["POST"], "Private Companion Page qzone delete"),
("/qzone/post/delete", self.delete_qzone_post, ["POST"], "Private Companion Page qzone delete alias"),
("/creative/project", self.get_creative_project, ["GET"], "Private Companion Page creative project detail"),
("/creative/project/cover", self.get_creative_project_cover, ["GET"], "Private Companion Page creative project cover"),
("/creative/project/cover_data", self.get_creative_project_cover_data, ["GET"], "Private Companion Page creative project cover data"),
@ -464,17 +458,12 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"settings": self._runtime_settings(),
"deepseek_peak_routing": self._deepseek_peak_routing_summary(),
"cache": self._cache_summary(data),
"livingmemory": self._livingmemory_summary(),
"screen_companion": self._screen_companion_summary(data),
"knowledge": self.plugin._roleplay_knowledge_summary(),
"worldbook": self._worldbook_summary(data),
"proactive_candidates": self._proactive_candidate_summary(data),
"proactive_tasks": self._proactive_task_summary(data),
"message_debounce": self._message_debounce_summary(data),
"bilibili": self._bilibili_summary(data),
"news": self._news_summary(data),
"web_exploration": self._web_exploration_summary(data),
"qzone": self._qzone_summary(data),
"private_reading": self._jm_cosmos_summary(data),
"creative": self._creative_summary(data),
"bookshelf": await self._bookshelf_summary(data, unlocked=False),
@ -1816,7 +1805,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
sqlite_status = {**sqlite_status, "items": all_sqlite_items}
passive_no_reply = self._passive_no_reply_summary(data)
screen_companion = self._screen_companion_summary(data)
qzone = self._qzone_summary(data)
all_recent_events = self._troubleshooting_recent_events(
diagnostics=diagnostics,
proactive_tasks=proactive_tasks,
@ -1885,7 +1873,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"passive_no_reply": passive_no_reply,
"prompt_injections": self._prompt_injection_summary(data),
"screen_companion": screen_companion,
"qzone": qzone,
"proactive_intensity": self._proactive_intensity_summary(),
"proactive_runtime": proactive_tasks.get("runtime", {}),
"token_budget": token_stats.get("budget", {}),
@ -1961,8 +1948,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
result = await self._run_tts_generation_chain_test(payload)
elif test_type == "screen_peek":
result = await self._run_screen_peek_chain_test(payload)
elif test_type == "qzone_integration":
result = await self._run_qzone_chain_test(payload)
elif test_type == "proactive_message":
result = await self._run_proactive_message_chain_test(payload)
elif test_type in {"skill_similarity", "model_diagnostics"}:
@ -2763,144 +2748,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"error": "" if not unusable else (preview or "没有得到屏幕观察结果"),
}
async def _run_qzone_chain_test(self, payload: dict[str, Any]) -> dict[str, Any]:
steps: list[dict[str, str]] = []
def add_step(name: str, status: str, detail: str) -> None:
steps.append(
{
"name": self._single_line(name, 40),
"status": self._single_line(status, 16),
"detail": self._single_line(detail, 180),
}
)
started = time.time()
service_available = bool(
callable(getattr(self.plugin, "_test_qzone_integration", None))
and callable(getattr(self.plugin, "_qzone_get_cookies", None))
)
platform_checker = getattr(self.plugin, "_qzone_platform_supported", None)
platform_supported = bool(platform_checker(None)) if callable(platform_checker) else True
enabled = bool(getattr(self.plugin, "enable_qzone_integration", False) and platform_supported)
comment_enabled = bool(getattr(self.plugin, "enable_qzone_comment_inbox", False))
add_step("内置服务", "ok" if service_available else "error", "可用" if service_available else "QQ 空间模块入口不可用")
add_step(
"平台能力",
"ok" if platform_supported else "error",
"OneBot/aiocqhttp 可用" if platform_supported else "QQ 官方机器人不支持 QQ 空间",
)
add_step("整合开关", "ok" if enabled else "warn", "已开启" if enabled else "已关闭")
if not service_available or not enabled:
unavailable_detail = (
"QQ 官方机器人不支持 QQ 空间;不会执行读取、发布、点赞、评论或后台轮询。"
if not platform_supported
else "QQ 空间整合未启用或模块入口不可用"
)
return {
"ok": False,
"title": "QQ 空间链路测试",
"provider": "qzone",
"detail": unavailable_detail,
"text_preview": unavailable_detail if not platform_supported else "开启 QQ 空间整合后再测试 Cookie、读取和发布工具链路。",
"steps": steps,
"elapsed_ms": int((time.time() - started) * 1000),
"error": unavailable_detail,
}
target_id = self._single_line(payload.get("target_id"), 40)
read_text = ""
read_ok = False
read_detail = ""
reader = getattr(self.plugin, "_test_qzone_integration", None)
if callable(reader):
try:
read_text = await asyncio.wait_for(
reader(None, target_id=target_id),
timeout=max(15, self._int(payload.get("timeout_seconds"), 45, 10, 180)),
)
read_ok = ("读取链路正常" in read_text) or ("读取链路可调用" in read_text)
read_detail = (
(self._qzone_test_line_with_prefix(read_text, "查询结果:失败") if not read_ok else "")
or self._qzone_test_last_result_line(read_text)
or self._single_line(read_text, 180)
)
add_step("Cookie/读取", "ok" if read_ok else "error", read_detail or "读取测试未返回明确结果")
except Exception as exc:
read_detail = self._single_line(exc, 180)
add_step("Cookie/读取", "error", read_detail or "读取测试异常")
else:
add_step("Cookie/读取", "error", "缺少 _test_qzone_integration 测试入口")
publish_ok = False
publish_detail = ""
publisher = getattr(self.plugin, "_pc_qzone_publish_feed_impl", None)
if callable(publisher):
try:
raw = await asyncio.wait_for(publisher(None, ""), timeout=15)
parsed = json.loads(raw) if isinstance(raw, str) else {}
status = self._single_line(parsed.get("status"), 40) if isinstance(parsed, dict) else ""
message = self._single_line(parsed.get("message"), 160) if isinstance(parsed, dict) else self._single_line(raw, 160)
publish_ok = status == "need_text"
publish_detail = "空参数返回 need_text,发布工具入口正常" if publish_ok else (message or f"返回 {status or '未知状态'}")
add_step("发布模拟", "ok" if publish_ok else "warn", publish_detail)
except Exception as exc:
publish_detail = self._single_line(exc, 180)
add_step("发布模拟", "error", publish_detail or "发布工具空参数测试异常")
else:
add_step("发布模拟", "warn", "缺少发布工具入口,无法测试空参数模拟")
async with self.plugin._data_lock:
qzone_state = deepcopy(
self.plugin.data.get("qzone_integration")
if isinstance(self.plugin.data.get("qzone_integration"), dict)
else {}
)
list_len = lambda key: len(qzone_state.get(key)) if isinstance(qzone_state.get(key), list) else 0
seen_count = list_len("comment_inbox_seen_ids") + list_len("comment_inbox_seen_keys")
replied_count = list_len("comment_inbox_replied_ids") + list_len("comment_inbox_replied_keys")
inbox_status = self._single_line(qzone_state.get("last_comment_inbox_status"), 120)
inbox_detail = (
f"{'已开启' if comment_enabled else '未开启'};已见 {seen_count},已回复 {replied_count}"
+ (f";最近 {inbox_status}" if inbox_status else "")
)
add_step("评论收件箱", "ok" if comment_enabled else "info", inbox_detail)
ok = bool(read_ok and publish_ok)
preview_parts = [
read_detail,
publish_detail,
inbox_detail,
]
if read_text:
preview_parts.append(self._single_line(read_text, 500))
return {
"ok": ok,
"title": "QQ 空间链路测试",
"provider": "qzone",
"detail": "QQ 空间读取和发布模拟正常" if ok else "QQ 空间链路存在需要处理的项",
"text_preview": self._single_line(";".join(part for part in preview_parts if part), 500),
"steps": steps,
"elapsed_ms": int((time.time() - started) * 1000),
"error": "" if ok else (read_detail or publish_detail or "QQ 空间链路测试未通过"),
}
@staticmethod
def _qzone_test_last_result_line(text: str) -> str:
for line in reversed(str(text or "").replace("\r", "\n").split("\n")):
clean = line.strip().lstrip("-").strip()
if clean.startswith("结果:"):
return clean
return ""
@staticmethod
def _qzone_test_line_with_prefix(text: str, prefix: str) -> str:
for line in str(text or "").replace("\r", "\n").split("\n"):
clean = line.strip().lstrip("-").strip()
if clean.startswith(prefix):
return clean
return ""
async def _run_tts_generation_chain_test(self, payload: dict[str, Any]) -> dict[str, Any]:
context = getattr(self.plugin, "context", None)
if context is None:
@ -11282,7 +11129,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
values["enable_private_reading_boredom_read"] = bool(private_reading_available and getattr(self.plugin, "enable_jm_cosmos_boredom_read", False))
values["enable_private_reading_ask_recommendation"] = bool(private_reading_available and getattr(self.plugin, "enable_private_reading_ask_recommendation", False))
values["enable_private_reading_preference_influence"] = bool(private_reading_available and getattr(self.plugin, "enable_private_reading_preference_influence", True))
return values
return {key: value for key, value in values.items() if not _ops_config_key_removed(key)}
def _proactive_only_mode_snapshot(self) -> dict[str, Any]:
clearer = getattr(self.plugin, "_clear_proactive_only_temp_unlocks_if_mode_off", None)
@ -15372,7 +15219,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"atrelay_multi_target_limit",
}
keys.update(self._schema_setting_keys(public_only=True))
return keys
return {key for key in keys if not _ops_config_key_removed(key)}
def _normalize_setting_value(self, key: str, value: Any) -> Any:
if key in self._schema_bool_keys():
@ -16404,6 +16251,7 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
return "\n".join(lines)[:limit].strip()
def _schema_key_index(self) -> dict[str, Any]:
"""Build a schema index without removed ops-only entertainment capabilities."""
cached = self._schema_key_index_cache
if cached is not None:
return cached
@ -16423,6 +16271,8 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
if not isinstance(item, dict):
continue
key = str(raw_key)
if _ops_config_key_removed(key):
continue
item_type = str(item.get("type") or "")
if item_type == "object" and isinstance(item.get("items"), dict):
visit(item["items"], key)
@ -16795,74 +16645,16 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
return memories[:8]
def _livingmemory_summary(self) -> dict[str, Any]:
try:
available = bool(self.plugin._livingmemory_available())
except Exception:
available = False
try:
plugin_dir = str(self.plugin._livingmemory_plugin_dir())
except Exception:
plugin_dir = ""
try:
status = self.plugin._format_livingmemory_status()
except Exception:
status = "记忆插件:状态探测失败,已跳过协同。"
# Detect "我会牢牢记住你" (RememberYou) bridge availability
memory_companion_active = False
memory_companion_display_name = ""
try:
bridge = self.plugin._memory_companion_bridge() # type: ignore[attr-defined]
if bridge is not None:
memory_companion_active = True
memory_companion_display_name = getattr(bridge, "display_name", "") or "我会牢牢记住你"
if str(memory_companion_display_name).strip().lower() in {"rememberyou", "remember you", "memorycompanion", "memory companion", "astrbot_plugin_memory_companion", "astrbot_plugin_remember_you"}:
memory_companion_display_name = "我会牢牢记住你"
except Exception:
pass
configured_enabled = bool(getattr(self.plugin, "enable_livingmemory_integration", False))
active_plugins: list[dict[str, Any]] = []
if memory_companion_active:
active_plugins.append(
{
"type": "memory_companion",
"name": memory_companion_display_name or "我会牢牢记住你",
"display_name": memory_companion_display_name or "我会牢牢记住你",
"status": "桥接可用",
}
)
if available:
active_plugins.append(
{
"type": "livingmemory",
"name": "LivingMemory",
"display_name": "LivingMemory",
"status": "工具式召回可用",
"tool_name": getattr(self.plugin, "livingmemory_tool_name", "") or "recall_long_term_memory",
"plugin_dir": plugin_dir,
}
)
selected_plugin = active_plugins[0] if active_plugins else None
conflict = bool(memory_companion_active and available)
conflict_warning = (
f"同时检测到{memory_companion_display_name or '我会牢牢记住你'}和 LivingMemory。建议只保留一个可协同记忆插件,避免重复召回、重复写入或提示词膨胀。"
if conflict
else ""
)
return {
"enabled": bool(configured_enabled and active_plugins),
"configured_enabled": configured_enabled,
"compatible_available": bool(active_plugins),
"available": available,
"tool_name": getattr(self.plugin, "livingmemory_tool_name", ""),
"plugin_dir": plugin_dir,
"status": status,
"memory_companion_active": memory_companion_active,
"memory_companion_display_name": memory_companion_display_name,
"active_plugins": active_plugins,
"selected_plugin": selected_plugin,
"selected_plugin_name": str((selected_plugin or {}).get("display_name") or ""),
"conflict": conflict,
"conflict_warning": conflict_warning,
"enabled": False,
"configured_enabled": False,
"compatible_available": False,
"available": False,
"status": "Ops removed LivingMemory runtime compatibility; memory plugin bridge remains.",
"active_plugins": [],
"selected_plugin": None,
"conflict": False,
"migration_check": "not_required",
}
def _screen_companion_available(self) -> bool:
@ -16886,235 +16678,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
"summary_chars": len(str(context.get("summary") or "")),
}
def _bilibili_summary(self, data: dict[str, Any]) -> dict[str, Any]:
state = data.get("bilibili_integration") if isinstance(data.get("bilibili_integration"), dict) else {}
try:
available = bool(getattr(self.plugin, "_bilibili_available", lambda: False)())
except Exception:
available = False
latest = None
try:
latest_getter = getattr(self.plugin, "_latest_bilibili_video_candidate", None)
latest = latest_getter(include_memory_api=False) if callable(latest_getter) else None
except Exception:
latest = None
try:
watch_log = str(getattr(self.plugin, "_bilibili_watch_log_file", lambda: "")())
except Exception:
watch_log = ""
try:
memory_checker = getattr(self.plugin, "_bilibili_memory_api_available", None)
if callable(memory_checker):
try:
memory_api_available = bool(memory_checker(allow_probe=False))
except TypeError:
memory_api_available = bool(memory_checker())
else:
memory_api_available = False
except Exception:
memory_api_available = False
return {
"enabled": bool(available and getattr(self.plugin, "enable_bilibili_integration", False)),
"boredom_watch_enabled": bool(available and getattr(self.plugin, "enable_bilibili_boredom_watch", False)),
"available": available,
"memory_api_available": memory_api_available,
"watch_log": watch_log,
"last_boredom_watch_at": self.plugin._format_timestamp_elapsed(state.get("last_boredom_watch_at", 0)),
"last_status": state.get("last_boredom_watch_status", ""),
"latest_video": latest if isinstance(latest, dict) else {},
}
def _news_summary(self, data: dict[str, Any]) -> dict[str, Any]:
state = data.get("news_integration") if isinstance(data.get("news_integration"), dict) else {}
digest = state.get("last_digest") if isinstance(state.get("last_digest"), dict) else {}
latest_items = state.get("latest_items") if isinstance(state.get("latest_items"), list) else []
history = [
item
for item in self._browsing_history_entries(data)
if item.get("source") == "news"
]
ai_daily = state.get("ai_daily") if isinstance(state.get("ai_daily"), dict) else {}
ai_digest = ai_daily.get("last_digest") if isinstance(ai_daily.get("last_digest"), dict) else {}
ai_digest_items = ai_digest.get("items") if isinstance(ai_digest.get("items"), list) else []
ai_digest_first_item = ai_digest_items[0] if ai_digest_items and isinstance(ai_digest_items[0], dict) else {}
try:
ai_text_chars = max(0, int(ai_daily.get("last_text_chars") or 0))
except (TypeError, ValueError):
ai_text_chars = 0
if not ai_text_chars and ai_digest_first_item:
ai_text_chars = len(str(ai_digest_first_item.get("article_text") or ""))
try:
ai_subtitle_chars = max(0, int(ai_daily.get("last_video_subtitle_chars") or 0))
except (TypeError, ValueError):
ai_subtitle_chars = 0
if not ai_subtitle_chars and ai_digest_first_item:
ai_subtitle_chars = len(str(ai_digest_first_item.get("video_subtitle_text") or ""))
try:
ai_video_context_chars = max(0, int(ai_daily.get("last_video_context_chars") or 0))
except (TypeError, ValueError):
ai_video_context_chars = 0
if not ai_video_context_chars and ai_digest_first_item:
ai_video_context_chars = len(str(ai_digest_first_item.get("video_context_text") or ""))
try:
ai_video_duration = max(0, int(ai_daily.get("last_video_duration") or ai_digest_first_item.get("video_duration") or 0))
except (TypeError, ValueError):
ai_video_duration = 0
ai_video_tags_raw = ai_daily.get("last_video_tags") if isinstance(ai_daily.get("last_video_tags"), list) else ai_digest_first_item.get("video_tags")
ai_video_tags = [
self._single_line(tag, 40)
for tag in ai_video_tags_raw
if self._single_line(tag, 40)
] if isinstance(ai_video_tags_raw, list) else []
ai_video_comments_raw = ai_daily.get("last_video_hot_comments") if isinstance(ai_daily.get("last_video_hot_comments"), list) else ai_digest_first_item.get("video_hot_comments")
ai_video_comments = [
self._single_line(comment, 120)
for comment in ai_video_comments_raw
if self._single_line(comment, 120)
] if isinstance(ai_video_comments_raw, list) else []
try:
source_count = len(getattr(self.plugin, "_news_source_items", lambda: [])())
except Exception:
source_count = 0
return {
"enabled": bool(getattr(self.plugin, "enable_news_integration", False)),
"boredom_read_enabled": bool(getattr(self.plugin, "enable_news_boredom_read", False)),
"daily_hot_enabled": bool(getattr(self.plugin, "enable_news_daily_hot_read", False)),
"ai_daily_enabled": bool(getattr(self.plugin, "enable_ai_daily_watch", False)),
"source_count": source_count,
"history_count": len(history),
"history": history,
"last_read_at": self.plugin._format_timestamp_elapsed(state.get("last_read_at", 0)),
"last_status": self._single_line(state.get("last_status"), 80),
"ai_daily": {
"status": self._single_line(ai_daily.get("status"), 80),
"date": self._single_line(ai_daily.get("date"), 20),
"last_checked_at": self.plugin._format_timestamp_elapsed(ai_daily.get("last_checked_at", 0)),
"last_success_date": self._single_line(ai_daily.get("last_success_date"), 20),
"last_source_name": self._single_line(ai_daily.get("last_source_name"), 40),
"last_source_author": self._single_line(ai_daily.get("last_source_author"), 60),
"last_source_mid": self._single_line(ai_daily.get("last_source_mid"), 40),
"last_source_schedule": self._single_line(ai_daily.get("last_source_schedule"), 10),
"last_video_title": self._single_line(ai_daily.get("last_video_title"), 120),
"last_video_link": self._single_line(ai_daily.get("last_video_link"), 400),
"last_video_owner_name": self._single_line(ai_daily.get("last_video_owner_name") or ai_digest_first_item.get("video_owner_name"), 80),
"last_video_tname": self._single_line(ai_daily.get("last_video_tname") or ai_digest_first_item.get("video_tname"), 60),
"last_video_duration": ai_video_duration,
"last_video_context_chars": ai_video_context_chars,
"last_video_tags": ai_video_tags[:10],
"last_video_hot_comments": ai_video_comments[:5],
"last_text_link": self._single_line(ai_daily.get("last_text_link"), 400),
"last_text_readable": bool(ai_daily.get("last_text_readable")) if "last_text_readable" in ai_daily else bool(ai_digest_first_item.get("article_readable") and ai_digest_first_item.get("article_text")),
"last_text_chars": ai_text_chars,
"last_video_subtitle_readable": bool(ai_daily.get("last_video_subtitle_readable")) if "last_video_subtitle_readable" in ai_daily else bool(ai_digest_first_item.get("video_subtitle_readable") and ai_digest_first_item.get("video_subtitle_text")),
"last_video_subtitle_chars": ai_subtitle_chars,
"last_video_subtitle_status": self._single_line(ai_daily.get("last_video_subtitle_status") or ai_digest_first_item.get("video_subtitle_status"), 40),
"last_read_basis": self._single_line(ai_daily.get("last_read_basis"), 40),
"sources": [
{
"key": self._single_line(item.get("key"), 80),
"name": self._single_line(item.get("name"), 40),
"author_name": self._single_line(item.get("author_name"), 60),
"mid": self._single_line(item.get("mid"), 40),
"schedule": self._single_line(item.get("schedule"), 10),
}
for item in (ai_daily.get("sources") if isinstance(ai_daily.get("sources"), list) else [])
if isinstance(item, dict)
],
"source_states": {
self._single_line(key, 80): {
"name": self._single_line(value.get("name"), 40),
"author_name": self._single_line(value.get("author_name"), 60),
"mid": self._single_line(value.get("mid"), 40),
"schedule": self._single_line(value.get("schedule"), 10),
"status": self._single_line(value.get("status"), 80),
"last_checked_at": self.plugin._format_timestamp_elapsed(value.get("last_checked_at", 0)),
"last_success_date": self._single_line(value.get("last_success_date"), 20),
"last_video_title": self._single_line(value.get("last_video_title"), 120),
}
for key, value in (ai_daily.get("source_states") if isinstance(ai_daily.get("source_states"), dict) else {}).items()
if isinstance(value, dict)
},
"topic": self._single_line(ai_digest.get("topic"), 60),
"headline": self._single_line(ai_digest.get("headline"), 120),
},
"last_digest": {
"topic": self._single_line(digest.get("topic"), 60),
"headline": self._single_line(digest.get("headline"), 120),
"source": self._single_line(digest.get("selected_source"), 40),
"impression": self._sanitize_news_text(
digest.get("impression"),
180,
fallback="这条新闻的正文解析异常,建议稍后重新阅读。",
),
"link": self._single_line(digest.get("selected_link"), 400),
},
"latest_items": [
{
"source": self._single_line(item.get("source"), 40),
"title": self._single_line(item.get("title"), 120),
"summary": self._sanitize_news_text(
item.get("summary"),
160,
fallback="这条新闻摘要暂时解析异常,建议打开原文查看。",
),
"link": self._single_line(item.get("link"), 400),
}
for item in latest_items[:8]
if isinstance(item, dict)
],
}
def _web_exploration_summary(self, data: dict[str, Any]) -> dict[str, Any]:
state = data.get("web_exploration") if isinstance(data.get("web_exploration"), dict) else {}
digest = state.get("last_digest") if isinstance(state.get("last_digest"), dict) else {}
notes = state.get("notes") if isinstance(state.get("notes"), list) else []
history = [
item
for item in self._browsing_history_entries(data)
if item.get("source") != "news"
]
custom_available = bool(getattr(self.plugin, "_custom_web_exploration_search_configured", lambda: False)())
try:
astrbot_available = bool(getattr(self.plugin, "_astrbot_any_web_search_available", lambda: False)())
except Exception:
astrbot_available = False
available = bool(custom_available or astrbot_available)
search_backend = "custom" if custom_available else ("astrbot" if astrbot_available else "none")
return {
"enabled": bool(getattr(self.plugin, "enable_web_exploration", False)),
"boredom_search_enabled": bool(getattr(self.plugin, "enable_web_exploration_boredom_search", False)),
"available": available,
"search_backend": search_backend,
"custom_search_enabled": custom_available,
"astrbot_search_available": astrbot_available,
"last_explore_at": self.plugin._format_timestamp_elapsed(state.get("last_explore_at", 0)),
"last_status": self._single_line(state.get("last_status"), 80),
"last_query": {
"query": self._single_line((state.get("last_query") or {}).get("query") if isinstance(state.get("last_query"), dict) else "", 80),
"reason": self._single_line((state.get("last_query") or {}).get("reason") if isinstance(state.get("last_query"), dict) else "", 120),
"topic": self._single_line((state.get("last_query") or {}).get("topic") if isinstance(state.get("last_query"), dict) else "", 20),
},
"last_digest": {
"topic": self._single_line(digest.get("topic"), 80),
"note": self._single_line(digest.get("note"), 220),
"source_title": self._single_line(digest.get("source_title"), 120),
"source_url": self._single_line(digest.get("source_url"), 400),
},
"note_count": len(notes),
"history_count": len(history),
"history": history,
"recent_notes": [
{
"topic": self._single_line(item.get("topic"), 80),
"note": self._single_line(item.get("note"), 180),
"query": self._single_line(item.get("query"), 80),
"created_at": self.plugin._format_timestamp_elapsed(item.get("created_ts", 0)),
}
for item in notes[-8:]
if isinstance(item, dict)
],
}
def _browsing_history_entries(self, data: dict[str, Any]) -> list[dict[str, Any]]:
entries: list[dict[str, Any]] = []
news_state = data.get("news_integration") if isinstance(data.get("news_integration"), dict) else {}
@ -17236,79 +16799,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
item.pop("_ts", None)
return entries
def _qzone_summary(self, data: dict[str, Any]) -> dict[str, Any]:
state = data.get("qzone_integration") if isinstance(data.get("qzone_integration"), dict) else {}
service_available = bool(
callable(getattr(self.plugin, "_qzone_get_cookies", None))
and callable(getattr(self.plugin, "_qzone_query_feeds", None))
)
platform_checker = getattr(self.plugin, "_qzone_platform_supported", None)
platform_supported = bool(platform_checker(None)) if callable(platform_checker) else True
available = bool(service_available and platform_supported)
enabled = bool(available and getattr(self.plugin, "enable_qzone_integration", False))
return {
"enabled": enabled,
"life_publish_enabled": bool(enabled and getattr(self.plugin, "enable_qzone_life_publish", False)),
"comment_inbox_enabled": bool(enabled and getattr(self.plugin, "enable_qzone_comment_inbox", False)),
"emotional_vent_enabled": bool(
enabled
and getattr(self.plugin, "enable_emotion_simulation", False)
and getattr(self.plugin, "enable_qzone_emotional_vent_publish", False)
),
"available": available,
"service_available": service_available,
"platform_supported": platform_supported,
"unavailable_reason": "" if platform_supported else "QQ 官方机器人不支持 QQ 空间;仅 OneBot/aiocqhttp 可用。",
"last_life_publish_at": self.plugin._format_timestamp_elapsed(state.get("last_life_publish_at", 0)),
"last_status": state.get("last_life_publish_status", ""),
"last_text": state.get("last_life_publish_text", ""),
"generated_image_enabled": bool(enabled and getattr(self.plugin, "enable_qzone_generated_image_publish", False)),
"generated_image_probability": self._float(getattr(self.plugin, "qzone_generated_image_probability", 0)),
"last_life_publish_images": self._int(state.get("last_life_publish_images")),
"last_life_publish_generated_image_status": state.get("last_life_publish_generated_image_status", ""),
"last_life_publish_generated_image_note": state.get("last_life_publish_generated_image_note", ""),
"last_life_publish_generated_image_backend": state.get("last_life_publish_generated_image_backend", ""),
"last_life_publish_generated_image_caption": state.get("last_life_publish_generated_image_caption", ""),
"last_life_publish_generated_image_reference": state.get("last_life_publish_generated_image_reference", ""),
"last_life_publish_generated_image_reference_exists": bool(state.get("last_life_publish_generated_image_reference_exists", False)),
"last_life_publish_generated_image_anchor": state.get("last_life_publish_generated_image_anchor", ""),
"last_life_publish_generated_image_composition": state.get("last_life_publish_generated_image_composition", ""),
"last_manual_publish_generated_image_status": state.get("last_manual_publish_generated_image_status", ""),
"last_manual_publish_generated_image_note": state.get("last_manual_publish_generated_image_note", ""),
"last_manual_publish_generated_image_backend": state.get("last_manual_publish_generated_image_backend", ""),
"last_manual_publish_generated_image_caption": state.get("last_manual_publish_generated_image_caption", ""),
"last_manual_publish_generated_image_reference": state.get("last_manual_publish_generated_image_reference", ""),
"last_manual_publish_generated_image_reference_exists": bool(state.get("last_manual_publish_generated_image_reference_exists", False)),
"last_manual_publish_generated_image_anchor": state.get("last_manual_publish_generated_image_anchor", ""),
"last_manual_publish_generated_image_composition": state.get("last_manual_publish_generated_image_composition", ""),
"last_emotional_vent_at": self.plugin._format_timestamp_elapsed(state.get("last_emotional_vent_at", 0)),
"last_emotional_vent_status": state.get("last_emotional_vent_status", ""),
"last_emotional_vent_text": state.get("last_emotional_vent_text", ""),
"last_emotional_vent_images": self._int(state.get("last_emotional_vent_images")),
"last_emotional_vent_generated_image_status": state.get("last_emotional_vent_generated_image_status", ""),
"last_emotional_vent_generated_image_note": state.get("last_emotional_vent_generated_image_note", ""),
"last_emotional_vent_generated_image_backend": state.get("last_emotional_vent_generated_image_backend", ""),
"last_emotional_vent_generated_image_caption": state.get("last_emotional_vent_generated_image_caption", ""),
"last_emotional_vent_generated_image_reference": state.get("last_emotional_vent_generated_image_reference", ""),
"last_emotional_vent_generated_image_reference_exists": bool(state.get("last_emotional_vent_generated_image_reference_exists", False)),
"last_emotional_vent_generated_image_anchor": state.get("last_emotional_vent_generated_image_anchor", ""),
"last_emotional_vent_generated_image_composition": state.get("last_emotional_vent_generated_image_composition", ""),
"last_comment_inbox_checked_at": self.plugin._format_timestamp_elapsed(state.get("last_comment_inbox_checked_at", 0)),
"last_comment_inbox_status": state.get("last_comment_inbox_status", ""),
"last_comment_inbox_reply_text": state.get("last_comment_inbox_reply_text", ""),
"auth_block_until": self.plugin._format_timestamp_elapsed(state.get("auth_block_until", 0)),
"auth_failure_reason": state.get("last_auth_failure_reason", ""),
"auth_failure_count": self._int(state.get("auth_failure_count")),
"auth_status": state.get("last_auth_status", ""),
"cookie_fetch_status": state.get("last_cookie_fetch_status", ""),
"cookie_fetch_reason": state.get("last_cookie_fetch_reason", ""),
"cookie_fetch_has_uin": bool(state.get("last_cookie_fetch_has_uin", False)),
"cookie_fetch_has_skey": bool(state.get("last_cookie_fetch_has_skey", False)),
"cookie_fetch_has_p_skey": bool(state.get("last_cookie_fetch_has_p_skey", False)),
"cookie_fetch_uin": state.get("last_cookie_fetch_uin", ""),
"cookie_fetch_at": self.plugin._format_timestamp_elapsed(state.get("last_cookie_fetch_at", 0)),
}
def _jm_cosmos_summary(self, data: dict[str, Any]) -> dict[str, Any]:
state = data.get("jm_cosmos_integration") if isinstance(data.get("jm_cosmos_integration"), dict) else {}
try:
@ -20044,18 +19534,6 @@ class PrivateCompanionPageApi(PrivateCompanionPageApiQzoneMixin, PrivateCompanio
return count
def _livingmemory_db_path(self) -> Path | None:
candidates: list[Path] = []
data_dir = Path(str(getattr(self.plugin, "data_dir", "") or "")).resolve()
if data_dir:
candidates.append(data_dir.parent / "astrbot_plugin_livingmemory" / "livingmemory.db")
candidates.append(data_dir.parent / "astrbot_plugin_livingmemory" / "livingmemory_graph_documents.db")
candidates.append(Path.home() / ".astrbot" / "data" / "plugin_data" / "astrbot_plugin_livingmemory" / "livingmemory.db")
for path in candidates:
try:
if path.exists() and path.is_file():
return path
except OSError:
continue
return None
def _worldbook_member_livingmemory_tokens(self, user_id: str, profile: dict[str, Any]) -> dict[str, list[str]]:

查看文件

@ -1,456 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import time
from copy import deepcopy
from types import SimpleNamespace
from typing import Any
from quart import request
from .qzone_recent_parser import parse_recent_feeds
class PrivateCompanionPageApiQzoneMixin:
async def refresh_qzone_cookies(self) -> dict[str, Any]:
try:
cookie_header = await self.plugin._qzone_get_cookies(None)
ctx = self.plugin._qzone_context_from_cookies(cookie_header)
async with self.plugin._data_lock:
state = self.plugin.data.get("qzone_integration") if isinstance(self.plugin.data.get("qzone_integration"), dict) else {}
if isinstance(state, dict):
clearer = getattr(self.plugin, "_qzone_clear_auth_failure", None)
if callable(clearer):
clearer(state)
return self._ok(
{
"refreshed": True,
"uin": int(ctx.get("uin") or 0),
"has_skey": bool(ctx.get("skey")),
"has_p_skey": bool(ctx.get("p_skey")),
}
)
except Exception as exc:
return self._error(str(exc))
async def get_qzone_status(self) -> dict[str, Any]:
try:
async with self.plugin._data_lock:
data = deepcopy(self.plugin.data if isinstance(self.plugin.data, dict) else {})
summary = self._qzone_summary(data)
login = {"bound": False, "uin": 0, "nickname": "", "avatar": ""}
if summary.get("available"):
try:
cookie_header = await self.plugin._qzone_get_cookies(None)
ctx = self.plugin._qzone_context_from_cookies(cookie_header)
login["bound"] = True
login["uin"] = int(ctx.get("uin") or 0)
login["nickname"] = f"QQ {ctx.get('uin')}"
except Exception:
pass
return self._ok(
{
"login": login,
"summary": summary,
"loaded_at": int(time.time()),
}
)
except Exception as exc:
return self._error(str(exc))
async def get_qzone_feed(self) -> dict[str, Any]:
try:
scope = self._single_line(request.args.get("scope"), 24) or "self"
hostuin = self._single_line(request.args.get("hostuin"), 40)
page = self._clamp_int(request.args.get("page"), 1, 1, 10)
target = hostuin if scope == "profile" else ""
if scope == "profile" and not target:
return self._ok({"items": [], "scope": scope, "target_uin": target})
if scope == "friends":
cookie_header = await self.plugin._qzone_get_cookies(None)
ctx = self.plugin._qzone_context_from_cookies(cookie_header)
raw = await self.plugin._qzone_request(
None,
"GET",
"https://user.qzone.qq.com/proxy/domain/ic2.qzone.qq.com/cgi-bin/feeds/feeds3_html_more",
params={
"uin": ctx["uin"],
"scope": 0,
"view": 1,
"filter": "all",
"flag": 1,
"applist": "all",
"pagenum": page,
"aisortEndTime": 0,
"aisortOffset": 0,
"aisortBeginTime": 0,
"begintime": 0,
"format": "json",
"g_tk": ctx["gtk"],
"useutf8": 1,
"outputhtmlfeed": 1,
},
cookie_header=cookie_header,
)
posts = parse_recent_feeds(raw)
return self._ok(
{
"items": [
self._qzone_page_post_payload(post, include_comments=False, viewer_uin=int(ctx.get("uin") or 0))
for post in posts[:10]
],
"scope": scope,
"page": page,
"target_uin": target,
}
)
cookie_header = await self.plugin._qzone_get_cookies(None)
ctx = self.plugin._qzone_context_from_cookies(cookie_header)
posts = await self.plugin._qzone_query_feeds(
None,
target_id=target or None,
pos=0,
num=10,
with_detail=False,
cookie_header=cookie_header,
)
return self._ok(
{
"items": [
self._qzone_page_post_payload(post, include_comments=False, viewer_uin=int(ctx.get("uin") or 0))
for post in posts
],
"scope": scope,
"page": page,
"target_uin": target,
}
)
except Exception as exc:
return self._error(str(exc))
async def get_qzone_detail(self) -> dict[str, Any]:
try:
post = await self._qzone_page_resolve_post_reference(
self._single_line(request.args.get("id") or request.args.get("post_id"), 120),
request.args,
with_detail=True,
)
cookie_header = await self.plugin._qzone_get_cookies(None)
ctx = self.plugin._qzone_context_from_cookies(cookie_header)
refreshed = await self.plugin._qzone_query_feeds(
None,
target_id=str(getattr(post, "uin", "") or ""),
pos=0,
num=10,
with_detail=True,
cookie_header=cookie_header,
)
matched = next((item for item in refreshed if str(getattr(item, "tid", "") or "") == str(getattr(post, "tid", "") or "")), post)
return self._ok({"post": self._qzone_page_post_payload(matched, include_comments=True, viewer_uin=int(ctx.get("uin") or 0))})
except Exception as exc:
return self._error(str(exc))
async def publish_qzone_post(self) -> dict[str, Any]:
try:
payload = await request.get_json(silent=True) or {}
content = self._multi_line(payload.get("content") if payload.get("content") is not None else payload.get("text"), 300)
if not content:
return self._error("说说内容不能为空")
result = await self.plugin._publish_qzone_text(content, None, images=[], auto_generate_image=True)
if not result.get("success"):
return self._error(result.get("message") or "发布失败")
return self._ok(result)
except Exception as exc:
return self._error(str(exc))
async def like_qzone_post(self) -> dict[str, Any]:
try:
payload = await request.get_json(silent=True) or {}
post = await self._qzone_page_resolve_post_reference(
self._single_line(payload.get("id") or payload.get("post_id"), 120),
payload,
with_detail=False,
)
result = await self.plugin._qzone_like_post(None, post)
setattr(post, "liked", bool(result.get("liked", True)))
return self._ok(
{
"liked": bool(result.get("liked", True)),
"verified": bool(result.get("verified")),
"verify_message": result.get("verify_message") or "",
"id": self._qzone_page_post_id(post),
}
)
except Exception as exc:
return self._error(str(exc))
async def comment_qzone_post(self) -> dict[str, Any]:
try:
payload = await request.get_json(silent=True) or {}
post = await self._qzone_page_resolve_post_reference(
self._single_line(payload.get("id") or payload.get("post_id"), 120),
payload,
with_detail=True,
)
content = self._multi_line(payload.get("content") if payload.get("content") is not None else payload.get("text"), 120)
if not content:
return self._error("评论内容不能为空")
sent = await self.plugin._qzone_comment_post(None, post, content=content)
author_uin = 0
author_name = "我"
try:
cookie_header = await self.plugin._qzone_get_cookies(None)
ctx = self.plugin._qzone_context_from_cookies(cookie_header)
author_uin = int(ctx.get("uin") or 0)
author_name = str(ctx.get("uin") or "我")
except Exception:
pass
comments = list(getattr(post, "comments", []) or [])
comments.append(
SimpleNamespace(
comment_id=f"local-{int(time.time())}",
comment_key="",
comment_legacy_id="",
uin=author_uin,
name=author_name,
content=sent,
create_time=int(time.time()),
raw={},
)
)
setattr(post, "comments", comments)
return self._ok({"post": self._qzone_page_post_payload(post, include_comments=True, viewer_uin=author_uin)})
except Exception as exc:
return self._error(str(exc))
async def delete_qzone_post(self) -> dict[str, Any]:
try:
payload = await request.get_json(silent=True) or {}
post = await self._qzone_page_resolve_post_reference(
self._single_line(payload.get("id") or payload.get("post_id"), 120),
payload,
with_detail=False,
)
cookie_header = await self.plugin._qzone_get_cookies(None)
ctx = self.plugin._qzone_context_from_cookies(cookie_header)
viewer_uin = int(ctx.get("uin") or 0)
if not self._qzone_page_can_delete(post, viewer_uin=viewer_uin):
return self._error("只能删除当前登录 QQ 自己发布的说说")
await self.plugin._qzone_delete_post(None, post, cookie_header=cookie_header)
post_id = self._qzone_page_post_id(post)
self._qzone_page_store().pop(post_id, None)
return self._ok({"deleted": True, "id": post_id})
except Exception as exc:
return self._error(str(exc))
def _qzone_page_store(self) -> dict[str, Any]:
store = getattr(self, "_qzone_page_posts", None)
if not isinstance(store, dict):
store = {}
self._qzone_page_posts = store
return store
def _qzone_page_post_id(self, post: Any) -> str:
return f"{self._single_line(getattr(post, 'uin', ''), 40)}:{self._single_line(getattr(post, 'tid', ''), 80)}"
def _qzone_page_remember_post(self, post: Any) -> str:
post_id = self._qzone_page_post_id(post)
self._qzone_page_store()[post_id] = post
return post_id
def _qzone_page_resolve_post(self, post_id: str) -> Any:
post = self._qzone_page_store().get(str(post_id or "").strip())
if post is None:
raise RuntimeError("说说引用已失效,请刷新页面后重试")
return post
async def _qzone_page_resolve_post_reference(self, post_id: str = "", source: Any = None, *, with_detail: bool = False) -> Any:
post_key = self._single_line(post_id, 160)
if post_key:
post = self._qzone_page_store().get(post_key)
if post is not None:
return post
def pick(*keys: str) -> str:
getter = getattr(source, "get", None)
if not callable(getter):
return ""
for key in keys:
value = getter(key)
if value not in (None, ""):
return self._single_line(value, 160)
return ""
hostuin = pick("hostuin", "host_uin", "uin", "author_uin", "target_uin")
fid = pick("fid", "tid", "post_tid")
topic_id = pick("topicId", "topic_id")
if topic_id and "_" in topic_id:
topic_parts = topic_id.split("_")
if len(topic_parts) >= 2:
hostuin = hostuin or self._single_line(topic_parts[0], 40)
fid = fid or self._single_line(topic_parts[1], 120)
if post_key and ":" in post_key:
left, right = post_key.split(":", 1)
hostuin = hostuin or self._single_line(left, 40)
fid = fid or self._single_line(right, 120)
if not fid:
raise RuntimeError("说说引用已失效,请刷新页面后重试")
cookie_header = await self.plugin._qzone_get_cookies(None)
if not hostuin:
ctx = self.plugin._qzone_context_from_cookies(cookie_header)
hostuin = self._single_line(ctx.get("uin"), 40)
if not hostuin:
raise RuntimeError("说说引用已失效,请刷新页面后重试")
posts = await self.plugin._qzone_query_feeds(
None,
target_id=hostuin,
pos=0,
num=20,
with_detail=with_detail,
cookie_header=cookie_header,
)
for post in posts:
post_tid = self._single_line(getattr(post, "tid", ""), 120)
post_fid = self._single_line(getattr(post, "fid", ""), 120)
if fid and fid in {post_tid, post_fid}:
self._qzone_page_remember_post(post)
return post
raise RuntimeError("未找到这条说说,请刷新动态后重试")
@staticmethod
def _qzone_page_raw_value(post: Any, *keys: str) -> Any:
raw = getattr(post, "raw", None)
for key in keys:
value = getattr(post, key, None)
if value not in (None, ""):
return value
if isinstance(raw, dict):
value = raw.get(key)
if value not in (None, ""):
return value
return None
def _qzone_page_like_count(self, post: Any) -> int:
raw = getattr(post, "raw", None)
for key in ("like_count", "likecount", "likes", "likenum", "praise_num", "praisenum"):
value = self._qzone_page_raw_value(post, key)
try:
if value not in (None, ""):
return max(0, int(float(value)))
except Exception:
pass
if isinstance(raw, dict):
for container_key in ("like", "likeinfo", "like_info", "praise", "praiseinfo"):
container = raw.get(container_key)
if not isinstance(container, dict):
continue
for key in ("count", "num", "total", "like_count", "likecount"):
try:
value = container.get(key)
if value not in (None, ""):
return max(0, int(float(value)))
except Exception:
pass
return 0
def _qzone_page_liked(self, post: Any) -> bool:
for key in ("liked", "has_liked", "isliked", "is_liked", "selfliked", "haslike", "has_like"):
value = self._qzone_page_raw_value(post, key)
if isinstance(value, bool):
return value
text = str(value or "").strip().lower()
if text in {"1", "true", "yes", "y"}:
return True
if text in {"0", "false", "no", "n"}:
return False
return bool(getattr(post, "liked", False))
@staticmethod
def _qzone_page_can_delete(post: Any, *, viewer_uin: int = 0) -> bool:
if not viewer_uin:
return False
try:
post_uin = int(getattr(post, "uin", 0) or 0)
except Exception:
post_uin = 0
return bool(post_uin and post_uin == int(viewer_uin))
def _qzone_page_image_items(self, post: Any) -> list[dict[str, str]]:
"""Normalize QQ Space image variants without forcing a large image into the feed."""
raw_items = getattr(post, "image_items", None)
if not isinstance(raw_items, list):
raw_items = getattr(post, "images", None)
if not isinstance(raw_items, list):
return []
def clean(value: Any) -> str:
source = self._single_line(value, 2000).strip()
return source if source.lower().startswith(("https://", "http://", "//", "data:image/")) else ""
def pick(item: Any, *keys: str) -> str:
if not isinstance(item, dict):
return clean(item)
for key in keys:
source = clean(item.get(key))
if source:
return source
return ""
items: list[dict[str, str]] = []
for item in raw_items:
preview_url = pick(item, "preview_url", "thumbnail_url", "thumb_url", "small_url", "url", "src", "image_url")
full_url = pick(
item,
"full_url",
"original_url",
"origin_url",
"raw_url",
"large_url",
"big_url",
"url",
"src",
"image_url",
)
if not (preview_url or full_url):
continue
normalized = {"preview_url": preview_url or full_url, "full_url": full_url or preview_url}
if normalized not in items:
items.append(normalized)
return items
def _qzone_page_post_payload(self, post: Any, *, include_comments: bool = False, viewer_uin: int = 0) -> dict[str, Any]:
image_items = self._qzone_page_image_items(post)
payload = {
"id": self._qzone_page_remember_post(post),
"tid": self._single_line(getattr(post, "tid", ""), 80),
"author": {
"uin": int(getattr(post, "uin", 0) or 0),
"nickname": self._single_line(getattr(post, "name", ""), 80) or str(getattr(post, "uin", "") or "QQ空间用户"),
},
"content": self._multi_line(getattr(post, "text", "") or getattr(post, "rt_con", ""), 1200),
"created_at": int(getattr(post, "create_time", 0) or 0),
"created_at_text": self.plugin._format_timestamp_elapsed(getattr(post, "create_time", 0)) if callable(getattr(self.plugin, "_format_timestamp_elapsed", None)) else "",
"images": [item["full_url"] for item in image_items],
"image_items": image_items,
"stats": {
"likes": self._qzone_page_like_count(post),
"comments": len(getattr(post, "comments", []) or []),
},
"liked": self._qzone_page_liked(post),
"can_delete": self._qzone_page_can_delete(post, viewer_uin=viewer_uin),
}
if include_comments:
payload["comments"] = [
{
"id": self._single_line(getattr(comment, "comment_id", ""), 120),
"author": {
"uin": int(getattr(comment, "uin", 0) or 0),
"nickname": self._single_line(getattr(comment, "name", ""), 80) or str(getattr(comment, "uin", "") or "QQ空间用户"),
},
"content": self._multi_line(getattr(comment, "content", ""), 300),
"created_at": int(getattr(comment, "create_time", 0) or 0),
}
for comment in list(getattr(post, "comments", []) or [])
]
return payload

查看文件

@ -137,6 +137,32 @@ const state = {
let setupGuideProactivePollTimer = null;
const SETUP_GUIDE_PROACTIVE_TEST_TIMEOUT_MS = 120000;
const opsRemovedFeatureKeys = new Set([
"enable_livingmemory_integration", "enable_food_menu_recommendation", "enable_meal_care_proactive",
"enable_poke_action", "enable_qq_presence_sync", "enable_qq_custom_presence_sync",
"enable_screen_glance_action", "enable_unanswered_screen_peek_followup",
"enable_bilibili_integration", "enable_bilibili_boredom_watch", "enable_news_integration",
"enable_news_boredom_read", "enable_news_daily_hot_read", "enable_ai_daily_watch",
"enable_web_exploration", "enable_web_exploration_boredom_search", "enable_qzone_integration",
"enable_qzone_life_publish", "enable_qzone_generated_image_publish", "enable_qzone_comment_inbox",
"enable_qzone_emotional_vent_publish", "enable_external_event_self_link",
]);
function opsFeatureRemoved(key) {
const value = String(key || "");
return opsRemovedFeatureKeys.has(value)
|| value.startsWith("qzone_")
|| value.startsWith("bilibili_")
|| value.startsWith("news_")
|| value.startsWith("web_exploration")
|| value.startsWith("meal_care")
|| value.startsWith("food_menu")
|| value.startsWith("screen_peek_")
|| value.startsWith("unanswered_screen_peek_")
|| value.startsWith("poke_action_")
|| value.startsWith("qq_presence_");
}
const hiddenCompatibilityConfigKeys = new Set([
"enable_semantic_message_debounce",
"semantic_message_debounce_seconds",
@ -1245,6 +1271,7 @@ function proactiveOnlyRelatedUnlocks(key) {
}
function visibleFeatureSwitchKey(key) {
if (opsFeatureRemoved(key)) return false;
if (key === "enable_proactive_only_mode") return false;
if (hiddenCompatibilityConfigKeys.has(key)) return false;
if (featureSwitchExcludedKeys.has(key)) return false;
@ -4832,7 +4859,7 @@ function renderActiveTab(tabName = state.activeTab || "dashboard") {
const meta = document.getElementById("qzoneFeedMeta");
const feed = document.getElementById("qzoneFeed");
if (meta) meta.textContent = "QQ 空间面板脚本未加载";
if (feed && !feed.innerHTML.trim()) feed.innerHTML = `<div class="empty small">QQ 空间面板脚本未加载。请刷新拓展页;若仍失败,检查 qzone-panel.js 是否被浏览器拦截。</div>`;
if (feed && !feed.innerHTML.trim()) feed.innerHTML = `<div class="empty small">该面板已从运维版移除。</div>`;
}
} else if (tabName === "image-cache") {
renderImageCache();
@ -19536,11 +19563,12 @@ function renderFeatureSwitches() {
const filter = ($("#featureFilter")?.value || "").trim().toLowerCase();
renderProactiveOnlyModeCard();
renderPassiveInjectionPositionForm();
const knownKeys = new Set(featureGroups.flatMap((group) => group.keys));
const visibleGroups = featureGroups.map((group) => ({ ...group, keys: group.keys.filter(visibleFeatureSwitchKey) })).filter((group) => group.keys.length);
const knownKeys = new Set(visibleGroups.flatMap((group) => group.keys));
const extraKeys = Object.keys(state.featureDraft || {}).filter((key) => !knownKeys.has(key) && visibleFeatureSwitchKey(key));
const groups = extraKeys.length
? [...featureGroups, { title: "其他", note: "来自配置但暂未归入固定分组的开关。", keys: extraKeys }]
: featureGroups;
? [...visibleGroups, { title: "其他", note: "来自配置但暂未归入固定分组的开关。", keys: extraKeys }]
: visibleGroups;
const overviewSettings = state.overview?.settings || {};
const intensity = state.overview?.proactive_intensity || {};
const intensitySearchText = "主动强度预设 主动触达 proactive_intensity_preset 私聊主动 群聊唤醒 群主动插话";

查看文件

@ -1,142 +0,0 @@
@media (max-width: 860px) {
#panel-qzone .section-head {
align-items: stretch;
flex-direction: column;
gap: 12px;
}
#panel-qzone .section-head .actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
width: 100%;
}
#panel-qzone .section-head .actions button,
.qzone-scope-switch button,
.qzone-post-card footer button,
.qzone-detail-actions button,
.qzone-comment-form button,
#qzoneTargetForm button,
#qzonePublishForm button {
min-height: 42px;
border-radius: 9px;
font-weight: 800;
}
.qzone-shell {
grid-template-columns: 1fr;
gap: 12px;
}
.qzone-rail,
.qzone-detail-pane {
position: static;
}
.qzone-rail {
display: grid;
grid-template-columns: 1fr;
gap: 12px;
}
.qzone-mini-summary {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
.qzone-scope-switch {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 3px;
}
#qzoneTargetForm,
#qzonePublishForm,
.qzone-comment-form {
display: grid;
grid-template-columns: 1fr;
gap: 8px;
}
#qzoneTargetForm input,
#qzonePublishForm textarea,
.qzone-comment-form textarea,
#qzoneTargetForm button,
#qzonePublishForm button,
.qzone-comment-form button {
width: 100%;
}
.qzone-feed-head,
.qzone-post-card header,
.qzone-detail-head,
.qzone-comment-head {
align-items: flex-start;
gap: 10px;
}
.qzone-post-card footer {
display: grid;
grid-template-columns: 1fr;
gap: 10px;
width: 100%;
}
.qzone-detail-actions {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 8px;
width: 100%;
}
.qzone-detail-actions .danger-outline {
grid-column: 1 / -1;
}
.qzone-post-text,
.qzone-detail-text,
.qzone-comment-item p,
.qzone-comment-item b {
overflow-wrap: anywhere;
}
.qzone-post-media,
.qzone-detail-media {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
.qzone-post-media img,
.qzone-detail-media img {
width: 100%;
max-width: 100%;
object-fit: cover;
}
.qzone-detail-pane {
min-width: 0;
}
}
@media (max-width: 480px) {
#panel-qzone .section-head .actions,
.qzone-post-card footer,
.qzone-detail-actions,
.qzone-mini-summary,
.qzone-scope-switch,
.qzone-post-media,
.qzone-detail-media {
grid-template-columns: 1fr;
}
.qzone-card,
.qzone-post-card,
.qzone-detail-card,
.qzone-comment-block,
.qzone-empty {
padding: 12px;
}
.qzone-post-badge {
justify-self: flex-start;
}
}

查看文件

@ -6,7 +6,6 @@
<title>陪伴面板</title>
<link rel="stylesheet" href="./app.css?v=20260722-expression-editor" />
<link rel="stylesheet" href="./css/header-tools.css?v=20260713-font-options" />
<link rel="stylesheet" href="./css/qzone-mobile.css?v=20260711-qzone-image-preview" />
<link rel="stylesheet" href="./css/polish.css?v=20260715-learning-nav-merged-v1" />
<script>
(function () {
@ -115,7 +114,6 @@
<button class="tab" data-tab="memory"><i>06</i><span>观察</span></button>
<button class="tab" data-tab="proactive"><i>07</i><span>主动</span></button>
<button class="tab" data-tab="bookshelf"><i>08</i><span>书柜</span></button>
<button class="tab" data-tab="qzone"><i>09</i><span>QQ空间</span></button>
<button class="tab" data-tab="tokens"><i>10</i><span>Token</span></button>
<button class="tab" data-tab="troubleshooting"><i>11</i><span>排障</span></button>
<button class="tab" data-tab="config"><i>12</i><span>配置</span></button>
@ -1441,91 +1439,6 @@ QQ空间 = 公开札记
</div>
</section>
<section class="panel qzone-panel" id="panel-qzone">
<div class="section-head">
<div class="qzone-title-block">
<span class="qzone-kicker">社交动态工作台</span>
<h2>QQ 空间</h2>
<span class="muted">动态、互动与发布</span>
</div>
<div class="actions compact qzone-top-actions">
<button id="qzoneRefreshCookiesBtn" class="qzone-secondary-action" type="button">刷新 Cookies</button>
<button id="qzoneRefreshBtn" class="qzone-primary-action" type="button">刷新动态</button>
</div>
</div>
<div class="qzone-shell">
<aside class="qzone-rail">
<article class="qzone-card qzone-account-card">
<div class="qzone-account-head">
<div class="qzone-account-avatar-wrap">
<img id="qzoneAccountAvatar" class="qzone-account-avatar" alt="" hidden />
<span id="qzoneAccountAvatarFallback" class="qzone-account-avatar-fallback" aria-hidden="true">Q</span>
</div>
<div class="qzone-account-copy">
<div class="qzone-account-title-row">
<h3 id="qzoneAccountName">QQ 空间</h3>
<span id="qzoneAccountStatus" class="qzone-status-pill" data-tone="idle">等待同步</span>
</div>
<p id="qzoneAccountMeta" class="qzone-account-meta muted">等待加载</p>
</div>
</div>
<div id="qzoneQuickSummary" class="qzone-mini-summary"></div>
</article>
<article class="qzone-card qzone-filter-card">
<div class="qzone-card-head">
<h3>浏览范围</h3>
</div>
<div class="qzone-scope-switch" role="group" aria-label="动态范围">
<button type="button" class="active" data-qzone-scope="friends" aria-pressed="true">好友动态</button>
<button type="button" data-qzone-scope="self" aria-pressed="false">我的空间</button>
<button type="button" data-qzone-scope="profile" aria-pressed="false">指定 QQ</button>
</div>
<form id="qzoneTargetForm" class="inline-form compact-form">
<input id="qzoneTargetUin" inputmode="numeric" placeholder="输入 QQ 号后查看" />
<button type="submit">查看</button>
</form>
</article>
<article class="qzone-card qzone-compose-card">
<div class="qzone-card-head">
<h3>发布说说</h3>
<span class="qzone-public-badge">公开</span>
</div>
<form id="qzonePublishForm" class="stack-form">
<textarea id="qzonePublishContent" rows="5" placeholder="写点公开发到 QQ 空间的话"></textarea>
<button type="submit">发布到空间</button>
</form>
</article>
</aside>
<div class="qzone-main">
<div id="qzoneNotice" class="qzone-notice" hidden></div>
<div class="qzone-feed-head">
<div>
<span class="qzone-kicker">最新动态</span>
<h3>空间动态</h3>
<span id="qzoneFeedMeta" class="muted">准备加载</span>
</div>
<span id="qzoneFeedState" class="qzone-feed-state" data-state="idle" aria-live="polite">待同步</span>
</div>
<div id="qzoneFeed" class="qzone-feed-list"></div>
</div>
<aside class="qzone-detail-pane" aria-label="动态详情">
<div class="qzone-detail-pane-head">
<span class="qzone-kicker">当前选择</span>
<h3>动态详情</h3>
</div>
<div id="qzoneDetailEmpty" class="qzone-empty detail-empty">
<b>选择一条说说</b>
<span>这里会显示完整内容和评论。</span>
</div>
<div id="qzoneDetailContent" hidden></div>
</aside>
</div>
</section>
<section class="panel" id="panel-experimental">
<div id="experimentalRoot" class="experimental-root"></div>
</section>
@ -1567,7 +1480,6 @@ QQ空间 = 公开札记
<script src="./js/features/daily-outfit.js?v=20260711-qzone-preview-context"></script>
<script src="./js/ui/appearance.js?v=20260713-font-options"></script>
<script src="./js/panels/provider-tree.js?v=20260711-provider-debug"></script>
<script src="./js/panels/qzone-panel.js?v=20260711-qzone-preview-context"></script>
<script src="./app.js?v=20260722-expression-editor"></script>
</body>
</html>

查看文件

@ -1,656 +0,0 @@
window.PrivateCompanionQzonePanel = (() => {
const state = {
initialized: false,
status: null,
scope: "friends",
targetUin: "",
posts: [],
selectedId: "",
loading: false,
loaded: false,
page: 1,
pendingLikes: new Set(),
pendingDeletes: new Set(),
deleteConfirmId: "",
deleteConfirmAt: 0,
detailLoadingId: "",
context: null,
};
function text(value) {
return String(value ?? "");
}
function postById(id) {
return state.posts.find((item) => item.id === id) || null;
}
function setNotice(message = "", tone = "info") {
const notice = document.getElementById("qzoneNotice");
if (!notice) return;
notice.hidden = !message;
notice.textContent = message;
notice.dataset.tone = tone;
}
function isRouteMissingError(error) {
return /未找到该路由|找不到该路由|路由不存在|route\s*(?:not\s*found|missing)|not\s*found.*route|^not\s*found$|HTTP\s*404|\b404\b/i.test(String(error?.message || "").trim());
}
async function qzoneFetch(paths) {
const candidates = Array.isArray(paths) ? paths : [paths];
let lastError = null;
for (const path of candidates) {
try {
return await state.context.fetchJson(path);
} catch (error) {
lastError = error;
if (!isRouteMissingError(error)) break;
}
}
throw lastError || new Error("QQ 空间请求失败");
}
async function qzonePost(paths, body = {}) {
const candidates = Array.isArray(paths) ? paths : [paths];
let lastError = null;
for (const path of candidates) {
try {
return await state.context.postJson(path, body);
} catch (error) {
lastError = error;
if (!isRouteMissingError(error)) break;
}
}
throw lastError || new Error("QQ 空间请求失败");
}
async function refreshCookies() {
return qzonePost([
"/qzone/refresh_cookies",
"/qzone/refresh-cookies",
"/qzone/cookies/refresh",
"/qzone/refresh",
"/qzone/cookie/refresh",
], {});
}
function renderAccount() {
const login = state.status?.login || {};
const summary = state.status?.summary || {};
const name = document.getElementById("qzoneAccountName");
const meta = document.getElementById("qzoneAccountMeta");
const accountName = login.nickname || (login.uin ? `QQ ${login.uin}` : "未绑定");
if (name) name.textContent = accountName;
const avatar = document.getElementById("qzoneAccountAvatar");
const avatarFallback = document.getElementById("qzoneAccountAvatarFallback");
const avatarUrl = text(login.avatar).trim();
if (avatar) {
if (avatarUrl) avatar.src = avatarUrl;
else avatar.removeAttribute("src");
avatar.hidden = !avatarUrl;
}
if (avatarFallback) {
avatarFallback.hidden = Boolean(avatarUrl);
avatarFallback.textContent = Array.from(accountName.trim())[0] || "Q";
}
const accountStatus = document.getElementById("qzoneAccountStatus");
if (accountStatus) {
const tone = !state.status ? "idle" : (summary.enabled ? "ready" : (summary.available ? "warn" : "error"));
const label = !state.status ? "同步中" : (summary.enabled ? "已连接" : (summary.available ? "未启用" : "不可用"));
accountStatus.dataset.tone = tone;
accountStatus.textContent = label;
}
if (meta) {
meta.textContent = !state.status
? "正在读取 QQ 空间状态"
: summary.enabled
? `QQ 空间已启用 · ${summary.last_status || "等待操作"}`
: (summary.available ? "QQ 空间模块已加载,但整合开关未开启" : (summary.unavailable_reason || "QQ 空间模块不可用"));
}
const summaryBox = document.getElementById("qzoneQuickSummary");
if (summaryBox) {
const imageStatus = summary.last_life_publish_generated_image_status || "";
const imageNote = summary.last_life_publish_generated_image_note || "";
const imageLabel = summary.last_life_publish_images > 0
? `${summary.last_life_publish_images} 张`
: (imageStatus ? imageStatus.replace(/^skipped:/, "跳过:").replace(/^failed:/, "失败:") : `${state.posts.length} 条`);
const referenceMeta = summary.last_life_publish_generated_image_reference
? `参考图${summary.last_life_publish_generated_image_reference_exists ? "可用" : "不可用"}`
: "";
const designMeta = [summary.last_life_publish_generated_image_anchor, summary.last_life_publish_generated_image_composition]
.filter(Boolean)
.join(" / ");
const imageMeta = summary.generated_image_enabled
? ([imageNote, designMeta, referenceMeta].filter(Boolean).join(" · ") || `配图概率 ${Math.round(Number(summary.generated_image_probability || 0) * 100)}%`)
: "说说配图关闭";
summaryBox.innerHTML = `
<article data-state="${summary.life_publish_enabled ? "ready" : "idle"}"><span>生活说说</span><b>${summary.life_publish_enabled ? "开启" : "关闭"}</b></article>
<article data-state="${summary.comment_inbox_enabled ? "ready" : "idle"}"><span>评论收件箱</span><b>${summary.comment_inbox_enabled ? "开启" : "关闭"}</b></article>
<article data-state="info" title="${state.context.escapeHtml(imageMeta)}"><span>最近配图</span><b>${state.context.escapeHtml(imageLabel)}</b></article>
`;
}
}
function postAuthorName(post) {
return post.author?.nickname || post.author?.uin || "QQ空间用户";
}
function renderPostIdentity(post) {
const { escapeHtml } = state.context;
const author = postAuthorName(post);
const initial = Array.from(String(author).trim())[0] || "Q";
return `
<div class="qzone-post-identity">
<span class="qzone-author-mark" aria-hidden="true">${escapeHtml(initial)}</span>
<div>
<b>${escapeHtml(author)}</b>
<small>${escapeHtml(post.created_at_text || "刚刚")}</small>
</div>
</div>
`;
}
function renderPostMetrics(post) {
const { escapeHtml } = state.context;
return `
<div class="qzone-post-feedback" aria-label="互动数据">
<span>${escapeHtml(post.stats?.likes ?? 0)} 赞</span>
<span>${escapeHtml(post.stats?.comments ?? 0)} 评论</span>
</div>
`;
}
function qzoneImageItems(post) {
const rawItems = Array.isArray(post?.image_items) && post.image_items.length
? post.image_items
: (Array.isArray(post?.images) ? post.images : []);
return rawItems.map((item) => {
if (item && typeof item === "object") {
const previewUrl = text(item.preview_url || item.thumbnail_url || item.thumb_url || item.url || item.src || item.image_url).trim();
const fullUrl = text(item.full_url || item.original_url || item.origin_url || item.raw_url || item.large_url || item.url || item.src || item.image_url).trim();
return { previewUrl: previewUrl || fullUrl, fullUrl: fullUrl || previewUrl };
}
const source = text(item).trim();
return { previewUrl: source, fullUrl: source };
}).filter((item) => item.previewUrl || item.fullUrl);
}
function renderPreviewImage(item, post) {
const { escapeHtml } = state.context;
const author = postAuthorName(post);
const alt = `${author}的说说图片`;
const meta = ["QQ 空间图片", author, post.created_at_text || "刚刚"].filter(Boolean).join(" · ");
const previewUrl = text(item?.previewUrl).trim();
const fullUrl = text(item?.fullUrl || previewUrl).trim();
if (!previewUrl || !fullUrl) return "";
return `<img class="qzone-preview-image" src="${escapeHtml(previewUrl)}" alt="${escapeHtml(alt)}" loading="lazy" data-qzone-preview-image data-qzone-preview-src="${escapeHtml(fullUrl)}" data-qzone-preview-fallback-src="${escapeHtml(previewUrl)}" data-qzone-preview-meta="${escapeHtml(meta)}" tabindex="0" role="button" title="点击放大预览,滚轮缩放" />`;
}
function openImagePreview(image) {
if (!image || !state.context) return false;
const preview = window.PrivateCompanionDailyOutfit?.openImagePreview;
const source = image.dataset.qzonePreviewSrc || image.currentSrc || image.src || image.getAttribute("src") || "";
const fallbackSrc = image.dataset.qzonePreviewFallbackSrc || image.currentSrc || image.src || image.getAttribute("src") || "";
if (!preview || !source) return false;
return preview({ ...state.context, document }, {
src: source,
fallbackSrc,
alt: image.alt || "QQ 空间图片",
meta: image.dataset.qzonePreviewMeta || image.alt || "QQ 空间图片",
});
}
function renderFeed() {
const feed = document.getElementById("qzoneFeed");
const meta = document.getElementById("qzoneFeedMeta");
const feedState = document.getElementById("qzoneFeedState");
if (!feed || !meta) return;
if (feedState) {
feedState.dataset.state = state.loading ? "loading" : (state.loaded ? "ready" : "idle");
feedState.textContent = state.loading ? "同步中" : (state.loaded ? "已同步" : "待同步");
}
meta.textContent = state.loading
? "正在同步动态..."
: `${state.scope === "profile" ? (state.targetUin || "指定 QQ") : state.scope === "friends" ? "好友动态" : "我的空间"} · ${state.posts.length} 条`;
if (!state.posts.length) {
feed.innerHTML = state.loading
? `<div class="qzone-feed-skeleton" role="status" aria-label="正在同步空间动态"><span></span><span></span><span></span></div>`
: `<div class="qzone-empty"><b>暂无可显示的说说</b><span>可以先刷新,或切换到指定 QQ 试试。</span></div>`;
renderDetail();
return;
}
const { escapeHtml } = state.context;
feed.innerHTML = state.posts.map((post) => `
<article class="qzone-post-card ${state.selectedId === post.id ? "is-active" : ""}" data-qzone-open="${escapeHtml(post.id)}">
<header>
${renderPostIdentity(post)}
<span class="qzone-post-badge">${post.can_delete ? "我的说说" : "动态"}</span>
</header>
<p class="qzone-post-text">${escapeHtml(post.content || "无正文")}</p>
${qzoneImageItems(post).length ? `
<div class="qzone-post-media">
${qzoneImageItems(post).slice(0, 4).map((item) => renderPreviewImage(item, post)).join("")}
</div>
` : ""}
<footer>
${renderPostMetrics(post)}
<div class="qzone-post-actions">
<button type="button" data-qzone-like="${escapeHtml(post.id)}" ${state.pendingLikes.has(post.id) ? "disabled" : ""}>点赞</button>
<button type="button" data-qzone-open="${escapeHtml(post.id)}">评论</button>
${post.can_delete ? `<button type="button" class="danger-outline" data-qzone-delete="${escapeHtml(post.id)}" ${state.pendingDeletes.has(post.id) ? "disabled" : ""}>删除</button>` : ""}
</div>
</footer>
</article>
`).join("");
renderDetail();
}
function renderDetail() {
const empty = document.getElementById("qzoneDetailEmpty");
const detail = document.getElementById("qzoneDetailContent");
if (!empty || !detail) return;
const post = postById(state.selectedId);
if (!post) {
empty.hidden = false;
detail.hidden = true;
detail.innerHTML = "";
return;
}
empty.hidden = true;
detail.hidden = false;
const { escapeHtml } = state.context;
detail.innerHTML = `
<div class="qzone-detail-card">
<div class="qzone-detail-head">
${renderPostIdentity(post)}
<div class="qzone-detail-actions">
<button type="button" data-qzone-like="${escapeHtml(post.id)}" ${state.pendingLikes.has(post.id) ? "disabled" : ""}>点赞这条</button>
${post.can_delete ? `<button type="button" class="danger-outline" data-qzone-delete="${escapeHtml(post.id)}" ${state.pendingDeletes.has(post.id) ? "disabled" : ""}>删除说说</button>` : ""}
</div>
</div>
<p class="qzone-detail-text">${escapeHtml(post.content || "无正文")}</p>
${qzoneImageItems(post).length ? `
<div class="qzone-detail-media">
${qzoneImageItems(post).map((item) => renderPreviewImage(item, post)).join("")}
</div>
` : ""}
${renderPostMetrics(post)}
</div>
<div class="qzone-comment-block">
<div class="qzone-comment-head">
<b>全部评论</b>
<span>${escapeHtml(post.comments?.length ?? 0)} 条</span>
</div>
<div class="qzone-comment-list">
${(post.comments || []).length ? post.comments.map((comment) => `
<article class="qzone-comment-item">
<b>${escapeHtml(comment.author?.nickname || comment.author?.uin || "QQ空间用户")}</b>
<p>${escapeHtml(comment.content || "")}</p>
</article>
`).join("") : `<div class="qzone-empty compact"><span>还没有评论。</span></div>`}
</div>
<form id="qzoneCommentForm" class="qzone-comment-form">
<textarea id="qzoneCommentInput" rows="3" placeholder="写一条公开评论"></textarea>
<button type="submit">发送评论</button>
</form>
</div>
`;
const form = document.getElementById("qzoneCommentForm");
form?.addEventListener("submit", async (event) => {
event.preventDefault();
const input = document.getElementById("qzoneCommentInput");
const content = input?.value || "";
await sendComment(content);
if (input) input.value = "";
});
}
async function loadStatus(force = false) {
if (state.status && !force) return state.status;
try {
state.status = await qzoneFetch(["/qzone/status", "/qzone/summary", "/qzone/state", "/qzone/health"]);
renderAccount();
return state.status;
} catch (error) {
state.status = state.status || { login: { bound: false, uin: 0, nickname: "", avatar: "" }, summary: { enabled: false, available: false } };
setNotice(`状态加载失败:${error.message}`, "error");
renderAccount();
throw error;
}
}
async function loadFeed(force = false) {
if (state.scope === "profile" && !state.targetUin.trim()) {
state.posts = [];
state.loaded = false;
state.loading = false;
setNotice("输入 QQ 号后查看指定空间。", "warn");
renderFeed();
return state.posts;
}
if (state.loaded && !force) {
renderFeed();
return state.posts;
}
state.loading = true;
setNotice("", "info");
renderFeed();
try {
const params = new URLSearchParams();
params.set("scope", state.scope);
params.set("page", String(state.page || 1));
if (state.scope === "profile" && state.targetUin.trim()) params.set("hostuin", state.targetUin.trim());
const query = params.toString();
const payload = await qzoneFetch([
`/qzone/feed?${query}`,
`/qzone/feeds?${query}`,
`/qzone/list?${query}`,
]);
state.posts = Array.isArray(payload.items) ? payload.items : [];
state.loaded = true;
if (!state.selectedId && state.posts[0]) state.selectedId = state.posts[0].id;
renderAccount();
renderFeed();
return state.posts;
} catch (error) {
state.posts = [];
state.loaded = false;
state.selectedId = "";
setNotice(`动态加载失败:${error.message}`, "error");
renderFeed();
throw error;
} finally {
state.loading = false;
renderFeed();
}
}
async function openDetail(id) {
if (!id) return;
state.selectedId = id;
state.detailLoadingId = id;
renderFeed();
try {
const encodedId = encodeURIComponent(id);
const payload = await qzoneFetch([
`/qzone/detail?id=${encodedId}`,
`/qzone/post?id=${encodedId}`,
`/qzone/item?id=${encodedId}`,
]);
const post = payload.post;
if (post) {
state.posts = state.posts.map((item) => (item.id === id ? post : item));
}
} finally {
state.detailLoadingId = "";
renderFeed();
}
}
async function likePost(id) {
const post = postById(id);
if (!post) return;
state.pendingLikes.add(id);
renderFeed();
try {
const payload = await qzonePost(["/qzone/like", "/qzone/post/like"], { id });
state.posts = state.posts.map((item) => (
item.id === id
? {
...item,
liked: Boolean(payload?.liked),
stats: {
...(item.stats || {}),
likes: Number(item.stats?.likes || 0) + (!item.liked && payload?.liked ? 1 : 0),
},
}
: item
));
state.context.showToast(payload?.verified ? "点赞已确认" : (payload?.verify_message || "已发送点赞请求"));
} catch (error) {
state.context.showToast(`点赞失败:${error.message}`, "error");
} finally {
state.pendingLikes.delete(id);
renderFeed();
}
}
async function sendComment(content) {
const post = postById(state.selectedId);
const clean = text(content).trim();
if (!post || !clean) return;
try {
const payload = await qzonePost(["/qzone/comment", "/qzone/post/comment"], { id: post.id, content: clean });
if (payload?.post) {
state.posts = state.posts.map((item) => (item.id === post.id ? payload.post : item));
}
state.context.showToast("评论已发送");
renderFeed();
} catch (error) {
state.context.showToast(`评论失败:${error.message}`, "error");
}
}
function confirmDeletePost(id, button = null) {
const now = Date.now();
if (state.deleteConfirmId === id && now - state.deleteConfirmAt <= 6000) return true;
state.deleteConfirmId = id;
state.deleteConfirmAt = now;
if (button) {
if (!button.dataset.originalText) button.dataset.originalText = button.textContent || "删除";
button.textContent = "再次点击删除";
button.classList.add("is-confirming");
window.setTimeout(() => {
if (state.deleteConfirmId === id && Date.now() - state.deleteConfirmAt >= 5900) {
state.deleteConfirmId = "";
state.deleteConfirmAt = 0;
}
if (button.isConnected && button.dataset.originalText) {
button.textContent = button.dataset.originalText;
delete button.dataset.originalText;
button.classList.remove("is-confirming");
}
}, 6000);
}
state.context.showToast("再次点击会删除这条说说", "warn");
return false;
}
async function deletePost(id, button = null) {
const cleanId = text(id).trim();
if (!cleanId) {
state.context.showToast("没有拿到说说 ID,请刷新动态后重试", "error");
return;
}
const post = postById(cleanId);
if (!post) {
state.context.showToast("这条说说的页面引用已失效,请刷新动态后重试", "error");
return;
}
if (!post.can_delete) {
state.context.showToast("只能删除当前登录 QQ 自己发布的说说", "error");
return;
}
if (state.pendingDeletes.has(cleanId)) return;
if (!confirmDeletePost(cleanId, button)) return;
state.deleteConfirmId = "";
state.deleteConfirmAt = 0;
state.pendingDeletes.add(cleanId);
renderFeed();
try {
state.context.showToast("正在删除说说...");
await qzonePost(["/qzone/delete", "/qzone/post/delete"], { id: cleanId });
state.posts = state.posts.filter((item) => item.id !== cleanId);
if (state.selectedId === cleanId) state.selectedId = state.posts[0]?.id || "";
state.context.showToast("说说已删除");
} catch (error) {
state.context.showToast(`删除失败:${error.message}`, "error");
} finally {
state.pendingDeletes.delete(cleanId);
renderAccount();
renderFeed();
}
}
async function publish() {
const input = document.getElementById("qzonePublishContent");
const content = text(input?.value).trim();
if (!content) {
state.context.showToast("说说内容不能为空", "error");
return;
}
try {
await qzonePost(["/qzone/publish", "/qzone/post/publish", "/qzone/post"], { content });
if (input) input.value = "";
state.context.showToast("说说已发布");
await loadFeed(true);
} catch (error) {
state.context.showToast(`发布失败:${error.message}`, "error");
}
}
function bindDeleteEvents() {
const panel = document.getElementById("panel-qzone");
if (!panel || panel.dataset.qzoneDeleteBound === "1") return;
panel.dataset.qzoneDeleteBound = "1";
panel.addEventListener("click", async (event) => {
const element = event.target instanceof Element ? event.target : null;
const deleteButton = element?.closest("[data-qzone-delete]");
if (!deleteButton || !panel.contains(deleteButton)) return;
event.preventDefault();
event.stopPropagation();
if (typeof event.stopImmediatePropagation === "function") event.stopImmediatePropagation();
await deletePost(deleteButton.dataset.qzoneDelete || "", deleteButton);
}, true);
}
function bindEvents() {
const panel = document.getElementById("panel-qzone");
if (!panel || panel.dataset.bound === "1") return;
panel.dataset.bound = "1";
panel.addEventListener("click", async (event) => {
const element = event.target instanceof Element ? event.target : null;
const previewImage = element?.closest("[data-qzone-preview-image]");
if (previewImage && panel.contains(previewImage)) {
event.preventDefault();
event.stopPropagation();
openImagePreview(previewImage);
return;
}
const like = element?.closest("[data-qzone-like]");
if (like) {
await likePost(like.dataset.qzoneLike || "");
return;
}
const deleteButton = element?.closest("[data-qzone-delete]");
if (deleteButton) {
event.preventDefault();
event.stopPropagation();
await deletePost(deleteButton.dataset.qzoneDelete || "", deleteButton);
return;
}
const open = element?.closest("[data-qzone-open]");
if (open) {
await openDetail(open.dataset.qzoneOpen || "");
return;
}
const scopeButton = element?.closest("[data-qzone-scope]");
if (scopeButton) {
state.scope = scopeButton.dataset.qzoneScope || "self";
state.page = 1;
document.querySelectorAll("[data-qzone-scope]").forEach((item) => {
const active = item === scopeButton;
item.classList.toggle("active", active);
item.setAttribute("aria-pressed", String(active));
});
state.loaded = false;
try {
await loadFeed(true);
} catch (error) {
state.context.showToast(`动态加载失败:${error.message}`, "error");
}
return;
}
});
panel.addEventListener("keydown", (event) => {
if (event.key !== "Enter" && event.key !== " ") return;
const element = event.target instanceof Element ? event.target : null;
const previewImage = element?.closest("[data-qzone-preview-image]");
if (!previewImage || !panel.contains(previewImage)) return;
event.preventDefault();
event.stopPropagation();
openImagePreview(previewImage);
});
document.getElementById("qzoneTargetForm")?.addEventListener("submit", async (event) => {
event.preventDefault();
const target = document.getElementById("qzoneTargetUin");
state.targetUin = text(target?.value).trim();
state.scope = "profile";
state.page = 1;
document.querySelectorAll("[data-qzone-scope]").forEach((item) => {
const active = item.dataset.qzoneScope === "profile";
item.classList.toggle("active", active);
item.setAttribute("aria-pressed", String(active));
});
state.loaded = false;
try {
await loadFeed(true);
} catch (error) {
state.context.showToast(`查询失败:${error.message}`, "error");
}
});
document.getElementById("qzonePublishForm")?.addEventListener("submit", async (event) => {
event.preventDefault();
await publish();
});
document.getElementById("qzoneRefreshBtn")?.addEventListener("click", async () => {
try {
await loadStatus(true);
await loadFeed(true);
} catch (error) {
state.context.showToast(`刷新失败:${error.message}`, "error");
}
});
document.getElementById("qzoneRefreshCookiesBtn")?.addEventListener("click", async () => {
try {
const payload = await refreshCookies();
state.context.showToast(`Cookies 已刷新:QQ ${payload?.uin || "未知"}`);
await loadStatus(true);
await loadFeed(true);
} catch (error) {
setNotice(`刷新 Cookies 失败:${error.message}`, "error");
state.context.showToast(`刷新 Cookies 失败:${error.message}`, "error");
}
});
document.getElementById("qzoneAccountAvatar")?.addEventListener("error", (event) => {
const avatar = event.currentTarget;
const avatarFallback = document.getElementById("qzoneAccountAvatarFallback");
avatar.hidden = true;
if (avatarFallback) avatarFallback.hidden = false;
});
}
async function render(context) {
state.context = context;
bindDeleteEvents();
bindEvents();
renderAccount();
renderFeed();
try {
await loadStatus();
if (state.status?.summary?.platform_supported === false) {
state.posts = [];
state.loaded = true;
renderFeed();
setNotice(state.status.summary.unavailable_reason || "当前平台不支持 QQ 空间。", "warn");
return;
}
await loadFeed();
} catch (error) {
setNotice(error.message || "QQ 空间面板初始化失败", "error");
}
}
return { render };
})();

文件差异内容过多而无法显示 加载差异

文件差异内容过多而无法显示 加载差异

查看文件

@ -1,218 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import re
from html import unescape
from html.parser import HTMLParser
from types import SimpleNamespace
from typing import Any
class _QzoneFeedHtmlParser(HTMLParser):
_VOID_TAGS = {
"area",
"base",
"br",
"col",
"embed",
"hr",
"img",
"input",
"link",
"meta",
"param",
"source",
"track",
"wbr",
}
def __init__(self) -> None:
super().__init__(convert_charrefs=True)
self.text_parts: list[str] = []
self.repost_parts: list[str] = []
self.image_urls: list[str] = []
self.image_items: list[dict[str, str]] = []
self._class_stack: list[set[str]] = []
self._tag_stack: list[str] = []
@staticmethod
def _classes(attrs: list[tuple[str, str | None]]) -> set[str]:
for key, value in attrs:
if str(key or "").lower() == "class":
return {item.strip() for item in str(value or "").split() if item.strip()}
return set()
@staticmethod
def _attr(attrs: list[tuple[str, str | None]], name: str) -> str:
lowered = str(name or "").lower()
for key, value in attrs:
if str(key or "").lower() == lowered:
return str(value or "")
return ""
@classmethod
def _first_attr(cls, attrs: list[tuple[str, str | None]], *names: str) -> str:
for name in names:
value = cls._attr(attrs, name).strip()
if value:
return value
return ""
@staticmethod
def _is_content_image_url(value: str) -> bool:
source = str(value or "").strip().lower()
return bool(source) and not source.startswith("http://qzonestyle.gtimg.cn")
def _record_image(self, attrs: list[tuple[str, str | None]]) -> None:
preview_url = self._first_attr(attrs, "src", "data-src", "data-lazy-src", "data-original-src")
full_url = self._first_attr(
attrs,
"data-original",
"data-origin",
"data-origin-url",
"data-original-url",
"data-originalurl",
"data-big-url",
"data-bigurl",
"data-full-url",
"data-fullurl",
"data-raw-url",
"data-rawurl",
"origsrc",
"original",
"data-url",
)
if not self._is_content_image_url(full_url):
full_url = ""
if not self._is_content_image_url(preview_url):
preview_url = ""
source = full_url or preview_url
if not source:
return
item = {"preview_url": preview_url or source, "full_url": source}
if item not in self.image_items:
self.image_items.append(item)
if source not in self.image_urls:
self.image_urls.append(source)
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
normalized_tag = str(tag or "").lower()
classes = self._classes(attrs)
if normalized_tag != "img":
if normalized_tag not in self._VOID_TAGS:
self._tag_stack.append(normalized_tag)
self._class_stack.append(classes)
elif classes:
self._class_stack.append(classes)
self._class_stack.pop()
return
active_classes = self._class_stack + [classes]
if any({"img-box", "video-img"} & item for item in active_classes):
self._record_image(attrs)
def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
normalized_tag = str(tag or "").lower()
if normalized_tag == "img":
self.handle_starttag(tag, attrs)
return
classes = self._classes(attrs)
if classes:
self._class_stack.append(classes)
self._class_stack.pop()
def handle_endtag(self, tag: str) -> None:
normalized_tag = str(tag or "").lower()
for index in range(len(self._tag_stack) - 1, -1, -1):
if self._tag_stack[index] == normalized_tag:
del self._tag_stack[index:]
del self._class_stack[index:]
return
if self._tag_stack and self._class_stack:
self._tag_stack.pop()
self._class_stack.pop()
def handle_data(self, data: str) -> None:
text = unescape(str(data or "")).strip()
if not text:
return
if any("f-info" in item for item in self._class_stack):
self.text_parts.append(text)
if any("txt-box" in item for item in self._class_stack):
self.repost_parts.append(text)
def _parse_feed_html(html_content: str) -> tuple[str, str, list[str]]:
text, repost, image_urls, _items = _parse_feed_html_details(html_content)
return text, repost, image_urls
def _parse_feed_html_details(html_content: str) -> tuple[str, str, list[str], list[dict[str, str]]]:
parser = _QzoneFeedHtmlParser()
parser.feed(str(html_content or ""))
text = "".join(parser.text_parts).strip()
repost = "".join(parser.repost_parts).strip()
if ":" in repost:
repost = repost.split(":", 1)[1].strip()
return text, repost, parser.image_urls, parser.image_items
def _html_attr_value(html_content: str, *names: str) -> str:
source = str(html_content or "")
for name in names:
escaped = re.escape(str(name or ""))
match = re.search(rf"""{escaped}\s*=\s*["']([^"']+)["']""", source, flags=re.IGNORECASE)
if match:
return unescape(match.group(1)).strip()
return ""
def parse_recent_feeds(data: dict[str, Any]) -> list[Any]:
feeds: Any = []
if isinstance(data, dict):
first = data.get("data")
if isinstance(first, dict):
second = first.get("data")
feeds = second if isinstance(second, list) else []
elif isinstance(first, list):
feeds = first
elif isinstance(data.get("msglist"), list):
feeds = data.get("msglist")
if not isinstance(feeds, list) or not feeds:
return []
posts: list[Any] = []
for feed in feeds:
if not feed:
continue
appid = str(feed.get("appid", ""))
if appid != "311":
continue
uin = int(feed.get("uin") or 0)
tid = str(feed.get("key") or "")
if not uin or not tid:
continue
html_content = str(feed.get("html") or "")
if not html_content:
continue
text, rt_con, image_urls, image_items = _parse_feed_html_details(html_content)
posts.append(
SimpleNamespace(
tid=tid,
uin=uin,
name=str(feed.get("nickname") or feed.get("name") or uin),
text=text,
rt_con=rt_con,
images=image_urls,
image_items=image_items,
comments=[],
create_time=int(feed.get("abstime") or 0),
appid=str(feed.get("appid") or "311"),
typeid=str(feed.get("typeid") or feed.get("type") or "0"),
abstime=int(feed.get("abstime") or 0),
fid=str(feed.get("key") or tid),
unikey=str(feed.get("unikey") or feed.get("likeKey") or feed.get("like_key") or _html_attr_value(html_content, "data-unikey", "unikey")),
curkey=str(feed.get("curkey") or feed.get("curlikekey") or feed.get("likeKey") or feed.get("like_key") or _html_attr_value(html_content, "data-curkey", "curkey")),
raw=feed,
status="approved",
)
)
return posts

查看文件

@ -1,91 +0,0 @@
# -*- coding: utf-8 -*-
from __future__ import annotations
import re
from dataclasses import dataclass
NUMERIC_FID_MIN_LENGTH = 12
LATEST_ALIASES = {"", "0", "1", "latest", "newest", "最新", "最新一条", "最近", "第一条", "第1条"}
LAST_ALIASES = {"-1", "last", "最后", "最后一条", "末条"}
@dataclass(slots=True)
class QzonePostSelection:
target_id: str = ""
pos: int = 0
limit: int = 1
selector: str = "latest"
fid: str = ""
explicit_target: bool = False
explicit_selector: bool = False
@property
def is_last(self) -> bool:
return self.selector == "last"
def _looks_like_fid(value: str) -> bool:
text = str(value or "").strip()
if not text:
return False
if re.fullmatch(rf"\d{{{NUMERIC_FID_MIN_LENGTH},}}", text):
return True
if _parse_index(text) is not None:
return False
return bool(re.fullmatch(r"[A-Za-z0-9_.:-]{6,}", text))
def _parse_index(value: str) -> int | None:
text = str(value or "").strip()
lowered = text.lower()
if text in LATEST_ALIASES or lowered in LATEST_ALIASES:
return 0
if text in LAST_ALIASES or lowered in LAST_ALIASES:
return -1
normalized = text.translate(str.maketrans("0123456789", "0123456789"))
match = re.fullmatch(r"第\s*(\d+)\s*(?:条|條)?", normalized)
if not match:
match = re.fullmatch(r"(\d+)\s*(?:条|條)?", normalized)
if not match:
return None
return max(0, int(match.group(1)) - 1)
def parse_qzone_post_selection(
*,
user_id: str = "",
selector: str = "",
pos: int = 0,
fid: str = "",
) -> QzonePostSelection:
target_id = str(user_id or "").strip()
raw = str(selector or "").strip()
explicit_target = bool(target_id)
explicit_selector = bool(raw or fid)
at_match = re.search(r"\[CQ:at,qq=(\d+)[^\]]*\]|@(\d{5,})", raw)
if at_match:
target_id = at_match.group(1) or at_match.group(2) or target_id
explicit_target = True
raw = re.sub(r"\[CQ:at,qq=\d+[^\]]*\]|@\d{5,}", " ", raw, count=1).strip()
tokens = raw.split()
if not target_id and tokens and re.fullmatch(r"\d{5,}", tokens[0]) and not _looks_like_fid(tokens[0]):
target_id = tokens.pop(0)
explicit_target = True
explicit_fid = str(fid or "").strip()
if explicit_fid:
return QzonePostSelection(target_id=target_id, fid=explicit_fid, selector="fid", explicit_target=explicit_target, explicit_selector=True)
if tokens and _looks_like_fid(tokens[0]):
return QzonePostSelection(target_id=target_id, fid=tokens[0], selector="fid", explicit_target=explicit_target, explicit_selector=True)
parsed = _parse_index(tokens[0]) if tokens else _parse_index(raw)
if parsed is None:
parsed = max(0, int(pos or 0))
explicit_selector = explicit_selector or parsed > 0
if parsed < 0:
return QzonePostSelection(target_id=target_id, pos=0, limit=10, selector="last", explicit_target=explicit_target, explicit_selector=True)
return QzonePostSelection(target_id=target_id, pos=parsed, limit=1, selector="index" if parsed > 0 else "latest", explicit_target=explicit_target, explicit_selector=explicit_selector)

查看文件

@ -5265,12 +5265,6 @@ Local classifier result:
abs(mood_score),
)
return
vent = getattr(self, "_maybe_publish_qzone_emotional_vent", None)
if callable(vent):
try:
asyncio.create_task(vent(user_snapshot=deepcopy(user), relationship_state=deepcopy(state), intent=deepcopy(intent)))
except Exception as exc:
logger.debug("[PrivateCompanion] 公开心情动态任务创建失败: %s", _single_line(exc, 120))
def _remember_passive_reply_topic(self, user: dict[str, Any], text: str, inbound_text: str = "") -> None:
if not self.enable_passive_topic_suppression: