diff --git a/_conf_schema.json b/_conf_schema.json
index 4a2b654..f015625 100644
--- a/_conf_schema.json
+++ b/_conf_schema.json
@@ -1315,14 +1315,22 @@
"description": "Legacy flat config: 群聊表达语义归纳每日批次上限",
"type": "int",
"default": 6,
- "slider": {"min": 1, "max": 50, "step": 1},
+ "slider": {
+ "min": 1,
+ "max": 50,
+ "step": 1
+ },
"invisible": true
},
"expression_group_learning_min_new_messages": {
"description": "Legacy flat config: 群聊表达语义归纳最少新增消息数",
"type": "int",
"default": 20,
- "slider": {"min": 5, "max": 80, "step": 5},
+ "slider": {
+ "min": 5,
+ "max": 80,
+ "step": 5
+ },
"invisible": true
},
"expression_private_application_mode": {
@@ -1355,12 +1363,6 @@
"default": true,
"invisible": true
},
- "enable_food_menu_recommendation": {
- "description": "Legacy flat config: 启用吃什么候选",
- "type": "bool",
- "default": true,
- "invisible": true
- },
"user_habit_min_count": {
"description": "Legacy flat config: 习惯成型次数",
"type": "int",
@@ -1433,30 +1435,6 @@
"default": 90,
"invisible": true
},
- "enable_qzone_emotional_vent_publish": {
- "description": "Legacy flat config: 公开心情动态",
- "type": "bool",
- "default": false,
- "invisible": true
- },
- "qzone_emotional_vent_threshold": {
- "description": "Legacy flat config: 心情动态触发阈值",
- "type": "int",
- "default": 90,
- "invisible": true
- },
- "qzone_emotional_vent_cooldown_hours": {
- "description": "Legacy flat config: 心情动态冷却小时",
- "type": "int",
- "default": 72,
- "invisible": true
- },
- "qzone_emotional_vent_probability": {
- "description": "Legacy flat config: 心情动态触发概率",
- "type": "float",
- "default": 0.35,
- "invisible": true
- },
"enable_response_self_review": {
"description": "Legacy flat config: 旧版回复/主动复核总开关",
"type": "bool",
@@ -1481,7 +1459,6 @@
"default": true,
"invisible": true
},
-
"enable_smart_silence": {
"description": "Legacy flat config: 启用智能沉默",
"type": "bool",
@@ -1606,18 +1583,6 @@
"default": true,
"invisible": true
},
- "enable_livingmemory_integration": {
- "description": "Legacy flat config: 启用外部记忆插件协同",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "livingmemory_tool_name": {
- "description": "Legacy flat config: 记忆召回工具名",
- "type": "string",
- "default": "recall_long_term_memory",
- "invisible": true
- },
"memory_companion_context_timeout_seconds": {
"description": "Legacy flat config: 记忆上下文超时(秒)",
"type": "float",
@@ -1672,126 +1637,12 @@
"default": 900,
"invisible": true
},
- "enable_bilibili_integration": {
- "description": "Legacy flat config: 启用 B站 AI Bot 协同",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "enable_bilibili_boredom_watch": {
- "description": "Legacy flat config: 无聊时触发刷 B 站",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "bilibili_boredom_min_interval_hours": {
- "description": "Legacy flat config: 刷 B 站最小间隔(小时)",
- "type": "int",
- "default": 8,
- "invisible": true
- },
- "bilibili_share_probability": {
- "description": "Legacy flat config: 视频私聊分享概率",
- "type": "float",
- "default": 0.35,
- "invisible": true
- },
- "bilibili_share_min_score": {
- "description": "Legacy flat config: 视频分享最低评分",
- "type": "int",
- "default": 7,
- "invisible": true
- },
- "enable_news_integration": {
- "description": "Legacy flat config: 启用新闻阅读",
- "type": "bool",
- "default": false,
- "invisible": true
- },
- "enable_news_boredom_read": {
- "description": "Legacy flat config: 无聊时看新闻",
- "type": "bool",
- "default": true,
- "invisible": true
- },
"NEWS_PROVIDER_ID": {
"description": "Legacy flat config: 新闻整理模型(留空跟随主动转述/主模型)",
"type": "string",
"default": "",
"invisible": true
},
- "news_sources": {
- "description": "Legacy flat config: 新闻源",
- "type": "string",
- "default": "BBC中文|https://feeds.bbci.co.uk/zhongwen/simp/rss.xml\nGoogle新闻中文|https://news.google.com/rss?hl=zh-CN&gl=CN&ceid=CN:zh-Hans\nSolidot|https://www.solidot.org/index.rss\nHacker News|https://hnrss.org/frontpage\nMIT Technology Review|https://www.technologyreview.com/feed/\nArs Technica|https://feeds.arstechnica.com/arstechnica/index",
- "invisible": true
- },
- "enable_ai_daily_watch": {
- "description": "Legacy flat config: 追踪每日 AI 日报/早报",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "ai_daily_sources": {
- "description": "Legacy flat config: AI 日报/早报定时来源",
- "type": "string",
- "default": "AI日报|橘鸦Juya|285286947|日报 早报|23:00\nAI早报|黑鸦Heya|3706929260006322|早报 日报|12:00",
- "invisible": true
- },
- "ai_daily_source_uid": {
- "description": "Legacy flat config: 兼容旧版 AI 早报 UID",
- "type": "string",
- "default": "285286947",
- "invisible": true
- },
- "ai_daily_prefer_text_version": {
- "description": "Legacy flat config: AI 日报/早报优先文字版",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "news_min_interval_hours": {
- "description": "Legacy flat config: 看新闻最小间隔(小时)",
- "type": "int",
- "default": 6,
- "invisible": true
- },
- "news_share_probability": {
- "description": "Legacy flat config: 新闻私聊分享概率",
- "type": "float",
- "default": 0.22,
- "invisible": true
- },
- "enable_external_event_self_link": {
- "description": "Legacy flat config: 外界信息自我关联",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "external_event_self_link_probability": {
- "description": "Legacy flat config: 自我关联分享欲倍率",
- "type": "float",
- "default": 0.62,
- "invisible": true
- },
- "external_event_self_link_cooldown_hours": {
- "description": "Legacy flat config: 自我关联冷却(小时)",
- "type": "int",
- "default": 12,
- "invisible": true
- },
- "external_link_share_cooldown_hours": {
- "description": "Legacy flat config: 主动外链统一冷却(小时)",
- "type": "int",
- "default": 72,
- "invisible": true
- },
- "news_max_items_per_source": {
- "description": "Legacy flat config: 单源最多读取条数",
- "type": "int",
- "default": 5,
- "invisible": true
- },
"enable_web_exploration": {
"description": "Legacy flat config: 启用主动搜索",
"type": "bool",
@@ -1804,150 +1655,6 @@
"default": true,
"invisible": true
},
- "WEB_EXPLORATION_PROVIDER_ID": {
- "description": "Legacy flat config: 主动搜索决策/整理模型(留空跟随新闻整理/主模型)",
- "type": "string",
- "default": "",
- "invisible": true
- },
- "WEB_EXPLORATION_API_BASE_URL": {
- "description": "Legacy flat config: 主动搜索自定义接口地址",
- "type": "string",
- "default": "",
- "invisible": true
- },
- "WEB_EXPLORATION_API_KEY": {
- "description": "Legacy flat config: 主动搜索自定义接口 API Key",
- "type": "string",
- "default": "",
- "invisible": true
- },
- "WEB_EXPLORATION_API_MODEL": {
- "description": "Legacy flat config: 主动搜索自定义接口模型",
- "type": "string",
- "default": "",
- "invisible": true
- },
- "web_exploration_interests": {
- "description": "Legacy flat config: 探索兴趣倾向",
- "type": "string",
- "default": "按 Bot 人格自行决定;可偏向最近聊天、日程、人设兴趣、作品、技术、生活小知识、流行梗、时讯、新鲜事物。",
- "invisible": true
- },
- "enable_news_daily_hot_read": {
- "description": "Legacy flat config: 每日获取热点",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "news_hot_sources": {
- "description": "Legacy flat config: 热点来源",
- "type": "string",
- "default": "weibo,hackernews",
- "invisible": true
- },
- "news_hot_max_items": {
- "description": "Legacy flat config: 热点候选数量",
- "type": "int",
- "default": 12,
- "invisible": true
- },
- "web_exploration_min_interval_hours": {
- "description": "Legacy flat config: 网页探索最小间隔(小时)",
- "type": "int",
- "default": 8,
- "invisible": true
- },
- "web_exploration_share_probability": {
- "description": "Legacy flat config: 探索后私聊分享概率",
- "type": "float",
- "default": 0.18,
- "invisible": true
- },
- "web_exploration_max_results": {
- "description": "Legacy flat config: 网页搜索结果数",
- "type": "int",
- "default": 6,
- "invisible": true
- },
- "enable_qzone_integration": {
- "description": "Legacy flat config: 启用 QQ 空间动态层",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "QZONE_COOKIE": {
- "description": "Legacy flat config: QQ 空间手动 Cookie",
- "type": "text",
- "default": "",
- "invisible": true
- },
- "enable_qzone_life_publish": {
- "description": "Legacy flat config: 低频发布生活说说",
- "type": "bool",
- "default": false,
- "invisible": true
- },
- "qzone_life_publish_min_interval_hours": {
- "description": "Legacy flat config: 生活说说最小间隔(小时)",
- "type": "int",
- "default": 24,
- "invisible": true
- },
- "qzone_life_publish_probability": {
- "description": "Legacy flat config: 生活说说触发概率",
- "type": "float",
- "default": 0.18,
- "invisible": true
- },
- "qzone_publish_style_prompt": {
- "description": "Legacy flat config: QQ 空间说说风格提示词",
- "type": "text",
- "default": "",
- "invisible": true
- },
- "enable_qzone_generated_image_publish": {
- "description": "Legacy flat config: 主动说说可带生成图",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "qzone_generated_image_probability": {
- "description": "Legacy flat config: 主动说说带图概率",
- "type": "float",
- "default": 0.25,
- "invisible": true
- },
- "qzone_publish_image_style_prompt": {
- "description": "Legacy flat config: QQ 空间配图提示词",
- "type": "text",
- "default": "",
- "invisible": true
- },
- "enable_qzone_comment_inbox": {
- "description": "Legacy flat config: QQ 空间评论收件箱",
- "type": "bool",
- "default": false,
- "invisible": true
- },
- "qzone_comment_inbox_interval_minutes": {
- "description": "Legacy flat config: 评论收件箱检查间隔(分钟)",
- "type": "int",
- "default": 60,
- "invisible": true
- },
- "qzone_comment_inbox_recent_posts": {
- "description": "Legacy flat config: 评论收件箱扫描最近说说数",
- "type": "int",
- "default": 5,
- "invisible": true
- },
- "qzone_comment_inbox_max_replies_per_tick": {
- "description": "Legacy flat config: 评论收件箱每轮最多回复数",
- "type": "int",
- "default": 1,
- "invisible": true
- },
"enable_private_reading_integration": {
"description": "Legacy flat config: 启用夹层阅读素材",
"type": "bool",
@@ -3123,7 +2830,10 @@
"photo_generation_prompt_format": {
"description": "Legacy flat config: 生图提示词表达方式",
"type": "string",
- "options": ["traditional", "natural_language"],
+ "options": [
+ "traditional",
+ "natural_language"
+ ],
"default": "traditional",
"invisible": true
},
@@ -3151,60 +2861,6 @@
"default": "",
"invisible": true
},
- "enable_screen_glance_action": {
- "description": "Legacy flat config: 允许主动看一眼屏幕",
- "type": "bool",
- "default": false,
- "invisible": true
- },
- "screen_peek_max_daily": {
- "description": "Legacy flat config: 每日主动识屏最多次数",
- "type": "int",
- "default": 1,
- "invisible": true
- },
- "screen_peek_cooldown_minutes": {
- "description": "Legacy flat config: 主动识屏冷却分钟数",
- "type": "int",
- "default": 240,
- "invisible": true
- },
- "enable_unanswered_screen_peek_followup": {
- "description": "Legacy flat config: 主动后沉默可额外窥屏",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "unanswered_screen_peek_after_minutes": {
- "description": "Legacy flat config: 主动后沉默窥屏等待分钟数",
- "type": "int",
- "default": 45,
- "invisible": true
- },
- "unanswered_screen_peek_cooldown_minutes": {
- "description": "Legacy flat config: 沉默窥屏冷却分钟数",
- "type": "int",
- "default": 180,
- "invisible": true
- },
- "enable_poke_action": {
- "description": "Legacy flat config: 允许主动戳一戳",
- "type": "bool",
- "default": false,
- "invisible": true
- },
- "poke_action_max_times": {
- "description": "Legacy flat config: 主动戳一戳最多次数",
- "type": "int",
- "default": 1,
- "invisible": true
- },
- "poke_action_cooldown_minutes": {
- "description": "Legacy flat config: 主动戳一戳冷却分钟数",
- "type": "int",
- "default": 30,
- "invisible": true
- },
"enable_voice_action": {
"description": "Legacy flat config: 允许主动发语音",
"type": "bool",
@@ -3439,18 +3095,6 @@
"default": 30,
"invisible": true
},
- "enable_qq_presence_sync": {
- "description": "Legacy flat config: 允许细化模型同步 QQ 全局状态",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "enable_qq_custom_presence_sync": {
- "description": "Legacy flat config: 允许同步 QQ 自定义短状态",
- "type": "bool",
- "default": false,
- "invisible": true
- },
"enable_weather_context": {
"description": "Legacy flat config: 启用天气上下文",
"type": "bool",
@@ -3505,18 +3149,6 @@
"default": 90,
"invisible": true
},
- "enable_yesterday_screen_diary_context": {
- "description": "Legacy flat config: 读取昨日屏幕观察日记",
- "type": "bool",
- "default": true,
- "invisible": true
- },
- "screen_diary_context_max_chars": {
- "description": "Legacy flat config: 昨日屏幕日记上下文字数",
- "type": "int",
- "default": 700,
- "invisible": true
- },
"target_group_ids": {
"description": "Legacy flat config: 群聊陪伴目标群号(旧配置,等同白名单)",
"type": "list",
@@ -3706,18 +3338,6 @@
"default": "",
"invisible": true
},
- "allow_screen_peek_action": {
- "description": "Legacy flat config: 旧版主动识屏开关",
- "type": "string",
- "default": "",
- "invisible": true
- },
- "allow_poke_action": {
- "description": "Legacy flat config: 旧版戳一戳开关",
- "type": "string",
- "default": "",
- "invisible": true
- },
"allow_voice_action": {
"description": "Legacy flat config: 旧版主动语音开关",
"type": "string",
@@ -3736,18 +3356,6 @@
"default": false,
"invisible": true
},
- "hot_trend_sources": {
- "description": "Legacy flat config: 旧版热榜来源",
- "type": "string",
- "default": "",
- "invisible": true
- },
- "hot_trend_max_items": {
- "description": "Legacy flat config: 旧版热榜条数",
- "type": "string",
- "default": "",
- "invisible": true
- },
"enable_jm_cosmos_integration": {
"description": "Legacy flat config: 旧版夹层阅读开关",
"type": "bool",
@@ -5335,23 +4943,37 @@
"type": "bool",
"hint": "只有目标关键词与已经结束的日程片段相符时才推进,不会把计划中或进行中的活动算作完成。",
"default": true,
- "condition": {"enable_personal_goals": true}
+ "condition": {
+ "enable_personal_goals": true
+ }
},
"personal_goal_share_cooldown_hours": {
"description": "目标进展分享冷却(小时)",
"type": "int",
"hint": "只有跨越里程碑、长时间停滞或完成时才形成主动候选。",
- "slider": {"min": 1, "max": 168, "step": 1},
+ "slider": {
+ "min": 1,
+ "max": 168,
+ "step": 1
+ },
"default": 12,
- "condition": {"enable_personal_goals": true}
+ "condition": {
+ "enable_personal_goals": true
+ }
},
"personal_goal_stall_days": {
"description": "停滞提醒天数",
"type": "int",
"hint": "进行中的目标超过该天数没有真实推进时,可形成一次低压力的主动分享。",
- "slider": {"min": 1, "max": 30, "step": 1},
+ "slider": {
+ "min": 1,
+ "max": 30,
+ "step": 1
+ },
"default": 3,
- "condition": {"enable_personal_goals": true}
+ "condition": {
+ "enable_personal_goals": true
+ }
},
"skill_growth_rate": {
"description": "技能成长倍率",
@@ -5523,82 +5145,125 @@
"type": "string",
"hint": "在陪伴面板的“学习”页管理来源与画像。owner 仅从主要用户学习;selected 仅从勾选私聊学习;all 从全部私聊学习。",
"default": "owner",
- "options": ["owner", "selected", "all"],
+ "options": [
+ "owner",
+ "selected",
+ "all"
+ ],
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_private_learning_source_ids": {
"description": "私聊学习来源 ID",
"type": "list",
"default": [],
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_group_learning_source_mode": {
"description": "群聊学习来源",
"type": "string",
"hint": "在陪伴面板的“学习”页管理来源与画像。群聊可归纳脱敏后的短表达、梗模板和句法;昵称、账号、关系、事实和支持片段不会进入回复。",
"default": "disabled",
- "options": ["disabled", "selected", "all"],
+ "options": [
+ "disabled",
+ "selected",
+ "all"
+ ],
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_group_learning_source_ids": {
"description": "群聊学习来源 ID",
"type": "list",
"default": [],
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_group_learning_daily_batch_limit": {
"description": "群聊语义归纳每日批次上限",
"type": "int",
"hint": "所有群共享的每日模型归纳批次上限;情境表达和语法习惯共用已有群片段整理调用,不会额外发起模型请求。",
"default": 6,
- "slider": {"min": 1, "max": 50, "step": 1},
+ "slider": {
+ "min": 1,
+ "max": 50,
+ "step": 1
+ },
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_group_learning_min_new_messages": {
"description": "每批最少新增群消息",
"type": "int",
"hint": "只统计上次归纳后新增的群消息,数量不足时不要求模型归纳表达规则。",
"default": 20,
- "slider": {"min": 5, "max": 80, "step": 5},
+ "slider": {
+ "min": 5,
+ "max": 80,
+ "step": 5
+ },
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_private_application_mode": {
"description": "私聊使用范围",
"type": "string",
"hint": "在陪伴面板的“学习”页管理使用范围。控制哪些私聊会使用去标识的全局表达底色;本地表达规则只对对应学习来源生效。",
"default": "all",
- "options": ["all", "selected"],
+ "options": [
+ "all",
+ "selected"
+ ],
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_private_application_user_ids": {
"description": "私聊使用对象 ID",
"type": "list",
"default": [],
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_group_application_mode": {
"description": "群聊使用范围",
"type": "string",
"hint": "在陪伴面板的“学习”页管理使用范围。仅影响 Bot 的回复口感;不会把私聊或群聊原话、昵称、关系和事实带入群聊。",
"default": "all",
- "options": ["disabled", "all", "selected"],
+ "options": [
+ "disabled",
+ "all",
+ "selected"
+ ],
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"expression_group_application_ids": {
"description": "群聊使用对象 ID",
"type": "list",
"default": [],
"invisible": true,
- "condition": {"enable_expression_learning": true}
+ "condition": {
+ "enable_expression_learning": true
+ }
},
"enable_user_habit_learning": {
"description": "启用用户习惯画像",
@@ -5609,66 +5274,6 @@
"enable_mai_style_integration": true
}
},
- "enable_food_menu_recommendation": {
- "description": "启用吃什么候选",
- "type": "bool",
- "hint": "把常吃菜、店和外卖整理成候选。用户纠结吃什么、点什么或夜宵时,只取少量贴合项作为回复参考;饭点关心中识别到用户实际吃过的具体内容时也会自动回填。",
- "default": true,
- "condition": {
- "enable_mai_style_integration": true
- }
- },
- "enable_meal_care_proactive": {
- "description": "启用饭点主动关心",
- "type": "bool",
- "hint": "在早餐、午饭、晚饭窗口独立安排“吃了吗”关心,不再依赖早安/午安是否命中。仅用于主要用户,并继续遵守免打扰、主动额度、最小间隔和未回应降速。",
- "default": true,
- "condition": {
- "enable_mai_style_integration": true
- }
- },
- "meal_care_max_daily": {
- "description": "每日最多饭点关心次数",
- "type": "int",
- "hint": "这是单日上限,不代表每天都会询问。早餐、午饭、晚饭每餐最多首次询问一次;默认单日最多选择其中一餐。早餐会等早安发出且用户回应后才进入候选。填 0 可关闭首次饭点询问。",
- "slider": {
- "min": 0,
- "max": 3,
- "step": 1
- },
- "default": 1,
- "condition": {
- "enable_meal_care_proactive": true
- }
- },
- "meal_care_min_interval_hours": {
- "description": "饭点关心最短间隔小时",
- "type": "int",
- "hint": "控制跨天频率。默认 48 小时,通常最多隔天关心一次;期间 Bot 已经主动聊过饮食,也会从最近一次饮食话题重新计时,避免形成每日查岗。填 0 时仅使用每日上限和普通饮食冷却。",
- "slider": {
- "min": 0,
- "max": 168,
- "step": 12
- },
- "default": 48,
- "condition": {
- "enable_meal_care_proactive": true
- }
- },
- "meal_care_followup_minutes": {
- "description": "吃饭补问等待分钟",
- "type": "int",
- "hint": "首次询问后用户一直没有回应时,多久后允许一次低压补问。若用户回复忙碌或其他无关内容,会视为不想继续该话题并结束本轮关心;用户答“吃了”或“没吃”时,仅由当前回复自然承接,不再后台重复追问。每餐最多补问一次。",
- "slider": {
- "min": 15,
- "max": 180,
- "step": 5
- },
- "default": 45,
- "condition": {
- "enable_meal_care_proactive": true
- }
- },
"user_habit_min_count": {
"description": "习惯成型次数",
"type": "int",
@@ -5765,7 +5370,6 @@
"enable_mai_style_integration": true
}
},
-
"enable_smart_silence": {
"description": "启用智能沉默",
"type": "bool",
@@ -6030,21 +5634,6 @@
"type": "object",
"hint": "统一接入已适配的外部长期记忆插件。当前支持“我会牢牢记住你”/MemoryCompanion 与 LivingMemory;检测到不同插件时会展开各自适用的协同配置。",
"items": {
- "enable_livingmemory_integration": {
- "description": "启用外部记忆插件协同",
- "type": "bool",
- "hint": "统一控制已适配的外部记忆插件协同,不只对应 LivingMemory。检测到“我会牢牢记住你”/MemoryCompanion 或 LivingMemory 时,在私聊和群聊提示词中按各自能力使用记忆上下文或召回工具;本插件继续负责人格、状态、关系和群聊气氛。",
- "default": true
- },
- "livingmemory_tool_name": {
- "description": "记忆召回工具名",
- "type": "string",
- "hint": "LivingMemory 默认注册的 Agent 工具名是 recall_long_term_memory。如插件更改了工具名,可在这里同步。“我会牢牢记住你”通过桥接接口协同,通常不需要修改此项。",
- "default": "recall_long_term_memory",
- "condition": {
- "enable_livingmemory_integration": true
- }
- },
"memory_companion_context_timeout_seconds": {
"description": "记忆上下文超时(秒)",
"type": "float",
@@ -6055,18 +5644,14 @@
"max": 6.0,
"step": 0.1
},
- "condition": {
- "enable_livingmemory_integration": true
- }
+ "condition": {}
},
"enable_memory_companion_emotional_drift": {
"description": "情绪漂移联动",
"type": "bool",
"hint": "从“我会牢牢记住你”拉取待处理情绪事件(伤痕触动/温暖回忆/脆弱共鸣),按安全阀应用到 Bot 当前能量和心情底色。每次私聊和主动消息生成前触发。",
"default": true,
- "condition": {
- "enable_livingmemory_integration": true
- }
+ "condition": {}
},
"enable_memory_companion_cross_window_emotion": {
"description": "跨窗口情绪连续性",
@@ -6082,27 +5667,21 @@
"type": "bool",
"hint": "日记生成后将首条梦境碎片写入“我会牢牢记住你”,带上 dream_fragment 标签和查询锚点,支持跨会话梦境连续性。",
"default": true,
- "condition": {
- "enable_livingmemory_integration": true
- }
+ "condition": {}
},
"enable_memory_companion_open_loop_search": {
"description": "未完成话题取材",
"type": "bool",
"hint": "主动消息生成前从“我会牢牢记住你”检索未完成的承诺和话题,注入到主动消息提示词中,形成承诺兑现闭环。",
"default": true,
- "condition": {
- "enable_livingmemory_integration": true
- }
+ "condition": {}
},
"enable_memory_companion_feature_context": {
"description": "功能上下文读取",
"type": "bool",
"hint": "主动消息生成/复核、当前状态问答、每日穿搭、自然语言生图、QQ 空间互动、群聊主动插话、私下创作和陪伴答疑等链路按需读取“我会牢牢记住你”的结构化上下文。关闭后这些链路不会主动召回记忆。",
"default": true,
- "condition": {
- "enable_livingmemory_integration": true
- }
+ "condition": {}
},
"enable_memory_companion_private_recall": {
"description": "私聊选择性长期召回",
@@ -6143,527 +5722,6 @@
}
}
},
- "bilibili_config": {
- "description": "B 站联动",
- "type": "object",
- "hint": "控制 Bot 无聊刷 B 站和视频分享。",
- "items": {
- "enable_bilibili_integration": {
- "description": "启用 B站 AI Bot 协同",
- "type": "bool",
- "hint": "检测到正式插件 astrbot_plugin_bilibili_ai_bot 时,可读取其观看日志和 memory_api 视频记忆,并把适合的视频作为主动私聊分享素材。若目录名被手动改动,运行时会校验 metadata,不会把其他 B 站插件当成它。",
- "default": true
- },
- "enable_bilibili_boredom_watch": {
- "description": "无聊时触发刷 B 站",
- "type": "bool",
- "hint": "当日程/状态显示 Bot 比较空、无聊或在休息时,低频触发 B站 AI Bot 看 1 个视频。触发后是否评论、点赞等由 B站 AI Bot 自己的配置决定。",
- "default": true,
- "condition": {
- "enable_bilibili_integration": true
- }
- },
- "bilibili_boredom_min_interval_hours": {
- "description": "刷 B 站最小间隔(小时)",
- "type": "int",
- "hint": "陪伴插件主动触发 B站 AI Bot 刷视频的最小间隔,避免过于频繁。",
- "slider": {
- "min": 2,
- "max": 72,
- "step": 1
- },
- "default": 8,
- "condition": {
- "enable_bilibili_boredom_watch": true
- }
- },
- "bilibili_share_probability": {
- "description": "视频私聊分享概率",
- "type": "float",
- "hint": "读取到 B站 AI Bot 最新观看记录后,安排私聊分享的基础概率。高评分视频会略微提高概率。",
- "slider": {
- "min": 0,
- "max": 1,
- "step": 0.05
- },
- "default": 0.35,
- "condition": {
- "enable_bilibili_integration": true
- }
- },
- "bilibili_share_min_score": {
- "description": "视频分享最低评分",
- "type": "int",
- "hint": "B站 AI Bot 观看日志中的评分达到该值时,更容易被拿来私聊分享。",
- "slider": {
- "min": 0,
- "max": 10,
- "step": 1
- },
- "default": 7,
- "condition": {
- "enable_bilibili_integration": true
- }
- }
- }
- },
- "news_config": {
- "description": "新闻与 AI 日报",
- "type": "object",
- "hint": "控制新闻源、AI 日报来源和无聊时阅读分享。",
- "items": {
- "enable_news_integration": {
- "description": "启用新闻阅读",
- "type": "bool",
- "hint": "开启后 Bot 可在空档或无聊时低频读取配置的 RSS/Atom 新闻源,形成自己的内部印象,并可能作为主动私聊素材。",
- "default": false
- },
- "enable_news_boredom_read": {
- "description": "无聊时看新闻",
- "type": "bool",
- "hint": "当状态和日程显示 Bot 比较空、无聊或在休息时,低频抓取新闻源。读取后不一定分享,也可能只是记作近期见闻。",
- "default": true,
- "condition": {
- "enable_news_integration": true
- }
- },
- "NEWS_PROVIDER_ID": {
- "description": "新闻整理模型(留空跟随主动转述/主模型)",
- "type": "string",
- "default": "",
- "_special": "select_provider",
- "hint": "用于从抓到的新闻标题和摘要中挑一条适合分享的内容,并整理成 Bot 的内部印象。适合便宜、稳定、擅长短 JSON 的模型。",
- "condition": {
- "enable_news_integration": true
- }
- },
- "news_sources": {
- "description": "新闻源",
- "type": "string",
- "hint": "每行一个新闻源,格式为 名称|URL、名称|bilibili:UID、名称|bvid:BV...,也可以直接填 RSS/Atom URL、B 站空间链接或 B 站视频链接。默认只包含综合中文新闻和科技新闻源;AI 日报/早报建议交给下方定时来源,避免普通新闻阅读频繁访问 B 站 UP 空间。",
- "default": "BBC中文|https://feeds.bbci.co.uk/zhongwen/simp/rss.xml\nGoogle新闻中文|https://news.google.com/rss?hl=zh-CN&gl=CN&ceid=CN:zh-Hans\nSolidot|https://www.solidot.org/index.rss\nHacker News|https://hnrss.org/frontpage\nMIT Technology Review|https://www.technologyreview.com/feed/\nArs Technica|https://feeds.arstechnica.com/arstechnica/index",
- "condition": {
- "enable_news_integration": true
- }
- },
- "enable_ai_daily_watch": {
- "description": "追踪每日 AI 日报/早报",
- "type": "bool",
- "hint": "开启后按来源配置的固定时间读取 B 站 AI 日报/早报。默认 12:00 读黑鸦Heya早报,23:00 读橘鸦Juya日报;到点后当天只尝试一次,避免反复轮询 UP 空间导致限流。",
- "default": true,
- "condition": {
- "enable_news_integration": true
- }
- },
- "ai_daily_sources": {
- "description": "AI 日报/早报定时来源",
- "type": "string",
- "hint": "每行一个来源,格式:名称|UP主名|UID|关键词|HH:MM。默认:AI日报|橘鸦Juya|285286947|日报 早报|23:00,以及 AI早报|黑鸦Heya|3706929260006322|早报 日报|12:00。插件会通过 B 站搜索 API/网页搜索找到当天视频,再读取文字版、字幕或视频公开信息。",
- "default": "AI日报|橘鸦Juya|285286947|日报 早报|23:00\nAI早报|黑鸦Heya|3706929260006322|早报 日报|12:00",
- "condition": {
- "enable_ai_daily_watch": true
- }
- },
- "ai_daily_source_uid": {
- "description": "兼容旧版 AI 早报 UID",
- "type": "string",
- "hint": "旧版单 UP 配置兼容项。新版本请优先使用“AI 日报/早报定时来源”。",
- "default": "285286947",
- "condition": {
- "enable_ai_daily_watch": true
- }
- },
- "ai_daily_prefer_text_version": {
- "description": "AI 日报/早报优先文字版",
- "type": "bool",
- "hint": "开启后如果简介里有文字版链接,会优先阅读完整正文。若文字版暂时不可读,会尝试读取公开视频字幕,再退回视频公开信息避免完全漏读。",
- "default": true,
- "condition": {
- "enable_ai_daily_watch": true
- }
- },
- "news_min_interval_hours": {
- "description": "看新闻最小间隔(小时)",
- "type": "int",
- "hint": "两次主动看新闻之间的最小间隔。建议不要太短,避免频繁访问新闻源。",
- "slider": {
- "min": 1,
- "max": 72,
- "step": 1
- },
- "default": 6,
- "condition": {
- "enable_news_boredom_read": true
- }
- },
- "news_share_probability": {
- "description": "新闻私聊分享概率",
- "type": "float",
- "hint": "Bot 读到新闻后安排主动私聊分享的基础概率。即使不分享,也会记录最近看过的新闻印象。",
- "slider": {
- "min": 0,
- "max": 1,
- "step": 0.05
- },
- "default": 0.22,
- "condition": {
- "enable_news_integration": true
- }
- },
- "enable_external_event_self_link": {
- "description": "外界信息自我关联",
- "type": "bool",
- "hint": "开启后,Bot 读到新闻或主动搜索结果时,会先判断这件事是否与自己的模型、能力、兴趣、创作、日程或关系有关,再决定是否产生找用户说说的意愿。不是关键词硬触发。",
- "default": true
- },
- "external_event_self_link_probability": {
- "description": "自我关联分享欲倍率",
- "type": "float",
- "hint": "外界信息通过自我关联判断后,进入主动候选的概率倍率。数值越高,Bot 越容易因为读到与自己有关的新鲜事而来找用户。",
- "slider": {
- "min": 0,
- "max": 1,
- "step": 0.05
- },
- "default": 0.62,
- "condition": {
- "enable_external_event_self_link": true
- }
- },
- "external_event_self_link_cooldown_hours": {
- "description": "自我关联冷却(小时)",
- "type": "int",
- "hint": "同一用户两次因新闻/搜索自我关联而主动找人的最小间隔,避免外界消息连续触发分享欲。",
- "slider": {
- "min": 1,
- "max": 168,
- "step": 1
- },
- "default": 12,
- "condition": {
- "enable_external_event_self_link": true
- }
- },
- "external_link_share_cooldown_hours": {
- "description": "主动外链统一冷却(小时)",
- "type": "int",
- "hint": "B 站视频、新闻和主动搜索三类主动外链共用的最小间隔。默认 72 小时,避免不同来源轮流发链接;设为 0 可关闭这道统一限制。只限制 Bot 自行发起的外链分享,不影响用户主动询问链接或官方定时消息。",
- "slider": {
- "min": 0,
- "max": 168,
- "step": 1
- },
- "default": 72
- },
- "news_max_items_per_source": {
- "description": "单源最多读取条数",
- "type": "int",
- "hint": "每个新闻源最多读取多少条候选。数值越大,整理模型看到的候选越多。",
- "slider": {
- "min": 1,
- "max": 20,
- "step": 1
- },
- "default": 5,
- "condition": {
- "enable_news_integration": true
- }
- }
- }
- },
- "web_exploration_config": {
- "description": "主动搜索",
- "type": "object",
- "hint": "控制 Bot 基于兴趣、日程和关系的自主网页探索。",
- "items": {
- "enable_web_exploration": {
- "description": "启用主动搜索",
- "type": "bool",
- "hint": "开启后 Bot 可按自己的人格、兴趣、当前状态、日程心情和最近话题,低频联网了解新鲜事物,并留下探索笔记。默认使用 AstrBot 全局网页搜索;也可在下方填写自定义搜索接口。",
- "default": false
- },
- "enable_web_exploration_boredom_search": {
- "description": "空档时自主搜索",
- "type": "bool",
- "hint": "当 Bot 比较空、无聊、休息或有好奇心时,先让模型决定想搜索什么,再调用 AstrBot 全局网页搜索或下方自定义搜索接口。",
- "default": true,
- "condition": {
- "enable_web_exploration": true
- }
- },
- "WEB_EXPLORATION_PROVIDER_ID": {
- "description": "主动搜索决策/整理模型(留空跟随新闻整理/主模型)",
- "type": "string",
- "default": "",
- "_special": "select_provider",
- "hint": "不负责联网检索;该模型只用于决定 Bot 想搜索什么,以及把搜索结果整理成探索笔记。若下方自定义搜索接口留空,联网检索继续使用 AstrBot 全局网页搜索配置。",
- "condition": {
- "enable_web_exploration": true
- }
- },
- "WEB_EXPLORATION_API_BASE_URL": {
- "description": "主动搜索自定义接口地址",
- "type": "string",
- "default": "",
- "hint": "仅主动搜索联网检索使用;留空则继续使用 AstrBot 全局网页搜索。普通搜索接口可接受 POST JSON:query、topic、max_results、model,并返回 results/items/data/search_results 等列表;也支持 GET 占位或尾插,例如 https://example.com/search?q={query} 或 https://example.com/search?q=。OpenAI 兼容 /chat/completions 也可返回 JSON 搜索结果。",
- "condition": {
- "enable_web_exploration": true
- }
- },
- "WEB_EXPLORATION_API_KEY": {
- "description": "主动搜索自定义接口 API Key",
- "type": "string",
- "default": "",
- "hint": "可选鉴权 Key。填写后请求头会带 Authorization: Bearer ;本地或内网接口不需要鉴权时可留空。",
- "condition": {
- "enable_web_exploration": true
- }
- },
- "WEB_EXPLORATION_API_MODEL": {
- "description": "主动搜索自定义接口模型",
- "type": "string",
- "default": "",
- "hint": "可选模型名。只会传给自定义搜索接口,不影响主动搜索决策/整理模型。",
- "condition": {
- "enable_web_exploration": true
- }
- },
- "web_exploration_interests": {
- "description": "探索兴趣倾向",
- "type": "string",
- "hint": "告诉 Bot 自主搜索时可以偏向哪些方向。不是硬名单,Bot 仍会结合人设、日程、最近聊天和心情自行决定。",
- "default": "按 Bot 人格自行决定;可偏向最近聊天、日程、人设兴趣、作品、技术、生活小知识、流行梗、时讯、新鲜事物。",
- "condition": {
- "enable_web_exploration": true
- }
- },
- "enable_news_daily_hot_read": {
- "description": "每日获取热点",
- "type": "bool",
- "hint": "新闻阅读开启后,默认在每日生成日程时一起获取公开热点,形成今天的外界见闻。不会单独作为第三个主动功能。",
- "default": true,
- "condition": {
- "enable_news_integration": true
- }
- },
- "news_hot_sources": {
- "description": "热点来源",
- "type": "string",
- "hint": "逗号或换行分隔。当前支持 weibo、hackernews。热点会和 RSS 新闻一起整理成今日见闻。",
- "default": "weibo,hackernews",
- "condition": {
- "enable_news_daily_hot_read": true
- }
- },
- "news_hot_max_items": {
- "description": "热点候选数量",
- "type": "int",
- "hint": "每日最多保留多少条公开热点候选。数值越大,新闻整理模型看到的信息越多。",
- "slider": {
- "min": 3,
- "max": 30,
- "step": 1
- },
- "default": 12,
- "condition": {
- "enable_news_daily_hot_read": true
- }
- },
- "web_exploration_min_interval_hours": {
- "description": "网页探索最小间隔(小时)",
- "type": "int",
- "hint": "两次自主网页搜索之间的最小间隔。建议不要太短,避免频繁调用搜索 API。",
- "slider": {
- "min": 1,
- "max": 168,
- "step": 1
- },
- "default": 8,
- "condition": {
- "enable_web_exploration_boredom_search": true
- }
- },
- "web_exploration_share_probability": {
- "description": "探索后私聊分享概率",
- "type": "float",
- "hint": "Bot 完成一次探索后,是否安排主动私聊分享的基础概率。不分享时也会保留探索笔记。",
- "slider": {
- "min": 0,
- "max": 1,
- "step": 0.05
- },
- "default": 0.18,
- "condition": {
- "enable_web_exploration": true
- }
- },
- "web_exploration_max_results": {
- "description": "网页搜索结果数",
- "type": "int",
- "hint": "每次自主搜索最多读取多少条结果。不同搜索 provider 的上限不同,插件会自动裁剪。",
- "slider": {
- "min": 3,
- "max": 20,
- "step": 1
- },
- "default": 6,
- "condition": {
- "enable_web_exploration": true
- }
- }
- }
- },
- "qzone_config": {
- "description": "QQ 空间动态",
- "type": "object",
- "hint": "控制说说查看、点赞评论、低频生活说说和配图。",
- "items": {
- "enable_qzone_integration": {
- "description": "启用 QQ 空间动态层",
- "type": "bool",
- "hint": "整合 QQ 空间查看、点赞、评论和发布说说入口。仅 OneBot/aiocqhttp 可用;QQ 官方机器人不支持,插件会自动跳过工具注入、后台轮询和发布任务。",
- "default": true
- },
- "QZONE_COOKIE": {
- "description": "QQ 空间手动 Cookie",
- "type": "text",
- "hint": "可填写浏览器 QQ 空间 Cookie,作为查看、评论、点赞和发布说说的优先凭据。留空时仍使用 OneBot 自动 Cookie。需包含 uin/p_uin 与 p_skey 或 skey;填写后可在 QQ 空间页点击刷新 Cookies,或到排障中心测试 QQ 空间链路。",
- "default": "",
- "condition": {
- "enable_qzone_integration": true
- }
- },
- "enable_qzone_life_publish": {
- "description": "低频发布生活说说",
- "type": "bool",
- "hint": "开启后, Bot 可根据当天状态、日程和日记余味低频写一条 QQ 空间说说。默认关闭,避免未经确认公开发布。",
- "default": false,
- "condition": {
- "enable_qzone_integration": true
- }
- },
- "qzone_life_publish_min_interval_hours": {
- "description": "生活说说最小间隔(小时)",
- "type": "int",
- "hint": "两次自动生活说说之间的最小间隔。",
- "slider": {
- "min": 4,
- "max": 168,
- "step": 1
- },
- "default": 24,
- "condition": {
- "enable_qzone_life_publish": true
- }
- },
- "qzone_life_publish_probability": {
- "description": "生活说说触发概率",
- "type": "float",
- "hint": "满足间隔后每轮后台检查尝试发布生活说说的概率。",
- "slider": {
- "min": 0,
- "max": 1,
- "step": 0.05
- },
- "default": 0.18,
- "condition": {
- "enable_qzone_life_publish": true
- }
- },
- "qzone_publish_style_prompt": {
- "description": "说说风格提示词",
- "type": "text",
- "hint": "用于约束自动生活说说、心情说说和说说草稿测试的口吻。留空使用内置默认:更像随手生活碎片,避免哲理总结、人生感悟和文案腔。",
- "default": "",
- "condition": {
- "enable_qzone_life_publish": true
- }
- },
- "enable_qzone_generated_image_publish": {
- "description": "主动说说可带生成图",
- "type": "bool",
- "hint": "开启后,自动生活说说或情绪说说在命中配图概率时,会调用现有生图后端生成一张公开动态配图;手动发说说未附图时会直接尝试生成配图。生图失败时只发文字,不阻断说说发布。",
- "default": true,
- "condition": {
- "enable_qzone_integration": true
- }
- },
- "qzone_generated_image_probability": {
- "description": "主动说说带图概率",
- "type": "float",
- "hint": "主动说说每次准备发布时,额外尝试生成配图的概率。仅控制是否尝试配图,不改变说说本身触发概率。",
- "slider": {
- "min": 0,
- "max": 1,
- "step": 0.05
- },
- "default": 0.25,
- "condition": {
- "enable_qzone_generated_image_publish": true
- }
- },
- "qzone_publish_image_style_prompt": {
- "description": "空间配图提示词",
- "type": "text",
- "hint": "用于约束 QQ 空间自动配图的构图和画面选择。留空使用内置默认:按正文选择生活图,人物可自然入镜,但避免过度使用镜前自拍和手机挡脸自拍。",
- "default": "",
- "condition": {
- "enable_qzone_generated_image_publish": true
- }
- },
- "enable_qzone_comment_inbox": {
- "description": "空间评论收件箱",
- "type": "bool",
- "hint": "默认关闭。开启后会低频拉取自己最近说说详情,记录已见评论,并由模型判断是否需要用追加评论方式公开回复新评论。首次开启只记录现有评论,不回复旧积压。",
- "default": false,
- "condition": {
- "enable_qzone_integration": true
- }
- },
- "qzone_comment_inbox_interval_minutes": {
- "description": "评论检查间隔(分钟)",
- "type": "int",
- "hint": "两次自动检查自己说说评论之间的最小间隔。",
- "slider": {
- "min": 5,
- "max": 1440,
- "step": 5
- },
- "default": 60,
- "condition": {
- "enable_qzone_comment_inbox": true
- }
- },
- "qzone_comment_inbox_recent_posts": {
- "description": "扫描最近说说数",
- "type": "int",
- "hint": "每次检查向前拉取多少条自己的最近说说详情来解析评论。",
- "slider": {
- "min": 1,
- "max": 20,
- "step": 1
- },
- "default": 5,
- "condition": {
- "enable_qzone_comment_inbox": true
- }
- },
- "qzone_comment_inbox_max_replies_per_tick": {
- "description": "每轮最多回复数",
- "type": "int",
- "hint": "每次后台检查最多公开回复多少条新评论。建议保持 1,避免评论区刷屏。",
- "slider": {
- "min": 1,
- "max": 5,
- "step": 1
- },
- "default": 1,
- "condition": {
- "enable_qzone_comment_inbox": true
- }
- }
- }
- },
"private_reading_config": {
"description": "私密阅读/书柜夹层",
"type": "object",
@@ -8072,7 +7130,13 @@
"description": "日记写作形式",
"type": "string",
"hint": "自动模式会按日期和当天可用经历稳定选择一种形式,不会每次重载都变化。也可固定为场景短记、碎片手记、心绪自述或观察记录。",
- "options": ["auto", "scene", "fragments", "inner_voice", "observation"],
+ "options": [
+ "auto",
+ "scene",
+ "fragments",
+ "inner_voice",
+ "observation"
+ ],
"default": "auto",
"condition": {
"enable_daily_diary": true
@@ -8082,7 +7146,11 @@
"description": "日记篇幅",
"type": "string",
"hint": "材料不足时允许比目标更短,避免为了凑字数虚构生活细节。",
- "options": ["short", "standard", "long"],
+ "options": [
+ "short",
+ "standard",
+ "long"
+ ],
"default": "standard",
"condition": {
"enable_daily_diary": true
@@ -8092,7 +7160,11 @@
"description": "日记写实程度",
"type": "string",
"hint": "严格写实只采用已确认经历;自然平衡允许轻微感官表达;个性表达可增强节奏和内心色彩,但都不会虚构事件。",
- "options": ["strict", "balanced", "expressive"],
+ "options": [
+ "strict",
+ "balanced",
+ "expressive"
+ ],
"default": "balanced",
"condition": {
"enable_daily_diary": true
@@ -8241,7 +7313,11 @@
"type": "int",
"hint": "0 表示自然推进;大于 0 时按当前六阶段总天数定位到对应周期日,并只应用一次。重启不会重复重置;修改数值或阶段天数后才会重新应用。",
"default": 0,
- "slider": { "min": 0, "max": 180, "step": 1 },
+ "slider": {
+ "min": 0,
+ "max": 180,
+ "step": 1
+ },
"condition": {
"enable_advanced_cycle_strategy": true
}
@@ -8250,164 +7326,260 @@
"description": "月经期持续天数",
"type": "int",
"default": 5,
- "slider": { "min": 1, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": 1,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_menstrual_prompt": {
"description": "月经期状态描述",
"type": "string",
"hint": "作为 Bot 当前模拟状态的柔性背景,不应写成医学结论或固定台词。",
"default": "处于月经期,身体更容易疲倦,情绪感受稍敏锐",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_menstrual_mood": {
"description": "月经期情绪底色",
"type": "string",
"default": "疲惫",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_menstrual_energy": {
"description": "月经期精力变化",
"type": "int",
"hint": "仅在关闭强度联动时使用。",
"default": -12,
- "slider": { "min": -50, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": -50,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_follicular_days": {
"description": "卵泡期早持续天数",
"type": "int",
"default": 5,
- "slider": { "min": 1, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": 1,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_follicular_prompt": {
"description": "卵泡期早状态描述",
"type": "string",
"default": "处于卵泡期早,精力平稳回升,心情逐渐轻快",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_follicular_mood": {
"description": "卵泡期早情绪底色",
"type": "string",
"default": "轻快",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_follicular_energy": {
"description": "卵泡期早精力变化",
"type": "int",
"hint": "仅在关闭强度联动时使用;设为 0 仍会保留该阶段并继续推进。",
"default": 0,
- "slider": { "min": -50, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": -50,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_pre_ovulation_days": {
"description": "排卵前期持续天数",
"type": "int",
"default": 3,
- "slider": { "min": 1, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": 1,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_pre_ovulation_prompt": {
"description": "排卵前期状态描述",
"type": "string",
"default": "处于排卵前期,身体逐渐轻盈,精力有所上升",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_pre_ovulation_mood": {
"description": "排卵前期情绪底色",
"type": "string",
"default": "期待",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_pre_ovulation_energy": {
"description": "排卵前期精力变化",
"type": "int",
"hint": "仅在关闭强度联动时使用。",
"default": 8,
- "slider": { "min": -50, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": -50,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_ovulation_days": {
"description": "排卵期持续天数",
"type": "int",
"default": 1,
- "slider": { "min": 1, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": 1,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_ovulation_prompt": {
"description": "排卵期状态描述",
"type": "string",
"default": "处于排卵期,精力较充足,社交意愿稍有增强",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_ovulation_mood": {
"description": "排卵期情绪底色",
"type": "string",
"default": "明朗",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_ovulation_energy": {
"description": "排卵期精力变化",
"type": "int",
"hint": "仅在关闭强度联动时使用。",
"default": 9,
- "slider": { "min": -50, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": -50,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_luteal_days": {
"description": "黄体期早持续天数",
"type": "int",
"default": 8,
- "slider": { "min": 1, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": 1,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_luteal_prompt": {
"description": "黄体期早状态描述",
"type": "string",
"default": "处于黄体期早,精力尚可,情绪整体平稳",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_luteal_mood": {
"description": "黄体期早情绪底色",
"type": "string",
"default": "平稳",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_luteal_energy": {
"description": "黄体期早精力变化",
"type": "int",
"hint": "仅在关闭强度联动时使用。",
"default": 5,
- "slider": { "min": -50, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": -50,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_pms_days": {
"description": "PMS 期持续天数",
"type": "int",
"default": 6,
- "slider": { "min": 1, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": 1,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_pms_prompt": {
"description": "PMS 期状态描述",
"type": "string",
"default": "处于 PMS 期,精力有所下降,情绪波动稍明显",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_pms_mood": {
"description": "PMS 期情绪底色",
"type": "string",
"default": "敏感",
- "condition": { "enable_advanced_cycle_strategy": true }
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"advanced_cycle_pms_energy": {
"description": "PMS 期精力变化",
"type": "int",
"hint": "仅在关闭强度联动时使用。",
"default": -8,
- "slider": { "min": -50, "max": 30, "step": 1 },
- "condition": { "enable_advanced_cycle_strategy": true }
+ "slider": {
+ "min": -50,
+ "max": 30,
+ "step": 1
+ },
+ "condition": {
+ "enable_advanced_cycle_strategy": true
+ }
},
"humanized_state_intensity": {
"description": "拟人状态强度",
@@ -9218,125 +8390,6 @@
}
}
},
- "screen_action_config": {
- "description": "主动识屏行为",
- "type": "object",
- "hint": "控制轻窥屏、识屏每日上限、冷却和主动后沉默窥屏。",
- "items": {
- "enable_screen_glance_action": {
- "description": "允许主动看一眼屏幕",
- "type": "bool",
- "hint": "默认关闭。开启后,Bot 才可能在关心、好奇、确认状态等合适动机下调用屏幕陪伴插件观察当前屏幕;结果只作为 LLM 上下文,并会要求避免暴露隐私细节。识屏开始即计入额度,避免发送失败或重启后反复识屏。",
- "default": false
- },
- "screen_peek_max_daily": {
- "description": "每日主动识屏最多次数",
- "type": "int",
- "hint": "按用户计数。开始调用屏幕插件就会消耗额度,即使后续消息发送失败也不会立刻继续识屏。设为 0 表示禁止主动识屏。",
- "slider": {
- "min": 0,
- "max": 5,
- "step": 1
- },
- "default": 1,
- "condition": {
- "enable_screen_glance_action": true
- }
- },
- "screen_peek_cooldown_minutes": {
- "description": "主动识屏冷却分钟数",
- "type": "int",
- "hint": "按用户计时。用于防止多个主动候选在短时间内连续调用识屏。设为 0 表示不启用冷却,不建议。",
- "slider": {
- "min": 0,
- "max": 1440,
- "step": 10
- },
- "default": 240,
- "condition": {
- "enable_screen_glance_action": true
- }
- },
- "enable_unanswered_screen_peek_followup": {
- "description": "主动后沉默可额外窥屏",
- "type": "bool",
- "hint": "开启后,如果 Bot 因无聊或空档主动找用户,过一段时间用户仍未回复,Bot 可以额外窥屏确认用户在做什么。这类窥屏不消耗每日主动识屏次数,但仍受识屏插件可用性和冷却约束。",
- "default": true,
- "condition": {
- "enable_screen_glance_action": true
- }
- },
- "unanswered_screen_peek_after_minutes": {
- "description": "主动后沉默窥屏等待分钟数",
- "type": "int",
- "hint": "主动消息发出后,用户持续没有回复多久才考虑触发这次额外窥屏。用户期间有新消息会自动取消。",
- "slider": {
- "min": 10,
- "max": 240,
- "step": 5
- },
- "default": 45,
- "condition": {
- "enable_unanswered_screen_peek_followup": true
- }
- },
- "unanswered_screen_peek_cooldown_minutes": {
- "description": "沉默窥屏冷却分钟数",
- "type": "int",
- "hint": "只限制主动后沉默触发的额外窥屏,避免连续多轮主动后反复看屏。它不等同于每日次数上限。",
- "slider": {
- "min": 30,
- "max": 1440,
- "step": 10
- },
- "default": 180,
- "condition": {
- "enable_unanswered_screen_peek_followup": true
- }
- }
- }
- },
- "poke_action_config": {
- "description": "主动戳一戳",
- "type": "object",
- "hint": "控制主动戳一戳能力和每日次数。",
- "items": {
- "enable_poke_action": {
- "description": "允许主动戳一戳",
- "type": "bool",
- "hint": "开启后,Bot 可能在想轻轻刷存在感、嘴硬关心或逗一下用户时主动戳一戳,然后再自然补一句私聊。默认关闭,避免太跳。",
- "default": false
- },
- "poke_action_max_times": {
- "description": "每次主动戳一戳最多次数",
- "type": "int",
- "hint": "每次主动 poke 最多戳几下。实际主动行为默认只会轻轻戳一下,这个值主要作为上限兜底。",
- "slider": {
- "min": 1,
- "max": 3,
- "step": 1
- },
- "default": 1,
- "condition": {
- "enable_poke_action": true
- }
- },
- "poke_action_cooldown_minutes": {
- "description": "主动戳一戳冷却分钟数",
- "type": "int",
- "hint": "同一用户一次主动戳一戳成功后,至少等待多久才允许再次主动戳。用于阻止候选重试、并发调度或正文生成失败造成重复动作;默认 30 分钟,0 表示不设置时间冷却但仍保留并发锁。",
- "slider": {
- "min": 0,
- "max": 1440,
- "step": 5
- },
- "default": 30,
- "condition": {
- "enable_poke_action": true
- }
- }
- }
- },
"voice_action_config": {
"description": "主动语音行为",
"type": "object",
@@ -9821,28 +8874,6 @@
}
}
},
- "presence_sync_config": {
- "description": "QQ 状态同步",
- "type": "object",
- "hint": "同步 QQ 在线/忙碌等基础在线状态;自定义短状态涉及非标准 OneBot 扩展,默认关闭。",
- "items": {
- "enable_qq_presence_sync": {
- "description": "同步 QQ 在线状态",
- "type": "bool",
- "hint": "开启后,当前时间段细化可决定在线/忙碌等基础状态,并通过 OneBot 的 set_online_status 尝试同步。离开、隐身、请勿打扰会自动降级为在线;失败会静默跳过。",
- "default": true
- },
- "enable_qq_custom_presence_sync": {
- "description": "同步 QQ 自定义短状态",
- "type": "bool",
- "hint": "默认关闭。开启后才会尝试同步“专注中/休息中”等自定义短状态;该能力依赖协议端支持非标准 OneBot 扩展,不会调用已知会让部分 NapCat 版本断连的 set_custom_online_status。",
- "default": false,
- "condition": {
- "enable_qq_presence_sync": true
- }
- }
- }
- },
"weather_config": {
"description": "天气上下文与屏幕日记",
"type": "object",
@@ -9942,26 +8973,6 @@
"enable_weather_context": true,
"enable_environment_change_proactive": true
}
- },
- "enable_yesterday_screen_diary_context": {
- "description": "读取昨日屏幕观察日记",
- "type": "bool",
- "hint": "开启后,private_companion 每天只读取 screen_companion 的昨日观察日记脱敏摘要,作为今日状态和日程背景。不会读取今天实时屏幕,也会要求 Bot 不直接说“我昨天看到你”。",
- "default": true
- },
- "screen_diary_context_max_chars": {
- "description": "昨日屏幕日记上下文字数",
- "type": "int",
- "hint": "注入给状态/日程模型的昨日屏幕观察摘要最大字符数。建议保持较短,只保留活动类型和节奏,不保留窗口标题或隐私细节。",
- "slider": {
- "min": 200,
- "max": 1600,
- "step": 100
- },
- "default": 700,
- "condition": {
- "enable_yesterday_screen_diary_context": true
- }
}
}
},
@@ -10102,57 +9113,6 @@
"condition": {
"enable_emotion_simulation": true
}
- },
- "enable_qzone_emotional_vent_publish": {
- "description": "公开心情动态",
- "type": "bool",
- "hint": "短期余波很重时,可在 QQ 空间动态层可用且冷却通过的情况下低频发布一条模糊心情说说。默认关闭,避免未经确认公开发布。",
- "default": false,
- "condition": {
- "enable_emotion_simulation": true
- }
- },
- "qzone_emotional_vent_threshold": {
- "description": "心情动态触发阈值",
- "type": "int",
- "hint": "短期余波达到该值后,才可能触发公开心情动态。",
- "slider": {
- "min": 40,
- "max": 100,
- "step": 5
- },
- "default": 90,
- "condition": {
- "enable_qzone_emotional_vent_publish": true
- }
- },
- "qzone_emotional_vent_cooldown_hours": {
- "description": "心情动态冷却小时",
- "type": "int",
- "hint": "两次公开心情动态之间的最小间隔。",
- "slider": {
- "min": 4,
- "max": 336,
- "step": 4
- },
- "default": 72,
- "condition": {
- "enable_qzone_emotional_vent_publish": true
- }
- },
- "qzone_emotional_vent_probability": {
- "description": "心情动态触发概率",
- "type": "float",
- "hint": "达到极端情绪阈值并通过冷却后,实际尝试发布说说的概率。",
- "slider": {
- "min": 0,
- "max": 1,
- "step": 0.05
- },
- "default": 0.35,
- "condition": {
- "enable_qzone_emotional_vent_publish": true
- }
}
}
},
@@ -10484,20 +9444,6 @@
"default": "",
"invisible": true
},
- "allow_screen_peek_action": {
- "description": "旧版主动识屏开关",
- "type": "string",
- "hint": "旧版配置项;现在请使用 enable_screen_glance_action。",
- "default": "",
- "invisible": true
- },
- "allow_poke_action": {
- "description": "旧版戳一戳开关",
- "type": "string",
- "hint": "旧版配置项;现在请使用 enable_poke_action。",
- "default": "",
- "invisible": true
- },
"allow_voice_action": {
"description": "旧版主动语音开关",
"type": "string",
@@ -10519,20 +9465,6 @@
"default": false,
"invisible": true
},
- "hot_trend_sources": {
- "description": "旧版热榜来源",
- "type": "string",
- "hint": "旧版配置项;现在请使用 news_hot_sources。",
- "default": "",
- "invisible": true
- },
- "hot_trend_max_items": {
- "description": "旧版热榜条数",
- "type": "string",
- "hint": "旧版配置项;现在请使用 news_hot_max_items。",
- "default": "",
- "invisible": true
- },
"enable_jm_cosmos_integration": {
"description": "旧版夹层阅读开关",
"type": "bool",
diff --git a/command_handlers.py b/command_handlers.py
index 6b3a5d6..b8511cc 100644
--- a/command_handlers.py
+++ b/command_handlers.py
@@ -2862,7 +2862,6 @@ class CommandHandlersMixin:
"private_image.py",
"group_wakeup.py",
"group_observation.py",
- "qzone_integration.py",
"tts_enhancement.py",
"token_budget.py",
)
diff --git a/daily_state.py b/daily_state.py
index b1e2006..142a91d 100644
--- a/daily_state.py
+++ b/daily_state.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:
diff --git a/docs/OPS陪伴插件全功能盘点与删减评估.md b/docs/OPS陪伴插件全功能盘点与删减评估.md
new file mode 100644
index 0000000..5eb1351
--- /dev/null
+++ b/docs/OPS陪伴插件全功能盘点与删减评估.md
@@ -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 部署和数据删除。
diff --git a/docs/运维陪伴错题本.md b/docs/运维陪伴错题本.md
index e37bfb9..4928226 100644
--- a/docs/运维陪伴错题本.md
+++ b/docs/运维陪伴错题本.md
@@ -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 页面脚本残留扫描无结果;源码编译通过。
diff --git a/llm_tool_actions.py b/llm_tool_actions.py
index 3ae247f..03bcda0 100644
--- a/llm_tool_actions.py
+++ b/llm_tool_actions.py
@@ -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]] = {}
diff --git a/main.py b/main.py
index 78fcc7c..d6590b0 100644
--- a/main.py
+++ b/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 = ""
- 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)
diff --git a/news_exploration.py b/news_exploration.py
deleted file mode 100644
index 154b24c..0000000
--- a/news_exploration.py
+++ /dev/null
@@ -1,4548 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
-NewsExplorationMixin — 从 main.py 重新拆分出的新闻阅读/网页探索
-"""
-from __future__ import annotations
-
-import asyncio
-import base64
-import codecs
-import gc
-import hashlib
-import html
-import importlib
-import json
-import math
-import os
-import random
-import re
-import shutil
-import sys
-import time
-import unicodedata
-import uuid
-import zoneinfo
-from copy import deepcopy
-from datetime import date, datetime, timedelta
-from email.utils import parsedate_to_datetime
-from http.cookies import SimpleCookie
-from pathlib import Path
-from types import SimpleNamespace
-from typing import Any
-from urllib.parse import parse_qsl, quote, urlencode, urlparse, urlunparse
-from xml.etree import ElementTree as ET
-
-from astrbot.api import AstrBotConfig, logger
-from astrbot.api.event import AstrMessageEvent, MessageChain, filter
-try:
- from astrbot.api.message_components import At, Image, Plain, Record, Reply
-except ImportError:
- from astrbot.api.message_components import At, Image, Plain
- from astrbot.core.message.components import Record
- try:
- from astrbot.api.message_components import Reply
- except ImportError:
- try:
- from astrbot.core.message.components import Reply
- except ImportError:
- Reply = None
-from astrbot.api.provider import ProviderRequest
-from astrbot.api.star import Context, Star, StarTools, register
-from astrbot.core import file_token_service
-from astrbot.core.astr_main_agent import MainAgentBuildConfig, build_main_agent
-from astrbot.core.agent.message import AssistantMessageSegment, TextPart, UserMessageSegment
-from astrbot.core.db.po import Conversation
-from astrbot.core.platform.astrbot_message import AstrBotMessage, MessageMember
-from astrbot.core.platform.message_session import MessageSession
-from astrbot.core.platform.message_type import MessageType
-from astrbot.core.platform.platform import PlatformStatus
-from astrbot.core.platform.platform_metadata import PlatformMetadata
-from astrbot.core.star.star_handler import EventType, star_handlers_registry
-from astrbot.core.provider.entities import LLMResponse
-from astrbot.core.utils.astrbot_path import get_astrbot_data_path
-
-try:
- import chinese_calendar as calendar_cn
-except Exception:
- calendar_cn = None
-
-try:
- from lunarcalendar import Converter, Solar
-except Exception:
- Converter = None
- Solar = None
-
-from .constants import (
- DEFAULT_DAILY_PLAN_ITEMS,
- DEFAULT_HUMANIZED_STATE,
- PLUGIN_NAME,
- DATA_VERSION,
- PROACTIVE_ABILITY_REGISTRY,
- VOICE_FALLBACK_TEMPLATES,
- TIMER_TAG_PATTERN,
- SUPPORTED_TIMER_FORMATS,
- _ACTION_TEXT,
- _DATA_STORE_KEYS,
- _DEFAULT_GROUP_TEMPLATE,
- _DEFAULT_USER_TEMPLATE,
- _REASON_TEXT,
- _SIMULATION_FALLBACK_EVENTS,
-)
-from .dreaming import (
- build_dream_memory_fragments,
- dream_fragment_effective_weight,
- dream_theme_specs,
- extract_weighted_dream_fragments,
- fallback_diary_payload,
- fallback_dream_fragments_for_diary,
- generate_daily_diary,
- generate_enhanced_dream_pick,
- merge_dream_fragment_pool,
- normalize_dream_fragment_item,
- normalize_dream_fragment_pool,
- recent_diary_context,
- recent_diary_tags,
- weighted_unique_fragment_sample,
-)
-from .helpers import _date_key, _now_ts, _safe_float, _safe_int, _single_line, _strip_internal_message_blocks, _text_looks_garbled, _today_key
-from .planning import (
- build_daily_plan_prompt,
- build_detail_enhancement_prompt,
- format_plan_for_diary,
- generate_daily_plan,
- generate_detail_enhancement,
- get_schedule_planning_prompt,
- normalize_long_term_events,
- normalize_story_items,
- normalize_story_plan,
- pick_detail_segment,
-)
-
-DEFAULT_AI_DAILY_MORNING_UID = "3706929260006322"
-DEFAULT_AI_DAILY_JUYA_UID = "285286947"
-DEFAULT_AI_DAILY_SOURCES = "\n".join(
- [
- f"AI日报|橘鸦Juya|{DEFAULT_AI_DAILY_JUYA_UID}|日报 早报|23:00",
- f"AI早报|黑鸦Heya|{DEFAULT_AI_DAILY_MORNING_UID}|早报 日报|12:00",
- ]
-)
-BILIBILI_AI_BOT_PLUGIN_NAME = "astrbot_plugin_bilibili_ai_bot"
-BILIBILI_PUBLIC_INFO_PLUGIN_NAME = "astrbot_plugin_bilibili"
-BILIBILI_AI_BOT_LEGACY_DATA_NAMES = (
- BILIBILI_AI_BOT_PLUGIN_NAME,
- "astrbot_plugin_bilibili_bot",
-)
-
-DEFAULT_NEWS_SOURCES = "\n".join(
- [
- "BBC中文|https://feeds.bbci.co.uk/zhongwen/simp/rss.xml",
- "Google新闻中文|https://news.google.com/rss?hl=zh-CN&gl=CN&ceid=CN:zh-Hans",
- "Solidot|https://www.solidot.org/index.rss",
- "Hacker News|https://hnrss.org/frontpage",
- "MIT Technology Review|https://www.technologyreview.com/feed/",
- "Ars Technica|https://feeds.arstechnica.com/arstechnica/index",
- ]
-)
-
-LEGACY_DEFAULT_NEWS_SOURCES = "\n".join(
- [
- "BBC中文|https://feeds.bbci.co.uk/zhongwen/simp/rss.xml",
- "Google新闻中文|https://news.google.com/rss?hl=zh-CN&gl=CN&ceid=CN:zh-Hans",
- "Solidot|https://www.solidot.org/index.rss",
- ]
-)
-
-PREVIOUS_TECH_DEFAULT_NEWS_SOURCES = "\n".join(
- [
- "BBC中文|https://feeds.bbci.co.uk/zhongwen/simp/rss.xml",
- "Google新闻中文|https://news.google.com/rss?hl=zh-CN&gl=CN&ceid=CN:zh-Hans",
- "Solidot|https://www.solidot.org/index.rss",
- "Hacker News|https://hnrss.org/frontpage",
- "MIT Technology Review|https://www.technologyreview.com/feed/",
- "Ars Technica|https://feeds.arstechnica.com/arstechnica/index",
- ]
-)
-
-
-
-_LUNAR_MONTH_NAMES = [
- "正月",
- "二月",
- "三月",
- "四月",
- "五月",
- "六月",
- "七月",
- "八月",
- "九月",
- "十月",
- "冬月",
- "腊月",
-]
-_LUNAR_DAY_NAMES = [
- "初一",
- "初二",
- "初三",
- "初四",
- "初五",
- "初六",
- "初七",
- "初八",
- "初九",
- "初十",
- "十一",
- "十二",
- "十三",
- "十四",
- "十五",
- "十六",
- "十七",
- "十八",
- "十九",
- "二十",
- "廿一",
- "廿二",
- "廿三",
- "廿四",
- "廿五",
- "廿六",
- "廿七",
- "廿八",
- "廿九",
- "三十",
-]
-_SOLAR_TERM_DATES = {
- (1, 5): "小寒",
- (1, 20): "大寒",
- (2, 4): "立春",
- (2, 19): "雨水",
- (3, 5): "惊蛰",
- (3, 20): "春分",
- (4, 4): "清明",
- (4, 20): "谷雨",
- (5, 5): "立夏",
- (5, 21): "小满",
- (6, 5): "芒种",
- (6, 21): "夏至",
- (7, 7): "小暑",
- (7, 22): "大暑",
- (8, 7): "立秋",
- (8, 23): "处暑",
- (9, 7): "白露",
- (9, 23): "秋分",
- (10, 8): "寒露",
- (10, 23): "霜降",
- (11, 7): "立冬",
- (11, 22): "小雪",
- (12, 7): "大雪",
- (12, 22): "冬至",
-}
-_ALMANAC_YI = ["整理房间", "写字", "散步", "读书", "听歌", "轻度创作", "复盘", "安静休息"]
-_ALMANAC_JI = ["熬夜", "冲动发言", "硬撑", "反复纠结", "过度解释", "临时加压", "情绪化决定"]
-_PLATFORM_DISPLAY_NAMES = {
- "aiocqhttp": "QQ",
- "qq": "QQ",
- "onebot": "QQ",
- "telegram": "Telegram",
- "wechat": "微信",
- "discord": "Discord",
-}
-_NEWS_BINARY_CONTENT_TYPE_PREFIXES = ("image/", "audio/", "video/", "font/")
-_NEWS_BINARY_CONTENT_TYPES = {
- "application/octet-stream",
- "application/pdf",
- "application/zip",
- "application/x-gzip",
- "application/x-protobuf",
-}
-_NEWS_TEXTUAL_CONTENT_TYPES = {
- "application/xhtml+xml",
- "application/xml",
- "application/rss+xml",
- "application/atom+xml",
- "image/svg+xml",
- "text/html",
- "text/plain",
- "text/xml",
-}
-_NEWS_BINARY_SIGNATURES = (
- b"\xff\xd8\xff",
- b"JFIF\x00",
- b"Exif\x00\x00",
- b"\x89PNG\r\n\x1a\n",
- b"GIF87a",
- b"GIF89a",
- b"RIFF",
- b"%PDF-",
- b"PK\x03\x04",
-)
-_NEWS_MOJIBAKE_MARKERS = ("Ã", "â", "鈥", "銆", "鏉", "锟", "Ð", "Ê", "¤", "\ufffd")
-
-
-def _news_content_type_base(content_type: Any) -> str:
- return str(content_type or "").split(";", 1)[0].strip().lower()
-
-
-def _news_charset_from_content_type(content_type: Any) -> str:
- match = re.search(r"charset\s*=\s*['\"]?\s*([A-Za-z0-9._-]+)", str(content_type or ""), flags=re.I)
- return match.group(1).strip() if match else ""
-
-
-def _news_meta_charset(raw_bytes: bytes) -> str:
- head = raw_bytes[:4096].decode("ascii", errors="ignore")
- for pattern in (
- r"]+charset=['\"]?\s*([A-Za-z0-9._-]+)",
- r"]+content=['\"][^>]*charset\s*=\s*([A-Za-z0-9._-]+)",
- ):
- match = re.search(pattern, head, flags=re.I)
- if match:
- return match.group(1).strip()
- return ""
-
-
-def _normalize_news_charset(name: Any) -> str:
- normalized = str(name or "").strip().lower().replace("_", "-")
- aliases = {
- "gb2312": "gb18030",
- "gbk": "gb18030",
- "x-gbk": "gb18030",
- "utf8": "utf-8",
- }
- return aliases.get(normalized, normalized)
-
-
-def _news_response_looks_binary(raw_bytes: bytes, *, content_type: Any = "") -> bool:
- sample = raw_bytes[:2048]
- base_type = _news_content_type_base(content_type)
- if base_type:
- if any(base_type.startswith(prefix) for prefix in _NEWS_BINARY_CONTENT_TYPE_PREFIXES):
- return True
- if base_type in _NEWS_BINARY_CONTENT_TYPES:
- return True
- if base_type not in _NEWS_TEXTUAL_CONTENT_TYPES and not base_type.startswith("text/"):
- lowered = sample[:512].lower()
- if b" 0:
- return True
- control_bytes = sum(1 for byte in sample if byte < 32 and byte not in (9, 10, 13))
- if sample and control_bytes / len(sample) > 0.2:
- return True
- return False
-
-
-def _score_news_decoded_text(text: str) -> tuple[int, int]:
- if not text:
- return (10**9, 0)
- sample = text[:6000]
- replacement_count = sample.count("\ufffd")
- mojibake_count = sum(sample.count(marker) for marker in _NEWS_MOJIBAKE_MARKERS if marker != "\ufffd")
- control_count = sum(1 for ch in sample if ord(ch) < 32 and ch not in "\n\r\t")
- html_markers = len(re.findall(r"<(?:html|body|article|div|p|meta|title)\b", sample, flags=re.I))
- readable_count = sum(
- 1
- for ch in sample
- if ch.isalnum() or ch in " \n\r\t,。!?;:、“”‘’()《》【】—-.,!?;:()[]/%&+#@_=<>\"'"
- )
- score = replacement_count * 24 + mojibake_count * 8 + control_count * 40
- score -= min(html_markers * 6, 60)
- score -= min(readable_count // 24, 40)
- return (score, -len(sample))
-
-
-def _decode_news_response_text(
- raw_bytes: bytes,
- *,
- content_type: Any = "",
- declared_charset: Any = "",
-) -> str:
- if not raw_bytes:
- return ""
- candidates: list[str] = []
- if raw_bytes.startswith(codecs.BOM_UTF8):
- candidates.append("utf-8-sig")
- elif raw_bytes.startswith(codecs.BOM_UTF16_LE):
- candidates.append("utf-16-le")
- elif raw_bytes.startswith(codecs.BOM_UTF16_BE):
- candidates.append("utf-16-be")
- candidates.extend(
- [
- _normalize_news_charset(declared_charset),
- _normalize_news_charset(_news_charset_from_content_type(content_type)),
- _normalize_news_charset(_news_meta_charset(raw_bytes)),
- "utf-8",
- "utf-8-sig",
- "gb18030",
- "big5",
- "latin1",
- ]
- )
- seen: set[str] = set()
- best_text = ""
- best_score = (10**9, 0)
- for encoding in candidates:
- if not encoding or encoding in seen:
- continue
- seen.add(encoding)
- for error_mode, penalty in (("strict", 0), ("replace", 12)):
- try:
- decoded = raw_bytes.decode(encoding, errors=error_mode)
- except Exception:
- continue
- if not decoded.strip():
- continue
- score = _score_news_decoded_text(decoded)
- adjusted = (score[0] + penalty, score[1])
- if adjusted < best_score:
- best_score = adjusted
- best_text = decoded
- if best_text:
- return best_text
- return raw_bytes.decode("utf-8", errors="ignore")
-
-class NewsExplorationMixin:
- """新闻阅读/网页探索"""
-
- def _clean_bilibili_share_field(self, value: Any, limit: int = 160) -> str:
- cleaner = getattr(self, "_clean_external_share_source_field", None)
- if callable(cleaner):
- try:
- return cleaner(value, limit)
- except Exception:
- pass
- text = _single_line(value, limit)
- checker = getattr(self, "_looks_like_internal_provider_error_text", None)
- if callable(checker):
- try:
- if checker(text):
- return ""
- except Exception:
- pass
- return text
-
- def _external_event_pool(self) -> list[dict[str, Any]]:
- raw = self.data.setdefault("external_event_pool", [])
- if not isinstance(raw, list):
- raw = []
- self.data["external_event_pool"] = raw
- return raw
-
- def _cleanup_external_event_pool(self, *, now: float | None = None) -> list[dict[str, Any]]:
- now = _now_ts() if now is None else now
- kept: list[dict[str, Any]] = []
- for item in self._external_event_pool():
- if not isinstance(item, dict):
- continue
- created = _safe_float(item.get("created_ts"), 0)
- if created > 0 and now - created <= 48 * 3600:
- kept.append(item)
- self.data["external_event_pool"] = kept[-200:]
- return self.data["external_event_pool"]
-
- def _external_event_signature(self, payload: dict[str, Any], *, source_type: str = "") -> str:
- title = _single_line(payload.get("headline") or payload.get("topic") or payload.get("title") or payload.get("source_title"), 120).lower()
- source = _single_line(payload.get("selected_source") or payload.get("source_title") or payload.get("source"), 60).lower()
- link = _single_line(payload.get("selected_link") or payload.get("source_url") or payload.get("link") or payload.get("video_link"), 220).lower()
- if link:
- link = re.sub(r"https?://", "", link)
- link = link.split("?", 1)[0]
- compact = re.sub(r"[^a-z0-9\u4e00-\u9fff]+", "", title)
- return "|".join(part for part in (_single_line(source_type, 24).lower(), source[:24], compact[:64], link[:96]) if part)
-
- def _external_event_title_fingerprint(self, payload: dict[str, Any], *, source_type: str = "") -> str:
- title = _single_line(payload.get("headline") or payload.get("topic") or payload.get("title") or payload.get("source_title"), 140).lower()
- if not title:
- return ""
- title = re.sub(r"https?://\S+", "", title)
- title = re.sub(r"\b\d{4}[-/年]\d{1,2}[-/月]\d{1,2}日?\b", "", title)
- title = re.sub(r"\b\d{1,2}:\d{2}\b", "", title)
- title = re.sub(r"(?:第?\d+[期条]|今日|今天|昨夜|昨天|早报|日报|周报|速览|合集|汇总)", "", title)
- compact = re.sub(r"[^a-z0-9\u4e00-\u9fff]+", "", title)
- if len(compact) < 8:
- return ""
- digest = hashlib.sha1(compact.encode("utf-8", "ignore")).hexdigest()[:20]
- return f"{_single_line(source_type, 24).lower()}:title:{digest}"
-
- def _external_event_self_link_cache(self) -> dict[str, Any]:
- raw = self.data.setdefault("external_event_self_link_cache", {})
- if not isinstance(raw, dict):
- raw = {}
- self.data["external_event_self_link_cache"] = raw
- return raw
-
- def _cleanup_external_event_self_link_cache(self, *, now: float | None = None) -> dict[str, Any]:
- now = _now_ts() if now is None else now
- cache = self._external_event_self_link_cache()
- kept: dict[str, Any] = {}
- ranked: list[tuple[float, str, dict[str, Any]]] = []
- for key, item in cache.items():
- if not isinstance(item, dict):
- continue
- created = _safe_float(item.get("created_ts"), 0)
- if created <= 0 or now - created > 72 * 3600:
- continue
- ranked.append((_safe_float(item.get("last_hit_ts"), created), str(key), item))
- ranked.sort(key=lambda row: row[0])
- for _, key, item in ranked[-240:]:
- kept[key] = item
- self.data["external_event_self_link_cache"] = kept
- return kept
-
- def _external_event_self_link_cache_keys(self, payload: dict[str, Any], *, source_type: str = "") -> list[str]:
- keys: list[str] = []
- for key in (
- self._external_event_signature(payload, source_type=source_type),
- self._external_event_title_fingerprint(payload, source_type=source_type),
- ):
- key = _single_line(key, 220)
- if key and key not in keys:
- keys.append(key)
- return keys
-
- def _cached_external_event_wish(self, payload: dict[str, Any], *, source_type: str = "") -> dict[str, Any]:
- keys = self._external_event_self_link_cache_keys(payload, source_type=source_type)
- if not keys:
- return {}
- now = _now_ts()
- cache = self._cleanup_external_event_self_link_cache(now=now)
- for key in keys:
- item = cache.get(key)
- if not isinstance(item, dict):
- continue
- wish = item.get("wish")
- if not isinstance(wish, dict):
- continue
- item["hit_count"] = _safe_int(item.get("hit_count"), 0, 0) + 1
- item["last_hit_ts"] = now
- result = dict(wish)
- result["cache_hit"] = True
- result["cache_key"] = key
- logger.info(
- "[PrivateCompanion] 外界信息自我关联命中缓存: source=%s key=%s hit=%s",
- source_type,
- key,
- item["hit_count"],
- )
- return result
- return {}
-
- def _remember_external_event_wish_cache(self, payload: dict[str, Any], wish: dict[str, Any], *, source_type: str = "") -> None:
- if not isinstance(wish, dict) or not wish:
- return
- keys = self._external_event_self_link_cache_keys(payload, source_type=source_type)
- if not keys:
- return
- now = _now_ts()
- cache = self._cleanup_external_event_self_link_cache(now=now)
- stored_wish = {
- key: value
- for key, value in dict(wish).items()
- if key
- in {
- "relevance",
- "desire",
- "should_share",
- "share_probability",
- "self_link",
- "motive",
- "tone",
- "boundary",
- "source_type",
- "boost_reason",
- }
- }
- stored_wish["created_ts"] = now
- stored_wish["source_type"] = _single_line(source_type, 24)
- title = _single_line(payload.get("headline") or payload.get("topic") or payload.get("title") or payload.get("source_title"), 120)
- for key in keys:
- cache[key] = {
- "wish": stored_wish,
- "title": title,
- "source_type": _single_line(source_type, 24),
- "created_ts": now,
- "last_hit_ts": now,
- "hit_count": _safe_int((cache.get(key) or {}).get("hit_count") if isinstance(cache.get(key), dict) else 0, 0, 0),
- }
- self._cleanup_external_event_self_link_cache(now=now)
-
- def _external_event_recently_seen(self, payload: dict[str, Any], *, source_type: str = "", now: float | None = None) -> bool:
- now = _now_ts() if now is None else now
- signature = self._external_event_signature(payload, source_type=source_type)
- if not signature:
- return False
- for item in self._cleanup_external_event_pool(now=now):
- if str(item.get("signature") or "") != signature:
- continue
- if now - _safe_float(item.get("created_ts"), 0) <= 24 * 3600:
- return True
- return False
-
- def _remember_external_event(self, payload: dict[str, Any], *, source_type: str = "", reason: str = "") -> None:
- now = _now_ts()
- signature = self._external_event_signature(payload, source_type=source_type)
- if not signature:
- return
- pool = self._cleanup_external_event_pool(now=now)
- pool.append(
- {
- "signature": signature,
- "source_type": _single_line(source_type, 24),
- "reason": _single_line(reason, 40),
- "title": _single_line(payload.get("headline") or payload.get("topic") or payload.get("title"), 120),
- "created_ts": now,
- }
- )
- del pool[:-200]
-
- @staticmethod
- def _external_event_payload_text(payload: dict[str, Any], *, limit: int = 900) -> str:
- if not isinstance(payload, dict):
- return ""
- parts: list[str] = []
- for key in (
- "headline",
- "topic",
- "title",
- "impression",
- "summary",
- "note",
- "comment",
- "review",
- "up_name",
- "selected_source",
- "source",
- "source_title",
- "video_context_text",
- ):
- value = payload.get(key)
- if isinstance(value, list):
- value = " ".join(str(item) for item in value[:6])
- text = _single_line(value, 260)
- if text:
- parts.append(text)
- for key in ("tags", "keywords", "actions", "memory_context"):
- value = payload.get(key)
- if isinstance(value, list):
- text = " ".join(_single_line(item, 80) for item in value[:8] if _single_line(item, 80))
- if text:
- parts.append(text)
- return _single_line(" ".join(parts), limit)
-
- def _external_event_user_preference_profile(self, user: dict[str, Any]) -> dict[str, Any]:
- profile: dict[str, Any] = {
- "positive": [],
- "negative": [],
- "context": "",
- }
- memory = user.get("companion_memory") if isinstance(user, dict) else {}
- llm_profile = memory.get("profile") if isinstance(memory, dict) else {}
-
- def add_values(key: str, target: str, limit: int = 8) -> None:
- value = llm_profile.get(key) if isinstance(llm_profile, dict) else None
- values: list[str] = []
- if isinstance(value, list):
- values = [_single_line(item, 80) for item in value[:limit] if _single_line(item, 80)]
- else:
- text = _single_line(value, 160)
- if text:
- values = [text]
- profile[target].extend(values)
-
- add_values("interests", "positive", 10)
- add_values("weak_preferences", "positive", 10)
- add_values("strong_memories", "positive", 5)
- add_values("boundaries", "negative", 10)
- action_prefs = user.get("action_preferences") if isinstance(user, dict) else {}
- if isinstance(action_prefs, dict):
- for key, value in action_prefs.items():
- text = _single_line(value if isinstance(value, str) else key, 80)
- if text:
- profile["positive"].append(text)
- context_parts = []
- formatter = getattr(self, "_format_companion_memory_for_prompt", None)
- if callable(formatter):
- try:
- context_parts.append(_single_line(formatter(user), 900))
- except Exception:
- pass
- for key in ("last_user_message", "last_companion_message", "proactive_boundary_note"):
- text = _single_line(user.get(key), 180) if isinstance(user, dict) else ""
- if text:
- context_parts.append(text)
- profile["positive"] = list(dict.fromkeys(item for item in profile["positive"] if item))[:24]
- profile["negative"] = list(dict.fromkeys(item for item in profile["negative"] if item))[:16]
- profile["context"] = _single_line(";".join(part for part in context_parts if part), 1200)
- return profile
-
- @staticmethod
- def _external_event_text_match_score(text: str, clues: list[str], *, negative: bool = False) -> tuple[int, list[str]]:
- haystack = str(text or "").lower()
- score = 0
- hits: list[str] = []
- for clue in clues:
- clue_text = _single_line(clue, 80)
- if not clue_text:
- continue
- tokens = re.findall(r"[\u4e00-\u9fff]{2,8}|[a-z0-9_]{3,24}", clue_text.lower())
- matched = 0
- for token in tokens[:6]:
- if token and token in haystack:
- matched += 1
- if matched:
- hits.append(clue_text)
- score += min(5 if negative else 4, matched * (3 if negative else 2))
- return min(20 if negative else 18, score), hits[:5]
-
- def _external_event_user_preference_decision(self, user: dict[str, Any], payload: dict[str, Any]) -> dict[str, Any]:
- profile = self._external_event_user_preference_profile(user)
- payload_text = self._external_event_payload_text(payload).lower()
- positive_score, positive_hits = self._external_event_text_match_score(payload_text, profile.get("positive", []))
- negative_score, negative_hits = self._external_event_text_match_score(payload_text, profile.get("negative", []), negative=True)
- context_score, context_hits = self._external_event_text_match_score(payload_text, [profile.get("context", "")])
- score = max(0, min(30, positive_score + min(8, context_score) - negative_score))
- return {
- "score": score,
- "positive_hits": positive_hits,
- "negative_hits": negative_hits,
- "context_hits": context_hits,
- "blocked": bool(negative_score >= 8 and positive_score <= 2),
- }
-
- def _external_event_payload_from_news_item(self, item: dict[str, Any], *, base_digest: dict[str, Any] | None = None) -> dict[str, Any]:
- title = _single_line(item.get("title"), 100)
- summary = _single_line(item.get("summary") or item.get("snippet") or item.get("video_context_text"), 240)
- source = _single_line(item.get("source"), 40)
- payload = {
- "topic": title or _single_line((base_digest or {}).get("topic"), 40) or "新闻",
- "headline": title or _single_line((base_digest or {}).get("headline"), 100),
- "impression": summary or _single_line((base_digest or {}).get("impression"), 240),
- "selected_key": _single_line(item.get("key"), 32),
- "selected_link": _single_line(item.get("link") or item.get("video_link"), 400),
- "selected_source": source,
- "items": (base_digest or {}).get("items") if isinstance((base_digest or {}).get("items"), list) else [],
- "created_ts": _safe_float((base_digest or {}).get("created_ts"), 0) or _now_ts(),
- }
- for key in ("published_ts", "score", "video_context_text", "video_link", "article_readable", "video_subtitle_readable"):
- if key in item:
- payload[key] = item.get(key)
- return payload
-
- def _select_external_event_for_user(
- self,
- user: dict[str, Any],
- candidates: list[dict[str, Any]],
- *,
- source_type: str,
- base_payload: dict[str, Any] | None = None,
- now: float | None = None,
- ) -> dict[str, Any]:
- now = _now_ts() if now is None else now
- best: dict[str, Any] = {}
- best_score = -10**9
- for raw in candidates[:12]:
- if not isinstance(raw, dict):
- continue
- payload = self._external_event_payload_from_news_item(raw, base_digest=base_payload) if source_type == "news" else dict(raw)
- if base_payload and source_type != "news":
- payload.setdefault("created_ts", base_payload.get("created_ts"))
- pref = self._external_event_user_preference_decision(user, payload)
- if pref.get("blocked"):
- continue
- quality = self._external_event_quality_score(payload)
- user_match = self._external_event_user_interest_score(user, payload)
- duplicate_penalty = 12 if self._external_event_recently_seen(payload, source_type=source_type, now=now) else 0
- total = quality * 2 + user_match * 3 + _safe_int(pref.get("score"), 0) - duplicate_penalty
- if total > best_score:
- best_score = total
- best = {
- "payload": payload,
- "preference": pref,
- "selection_score": total,
- }
- return best
-
- def _external_event_user_interest_score(self, user: dict[str, Any], payload: dict[str, Any]) -> int:
- memory_text = ""
- formatter = getattr(self, "_format_companion_memory_for_prompt", None)
- if callable(formatter):
- try:
- memory_text = _single_line(formatter(user), 700).lower()
- except Exception:
- memory_text = ""
- haystack = self._external_event_payload_text(payload).lower()
- if not memory_text or not haystack:
- return 0
- score = 0
- for token in re.findall(r"[\u4e00-\u9fff]{2,8}|[a-z0-9_]{3,24}", haystack):
- if token and token in memory_text:
- score += 1
- return min(10, score)
-
- def _external_event_quality_score(self, payload: dict[str, Any]) -> int:
- score = 0
- if _single_line(payload.get("headline") or payload.get("topic") or payload.get("title"), 120):
- score += 2
- impression = _single_line(payload.get("impression") or payload.get("summary") or payload.get("note"), 320)
- if len(impression) >= 36:
- score += 2
- if _single_line(payload.get("selected_link") or payload.get("source_url") or payload.get("link"), 220):
- score += 1
- if _safe_float(payload.get("published_ts"), 0) > 0:
- score += 1
- if _safe_int(payload.get("score"), 0, 0, 10) >= max(1, _safe_int(getattr(self, "bilibili_share_min_score", 7), 7, 0, 10)):
- score += 2
- return min(10, score)
-
- def _external_event_share_decision(
- self,
- user: dict[str, Any],
- payload: dict[str, Any],
- *,
- source_type: str,
- wish: dict[str, Any] | None = None,
- base_probability: float = 0.2,
- now: float | None = None,
- ) -> dict[str, Any]:
- now = _now_ts() if now is None else now
- relevance = _safe_int((wish or {}).get("relevance"), 0, 0, 10)
- desire = _safe_int((wish or {}).get("desire"), 0, 0, 10)
- user_match = self._external_event_user_interest_score(user, payload)
- quality = self._external_event_quality_score(payload)
- freshness = 6
- published_ts = _safe_float(payload.get("published_ts"), 0)
- if published_ts > 0:
- age_hours = max(0.0, (now - published_ts) / 3600.0)
- if age_hours <= 6:
- freshness = 10
- elif age_hours <= 24:
- freshness = 8
- elif age_hours <= 72:
- freshness = 5
- else:
- freshness = 2
- noisy = self._external_event_recently_seen(payload, source_type=source_type, now=now)
- duplicate_penalty = 4 if noisy else 0
- interrupt_penalty = 0
- if now - _safe_float(user.get("last_seen"), 0) < max(self.idle_minutes, 90) * 60:
- interrupt_penalty += 3
- if now - _safe_float(user.get("last_sent"), 0) < max(self.min_interval_minutes, 120) * 60:
- interrupt_penalty += 2
- total = relevance * 2 + desire * 2 + user_match * 2 + quality + freshness - duplicate_penalty - interrupt_penalty
- normalized = max(0.0, min(1.0, base_probability + total / 100.0))
- return {
- "score": max(0, min(100, total * 2)),
- "probability": normalized,
- "user_match": user_match,
- "quality": quality,
- "freshness": freshness,
- "duplicate_penalty": duplicate_penalty,
- "interrupt_penalty": interrupt_penalty,
- "should_share": bool((wish or {}).get("should_share")) and total >= 18 and not noisy,
- "duplicate": noisy,
- }
-
- def _external_link_share_cooldown_remaining(
- self,
- user: dict[str, Any],
- *,
- now: float | None = None,
- ) -> float:
- """Return the shared cooldown remaining for plugin-initiated link shares.
-
- Older versions recorded only per-source candidate timestamps. Include
- those fields so upgrading immediately stops Bilibili/news/web shares
- from alternating around their separate short cooldowns.
- """
- if not isinstance(user, dict):
- return 0.0
- cooldown_hours = max(
- 0.0,
- _safe_float(getattr(self, "external_link_share_cooldown_hours", 72), 72.0),
- )
- if cooldown_hours <= 0:
- return 0.0
- now = _now_ts() if now is None else now
- last_share_at = max(
- (
- _safe_float(user.get(field), 0.0)
- for field in (
- "last_external_link_share_at",
- "last_external_link_candidate_at",
- "last_bilibili_share_at",
- "last_news_share_at",
- "last_web_exploration_share_at",
- "last_external_event_self_link_at",
- )
- ),
- default=0.0,
- )
- if last_share_at <= 0:
- return 0.0
- return max(0.0, last_share_at + cooldown_hours * 3600.0 - now)
-
- @staticmethod
- def _note_external_link_candidate(user: dict[str, Any], *, now: float) -> None:
- if isinstance(user, dict):
- user["last_external_link_candidate_at"] = now
-
- def _bilibili_plugin_dir(self) -> Path:
- candidates = self._bilibili_ai_bot_plugin_dirs()
- for path in candidates:
- if self._is_bilibili_ai_bot_dir(path):
- return path
- return Path(self.data_dir).parent.parent / "plugins" / BILIBILI_AI_BOT_PLUGIN_NAME
-
- def _bilibili_plugin_roots(self) -> list[Path]:
- return [
- Path(__file__).resolve().parent.parent,
- Path(self.data_dir).parent.parent / "plugins",
- ]
-
- def _is_bilibili_ai_bot_dir(self, path: Path) -> bool:
- if not (path / "main.py").exists():
- return False
- if path.name == BILIBILI_AI_BOT_PLUGIN_NAME:
- return True
- meta = path / "metadata.yaml"
- if not meta.exists():
- return False
- try:
- text = meta.read_text(encoding="utf-8", errors="ignore")
- except Exception:
- return False
- return bool(
- re.search(r"(?m)^name:\s*astrbot_plugin_bilibili_ai_bot\b", text)
- or "github.com/chenluQwQ/astrbot_plugin_bilibili_ai_bot" in text
- )
-
- def _bilibili_ai_bot_plugin_dirs(self) -> list[Path]:
- # Startup-safe: do not glob all bilibili-like plugin folders here.
- # A broad scan can interact badly with AstrBot's plugin loading phase.
- found: list[Path] = []
- seen: set[str] = set()
- for root in self._bilibili_plugin_roots():
- for path in (root / BILIBILI_AI_BOT_PLUGIN_NAME,):
- key = str(path)
- if key in seen:
- continue
- seen.add(key)
- if self._is_bilibili_ai_bot_dir(path):
- found.append(path)
- return found
-
- def _bilibili_ai_bot_package_names(self) -> list[str]:
- now = _now_ts()
- cache = getattr(self, "_bilibili_ai_bot_package_names_cache", None)
- if isinstance(cache, dict) and now - _safe_float(cache.get("ts"), 0) < 60:
- names = cache.get("names")
- if isinstance(names, list):
- return [str(name) for name in names if str(name or "").strip()]
- names = [BILIBILI_AI_BOT_PLUGIN_NAME]
- for path in self._bilibili_ai_bot_plugin_dirs():
- if path.name not in names:
- names.append(path.name)
- try:
- self._bilibili_ai_bot_package_names_cache = {"ts": now, "names": list(names)}
- except Exception:
- pass
- return names
-
- def _bilibili_ai_bot_data_dirs(self) -> list[Path]:
- candidates: list[Path] = []
- plugin_data_root = Path(self.data_dir).parent.parent / "plugin_data"
- for plugin_name in BILIBILI_AI_BOT_LEGACY_DATA_NAMES:
- candidates.append(plugin_data_root / plugin_name)
- deduped: list[Path] = []
- seen: set[str] = set()
- for path in candidates:
- key = str(path)
- if key not in seen:
- seen.add(key)
- deduped.append(path)
- return deduped
-
- def _bilibili_watch_log_file(self) -> Path:
- data_candidates = [path / "watch_log.json" for path in self._bilibili_ai_bot_data_dirs()]
- for path in data_candidates:
- if path.exists():
- return path
- return data_candidates[0] if data_candidates else self._bilibili_plugin_dir() / "watch_log.json"
-
- def _bilibili_available(self) -> bool:
- now = _now_ts()
- cache = getattr(self, "_bilibili_available_cache", None)
- if isinstance(cache, dict) and now - _safe_float(cache.get("ts"), 0) < 30:
- return bool(cache.get("available"))
- try:
- available = bool(self._bilibili_ai_bot_plugin_dirs()) or self._bilibili_watch_log_file().exists()
- except Exception:
- available = False
- try:
- self._bilibili_available_cache = {"ts": now, "available": bool(available)}
- except Exception:
- pass
- return bool(available)
-
- def _find_bilibili_bot_instance(self) -> Any | None:
- now = _now_ts()
- cache = getattr(self, "_bilibili_bot_instance_cache", None)
- if isinstance(cache, dict) and now - _safe_float(cache.get("ts"), 0) < 30:
- return cache.get("instance")
- names = tuple(self._bilibili_ai_bot_package_names())
- found = None
- try:
- getter = getattr(getattr(self, "context", None), "get_registered_star", None)
- if callable(getter):
- for name in names:
- obj = getter(name)
- if obj is not None and (
- callable(getattr(obj, "_run_proactive", None)) or hasattr(obj, "memory_api")
- ):
- found = obj
- break
- except Exception:
- pass
- if found is None and names:
- for obj in gc.get_objects():
- try:
- cls = obj.__class__
- module = str(getattr(cls, "__module__", ""))
- if not any(name in module for name in names):
- continue
- if (callable(getattr(obj, "_run_proactive", None)) and hasattr(obj, "_proactive_task")) or hasattr(obj, "memory_api"):
- found = obj
- break
- except Exception:
- continue
- try:
- self._bilibili_bot_instance_cache = {"ts": now, "instance": found}
- except Exception:
- pass
- return found
-
- def _find_bilibili_memory_api(self) -> Any | None:
- now = _now_ts()
- cache = getattr(self, "_bilibili_memory_api_object_cache", None)
- if isinstance(cache, dict) and now - _safe_float(cache.get("ts"), 0) < 30:
- return cache.get("api")
- bili = self._find_bilibili_bot_instance()
- api = getattr(bili, "memory_api", None) if bili is not None else None
- if api is not None and callable(getattr(api, "get_recent_memories", None)):
- try:
- self._bilibili_memory_api_object_cache = {"ts": now, "api": api}
- except Exception:
- pass
- return api
- names = tuple(self._bilibili_ai_bot_package_names())
- for obj in gc.get_objects():
- try:
- cls = obj.__class__
- module = str(getattr(cls, "__module__", ""))
- if not any(name in module for name in names):
- continue
- api = getattr(obj, "memory_api", None)
- if api is not None and callable(getattr(api, "get_recent_memories", None)):
- try:
- self._bilibili_memory_api_object_cache = {"ts": now, "api": api}
- except Exception:
- pass
- return api
- except Exception:
- continue
- try:
- self._bilibili_memory_api_object_cache = {"ts": now, "api": None}
- except Exception:
- pass
- return None
-
- def _bilibili_memory_api_available(self, *, allow_probe: bool = True, ttl_seconds: int = 60) -> bool:
- now = _now_ts()
- cache = getattr(self, "_bilibili_memory_api_cache", None)
- if isinstance(cache, dict) and now - _safe_float(cache.get("ts"), 0) < max(5, ttl_seconds):
- return bool(cache.get("available"))
- if not allow_probe:
- return False
- available = self._find_bilibili_memory_api() is not None
- try:
- self._bilibili_memory_api_cache = {"ts": now, "available": bool(available)}
- except Exception:
- pass
- return bool(available)
-
- def _find_bilibili_runtime_objects(self) -> list[Any]:
- now = _now_ts()
- cache = getattr(self, "_bilibili_runtime_objects_cache", None)
- if isinstance(cache, dict) and now - _safe_float(cache.get("ts"), 0) < 30:
- objects = cache.get("objects")
- if isinstance(objects, list):
- return list(objects)
- names = tuple(self._bilibili_ai_bot_package_names())
- found: list[Any] = []
- seen: set[int] = set()
- if names:
- for obj in gc.get_objects():
- try:
- cls = obj.__class__
- module = str(getattr(cls, "__module__", ""))
- if not any(name in module for name in names):
- continue
- if id(obj) in seen:
- continue
- if (
- callable(getattr(obj, "get_video_info", None))
- or callable(getattr(getattr(obj, "bili_client", None), "get_video_info", None))
- or callable(getattr(obj, "_http_get", None))
- ):
- seen.add(id(obj))
- found.append(obj)
- except Exception:
- continue
- try:
- self._bilibili_runtime_objects_cache = {"ts": now, "objects": list(found)}
- except Exception:
- pass
- return found
-
- def _load_bilibili_watch_log(self) -> list[dict[str, Any]]:
- try:
- path = self._bilibili_watch_log_file()
- if not path.exists():
- return []
- with path.open("r", encoding="utf-8") as f:
- raw = json.load(f)
- if isinstance(raw, list):
- return [item for item in raw if isinstance(item, dict)]
- except Exception as e:
- logger.debug(f"[PrivateCompanion] 读取 B 站观看日志失败: {e}")
- return []
-
- def _load_bilibili_recent_video_memories(self, *, hours: int = 72, limit: int = 12) -> list[dict[str, Any]]:
- api = self._find_bilibili_memory_api()
- if api is None:
- return []
- try:
- memories = api.get_recent_memories(
- source="bilibili",
- memory_types={"video"},
- hours=hours,
- limit=limit,
- )
- if isinstance(memories, list):
- return [item for item in memories if isinstance(item, dict)]
- except Exception as e:
- logger.debug(f"[PrivateCompanion] 读取 BiliBot 视频记忆失败: {e}")
- return []
-
- def _bilibili_memory_bvid(self, item: dict[str, Any]) -> str:
- bvid = self._clean_bilibili_share_field(item.get("bvid") or item.get("video_bvid"), 40)
- if bvid:
- return bvid
- text = str(item.get("text") or "")
- checker = getattr(self, "_looks_like_internal_provider_error_text", None)
- if callable(checker) and checker(text):
- return ""
- match = re.search(r"\bBV[0-9A-Za-z]{8,16}\b", text)
- return _single_line(match.group(0), 40) if match else ""
-
- def _bilibili_memory_title(self, item: dict[str, Any]) -> str:
- title = self._clean_bilibili_share_field(item.get("video_title") or item.get("title"), 80)
- if title:
- return title
- text = str(item.get("text") or "")
- checker = getattr(self, "_looks_like_internal_provider_error_text", None)
- if callable(checker) and checker(text):
- return ""
- match = re.search(r"《([^》]{1,80})》", text)
- return self._clean_bilibili_share_field(match.group(1), 80) if match else ""
-
- def _bilibili_memory_context_for_bvid(self, bvid: str, *, limit: int = 3) -> list[str]:
- safe_bvid = _single_line(bvid, 40)
- if not safe_bvid:
- return []
- contexts: list[str] = []
- for item in self._load_bilibili_recent_video_memories(limit=18):
- if self._bilibili_memory_bvid(item) != safe_bvid:
- continue
- text = self._clean_bilibili_share_field(item.get("text"), 180)
- if text and text not in contexts:
- contexts.append(text)
- if len(contexts) >= limit:
- break
- return contexts
-
- def _bilibili_video_candidate_from_memory(self) -> dict[str, Any] | None:
- candidates = self._bilibili_video_candidates_from_memory(limit=1)
- return candidates[0] if candidates else None
-
- def _bilibili_video_candidates_from_memory(self, *, limit: int = 6) -> list[dict[str, Any]]:
- candidates: list[dict[str, Any]] = []
- for item in self._load_bilibili_recent_video_memories(limit=max(1, limit * 2)):
- bvid = self._bilibili_memory_bvid(item)
- title = self._bilibili_memory_title(item)
- if not bvid or not title:
- continue
- text = self._clean_bilibili_share_field(item.get("text"), 220)
- candidates.append({
- "key": f"{bvid}:{_single_line(item.get('time'), 20)}:memory",
- "bvid": bvid,
- "title": title,
- "up_name": "",
- "score": self.bilibili_share_min_score,
- "mood": "",
- "comment": text,
- "review": text,
- "pic": "",
- "time": _single_line(item.get("time"), 24),
- "actions": [],
- "source": "memory_api",
- "memory_context": [text] if text else [],
- })
- if len(candidates) >= limit:
- break
- return candidates
-
- def _latest_bilibili_video_candidates(self, *, include_memory_api: bool = True, limit: int = 8) -> list[dict[str, Any]]:
- candidates: list[dict[str, Any]] = []
- seen: set[str] = set()
- logs = self._load_bilibili_watch_log()
- if logs:
- for item in reversed(logs[-40:]):
- bvid = self._clean_bilibili_share_field(item.get("bvid"), 32)
- title = self._clean_bilibili_share_field(item.get("title"), 80)
- if not bvid or not title:
- continue
- score = _safe_int(item.get("score"), 0, 0, 10)
- if score < self.bilibili_share_min_score:
- continue
- key = f"{bvid}:{_single_line(item.get('time'), 20)}"
- if key in seen:
- continue
- seen.add(key)
- comment = self._clean_bilibili_share_field(item.get("comment"), 120)
- review = self._clean_bilibili_share_field(item.get("review"), 180)
- candidates.append({
- "key": key,
- "bvid": bvid,
- "title": title,
- "up_name": self._clean_bilibili_share_field(item.get("up_name"), 40),
- "score": score,
- "mood": self._clean_bilibili_share_field(item.get("mood"), 24),
- "comment": comment,
- "review": review,
- "pic": _single_line(item.get("pic"), 240),
- "time": _single_line(item.get("time"), 24),
- "actions": list(item.get("actions") or []) if isinstance(item.get("actions"), list) else [],
- "source": "watch_log",
- "memory_context": self._bilibili_memory_context_for_bvid(bvid) if include_memory_api else [],
- })
- if len(candidates) >= limit:
- break
- if include_memory_api and len(candidates) < limit:
- for item in self._bilibili_video_candidates_from_memory(limit=limit - len(candidates)):
- key = str(item.get("key") or item.get("bvid") or "")
- if key and key not in seen:
- seen.add(key)
- candidates.append(item)
- return candidates[:limit]
-
- def _latest_bilibili_video_candidate(self, *, include_memory_api: bool = True) -> dict[str, Any] | None:
- candidates = self._latest_bilibili_video_candidates(include_memory_api=include_memory_api, limit=1)
- return candidates[0] if candidates else None
-
- def _record_bilibili_share_to_memory(self, user_id: str, candidate: dict[str, Any]) -> None:
- api = self._find_bilibili_memory_api()
- if api is None or not callable(getattr(api, "record", None)):
- return
- bvid = self._clean_bilibili_share_field(candidate.get("bvid"), 40)
- title = self._clean_bilibili_share_field(candidate.get("title"), 80)
- if not bvid or not title:
- return
- async def _record() -> None:
- try:
- await api.record(
- f"陪伴插件准备把视频《{title}》轻轻分享给 QQ 用户 {user_id},链接 {bvid}",
- user_id=str(user_id),
- username="PrivateCompanion",
- source="private_companion",
- memory_type="video",
- level="today",
- importance=4,
- extra={"bvid": bvid, "video_title": title},
- )
- except Exception as e:
- logger.debug(f"[PrivateCompanion] 写入 BiliBot 分享记忆失败: {e}")
- try:
- asyncio.create_task(_record())
- except RuntimeError:
- pass
-
-
- def _bot_currently_bored_enough_for_bilibili(self) -> bool:
- now_dt = datetime.now()
- if now_dt.hour < 10 or now_dt.hour >= 23:
- return False
- state = self.data.get("daily_state", {})
- energy = _safe_int(state.get("energy") if isinstance(state, dict) else 70, 70, 0, 100)
- mood = _single_line(state.get("mood_bias") if isinstance(state, dict) else "", 24)
- current_item = self._get_current_plan_item(self.data.get("daily_plan", {}))
- activity = _single_line((current_item or {}).get("activity"), 80)
- text = f"{mood} {activity}"
- boredom_tokens = ("无聊", "发呆", "摸鱼", "刷视频", "短视频", "休息", "闲", "空")
- if any(token in text for token in boredom_tokens):
- return True
- return 35 <= energy <= 72 and random.random() < 0.34
-
- async def _maybe_trigger_bilibili_boredom_watch(self) -> None:
- if not (self.enable_bilibili_integration and self.enable_bilibili_boredom_watch):
- return
- if not self._bilibili_available() or not self._bot_currently_bored_enough_for_bilibili():
- return
- state = self.data.setdefault("bilibili_integration", {})
- if not isinstance(state, dict):
- self.data["bilibili_integration"] = {}
- state = self.data["bilibili_integration"]
- now = _now_ts()
- min_interval = max(2, self.bilibili_boredom_min_interval_hours) * 3600
- if now - _safe_float(state.get("last_boredom_watch_at"), 0) < min_interval:
- return
- if now - _safe_float(state.get("last_boredom_watch_probe_at"), 0) < 30 * 60:
- return
- if random.random() > 0.38:
- return
- bili = self._find_bilibili_bot_instance()
- if bili is None:
- state["last_boredom_watch_probe_at"] = now
- self._save_data_sync()
- return
- task = getattr(bili, "_proactive_task", None)
- if task is not None and not task.done():
- return
- try:
- bili._proactive_task = asyncio.create_task(bili._run_proactive(max_watch=1))
- state["last_boredom_watch_at"] = now
- state["last_boredom_watch_status"] = "triggered"
- self._save_data_sync()
- logger.info("[PrivateCompanion] 已触发 B站 AI Bot 无聊刷视频联动")
- except Exception as e:
- state["last_boredom_watch_status"] = f"failed:{_single_line(str(e), 80)}"
- self._save_data_sync()
- logger.debug(f"[PrivateCompanion] 触发 B站 AI Bot 刷视频失败: {e}")
-
- def _maybe_schedule_bilibili_video_share(self) -> bool:
- if not self.enable_bilibili_integration:
- return False
- include_memory_api = bool(self._bilibili_memory_api_available(allow_probe=False))
- candidates = self._latest_bilibili_video_candidates(include_memory_api=include_memory_api, limit=8)
- if not candidates:
- return False
- users = self.data.get("users")
- if not isinstance(users, dict):
- return False
- now = _now_ts()
- changed = False
- for user_id, user in users.items():
- if not isinstance(user, dict) or not self._is_target_private_user(str(user_id), user) or not user.get("enabled", True) or not user.get("umo"):
- continue
- if now - _safe_float(user.get("last_seen"), 0) < max(self.idle_minutes, 90) * 60:
- continue
- if now - _safe_float(user.get("last_bilibili_share_at"), 0) < 10 * 3600:
- continue
- if self._external_link_share_cooldown_remaining(user, now=now) > 0:
- continue
- timer_event = self._get_active_llm_timer(user)
- if (
- _safe_float(user.get("next_proactive_at"), 0) > 0
- and str(user.get("planned_proactive_source") or "") == "timer"
- and self._llm_timer_can_use_internal_scheduler(timer_event if isinstance(timer_event, dict) else None)
- ):
- continue
- selection = self._select_external_event_for_user(user, candidates, source_type="bilibili", now=now)
- candidate = selection.get("payload") if isinstance(selection, dict) else None
- if not isinstance(candidate, dict):
- continue
- key = str(candidate.get("key") or candidate.get("bvid") or "")
- if key and str(user.get("last_bilibili_share_key") or "") == key:
- continue
- score = _safe_int(candidate.get("score"), 0, 0, 10)
- decision = self._external_event_share_decision(
- user,
- candidate,
- source_type="bilibili",
- wish={
- "relevance": score,
- "desire": max(score - 1, 0),
- "should_share": score >= self.bilibili_share_min_score,
- },
- base_probability=self.bilibili_share_probability,
- now=now,
- )
- if not decision.get("should_share"):
- continue
- chance = min(0.9, max(self.bilibili_share_probability, _safe_float(decision.get("probability"), self.bilibili_share_probability)))
- preference = selection.get("preference") if isinstance(selection.get("preference"), dict) else {}
- if _safe_int(preference.get("score"), 0) >= 8:
- chance = min(0.95, chance + 0.12)
- if random.random() > chance:
- continue
- delay_minutes = random.randint(12, 70)
- scheduled = now + delay_minutes * 60
- title = _single_line(candidate.get("title"), 70) or "视频"
- accepted = self._offer_proactive_candidate(
- str(user_id),
- user,
- {
- "source": "bilibili",
- "reason": "bili_video_share",
- "action": "message",
- "scheduled_ts": scheduled,
- "topic": title,
- "score": max(score, _safe_int(decision.get("score"), score, 0, 100)),
- "motive": "这条视频和对方兴趣相关",
- "context_key": "bilibili_video_context",
- "context": {**candidate, "created_ts": now, "share_decision": decision, "preference_match": preference},
- },
- )
- if not accepted:
- continue
- self._record_bilibili_share_to_memory(str(user_id), candidate)
- user["last_bilibili_share_key"] = key
- user["last_bilibili_share_at"] = now
- self._note_external_link_candidate(user, now=now)
- self._remember_external_event(candidate, source_type="bilibili", reason="bili_video_share")
- changed = True
- return changed
-
- def _news_source_items(self) -> list[dict[str, str]]:
- raw = str(getattr(self, "news_sources", "") or "")
- items: list[dict[str, str]] = []
- seen: set[str] = set()
- for line in self._split_news_source_lines(raw):
- line = line.strip()
- if not line or line.startswith("#"):
- continue
- if "|" in line:
- name, url = line.split("|", 1)
- else:
- name, url = "", line
- url = url.strip()
- source_type = "rss"
- mid = ""
- bvid = ""
- if url.lower().startswith("bilibili:"):
- mid = re.sub(r"\D+", "", url.split(":", 1)[1])
- source_type = "bilibili"
- elif url.lower().startswith("bvid:"):
- match = re.search(r"(BV[0-9A-Za-z]+)", url, flags=re.I)
- bvid = match.group(1) if match else ""
- source_type = "bilibili_video"
- elif re.fullmatch(r"\d{4,}", url):
- mid = url
- source_type = "bilibili"
- elif url.startswith(("http://", "https://")):
- parsed = urlparse(url)
- if parsed.netloc.endswith("bilibili.com") and parsed.path.startswith("/video/"):
- match = re.search(r"/video/(BV[0-9A-Za-z]+)", parsed.path, flags=re.I)
- if match:
- bvid = match.group(1)
- source_type = "bilibili_video"
- if "space.bilibili.com" in parsed.netloc or parsed.path.startswith("/space.bilibili.com"):
- match = re.search(r"/(\d+)", parsed.path)
- if match:
- mid = match.group(1)
- source_type = "bilibili"
- if source_type == "bilibili_video":
- if not bvid:
- continue
- key = f"bilibili_video:{bvid}"
- if key in seen:
- continue
- seen.add(key)
- items.append(
- {
- "name": _single_line(name, 40) or f"B站视频 {bvid}",
- "url": f"https://www.bilibili.com/video/{bvid}",
- "type": "bilibili_video",
- "bvid": bvid,
- }
- )
- if len(items) >= 12:
- break
- continue
- if source_type == "bilibili":
- if not mid:
- continue
- key = f"bilibili:{mid}"
- if key in seen:
- continue
- seen.add(key)
- items.append(
- {
- "name": _single_line(name, 40) or f"B站 UP {mid}",
- "url": f"https://space.bilibili.com/{mid}",
- "type": "bilibili",
- "mid": mid,
- }
- )
- if len(items) >= 12:
- break
- continue
- if not url.startswith(("http://", "https://")) or url in seen:
- continue
- seen.add(url)
- items.append({"name": _single_line(name, 40) or _single_line(url, 40), "url": url, "type": "rss"})
- if len(items) >= 12:
- break
- return items
-
- @staticmethod
- def _split_news_source_lines(raw: str) -> list[str]:
- text = str(raw or "").strip()
- if not text:
- return []
- lines = [line.strip() for line in text.splitlines() if line.strip()]
- if len(lines) != 1:
- return lines
- line = lines[0]
- markers = list(re.finditer(r"(?:^|\s+)(#?\s*[^|\n]+?)\|(?=(?:https?://|bilibili:|bvid:))", line, flags=re.I))
- if len(markers) <= 1:
- return lines
- recovered: list[str] = []
- for index, match in enumerate(markers):
- start = match.end()
- end = markers[index + 1].start() if index + 1 < len(markers) else len(line)
- name = str(match.group(1) or "").strip()
- target = line[start:end].strip()
- if name and target:
- recovered.append(f"{name}|{target}")
- return recovered or lines
-
- @staticmethod
- def _news_xml_text(node: Any, *paths: str) -> str:
- if node is None:
- return ""
- for path in paths:
- found = node.find(path)
- if found is not None and found.text:
- text = re.sub(r"<[^>]+>", "", html.unescape(str(found.text)))
- text = re.sub(r"\s+", " ", text).strip()
- if text:
- return text
- return ""
-
- @staticmethod
- def _news_parse_time(value: str) -> float:
- text = str(value or "").strip()
- if not text:
- return 0.0
- try:
- return parsedate_to_datetime(text).timestamp()
- except Exception:
- pass
- try:
- return datetime.fromisoformat(text.replace("Z", "+00:00")).timestamp()
- except Exception:
- return 0.0
-
- def _news_item_key(self, item: dict[str, Any]) -> str:
- raw = "|".join(
- _single_line(item.get(key), 240)
- for key in ("link", "title", "source")
- if _single_line(item.get(key), 240)
- )
- return hashlib.sha1(raw.encode("utf-8", errors="ignore")).hexdigest()[:16] if raw else ""
-
- @staticmethod
- def _bilibili_bvid_from_url(value: Any) -> str:
- text = str(value or "")
- match = re.search(r"(BV[0-9A-Za-z]+)", text)
- return match.group(1) if match else ""
-
- @staticmethod
- def _ai_daily_time_minutes(value: Any) -> int | None:
- text = str(value or "").strip().replace(":", ":")
- match = re.fullmatch(r"(\d{1,2}):(\d{2})", text)
- if not match:
- return None
- hour, minute = [int(part) for part in match.groups()]
- if not 0 <= minute <= 59:
- return None
- return (hour % 24) * 60 + minute
-
- def _ai_daily_source_key(self, source: dict[str, Any]) -> str:
- mid = re.sub(r"\D+", "", str(source.get("mid") or ""))
- if mid:
- return f"bilibili:{mid}"
- name = _single_line(source.get("name"), 40)
- return hashlib.sha1(name.encode("utf-8", errors="ignore")).hexdigest()[:12] if name else "unknown"
-
- def _ai_daily_source_items(self) -> list[dict[str, Any]]:
- raw = str(getattr(self, "ai_daily_sources", "") or "").strip() or DEFAULT_AI_DAILY_SOURCES
- items: list[dict[str, Any]] = []
- seen: set[str] = set()
- for line in raw.splitlines():
- line = line.strip()
- if not line or line.startswith("#"):
- continue
- parts = [part.strip() for part in line.split("|")]
- if len(parts) < 3:
- continue
- name = _single_line(parts[0], 40) or "AI日报"
- author = _single_line(parts[1], 60) or name
- mid = re.sub(r"\D+", "", parts[2])
- if not mid:
- continue
- keywords = [token for token in re.split(r"[\s,,、/|]+", parts[3] if len(parts) >= 4 else "") if token]
- if not keywords:
- keywords = ["日报"] if "日报" in name else ["早报"]
- schedule = _single_line(parts[4] if len(parts) >= 5 else "", 10) or ("23:00" if "日报" in name else "12:00")
- schedule_minutes = self._ai_daily_time_minutes(schedule)
- if schedule_minutes is None:
- schedule = "23:00" if "日报" in name else "12:00"
- schedule_minutes = self._ai_daily_time_minutes(schedule) or 0
- item = {
- "name": name,
- "author_name": author,
- "type": "bilibili",
- "mid": mid,
- "url": f"https://space.bilibili.com/{mid}",
- "keywords": keywords[:6],
- "schedule": schedule,
- "schedule_minutes": schedule_minutes,
- }
- key = self._ai_daily_source_key(item)
- if key in seen:
- continue
- seen.add(key)
- item["key"] = key
- items.append(item)
- if len(items) >= 8:
- break
- if items:
- return items
- legacy_mid = re.sub(r"\D+", "", str(getattr(self, "ai_daily_source_uid", "") or DEFAULT_AI_DAILY_JUYA_UID)) or DEFAULT_AI_DAILY_JUYA_UID
- return [
- {
- "name": "AI日报",
- "author_name": "橘鸦Juya",
- "type": "bilibili",
- "mid": legacy_mid,
- "url": f"https://space.bilibili.com/{legacy_mid}",
- "keywords": ["日报", "早报"],
- "schedule": "23:00",
- "schedule_minutes": 23 * 60,
- "key": f"bilibili:{legacy_mid}",
- }
- ]
-
- def _ai_daily_date_tokens(self, now_dt: datetime | None = None) -> list[str]:
- now_dt = now_dt or datetime.now()
- tokens = [
- now_dt.strftime("%Y-%m-%d"),
- now_dt.strftime("%Y/%m/%d"),
- now_dt.strftime("%Y年%m月%d日").replace("年0", "年").replace("月0", "月"),
- f"{now_dt.month}月{now_dt.day}日",
- f"{now_dt.month}.{now_dt.day}",
- f"{now_dt.month}-{now_dt.day}",
- f"{now_dt.month}/{now_dt.day}",
- f"{now_dt.month:02d}{now_dt.day:02d}",
- f"{now_dt.month}{now_dt.day:02d}",
- ]
- return list(dict.fromkeys(token for token in tokens if token))
-
- def _ai_daily_item_matches_source(self, item: dict[str, Any], source: dict[str, Any], today: str) -> bool:
- if not self._news_item_is_today(item, today):
- return False
- mid = re.sub(r"\D+", "", str(source.get("mid") or ""))
- owner_mid = re.sub(r"\D+", "", str(item.get("video_owner_mid") or ""))
- if mid and owner_mid and mid != owner_mid:
- return False
- if mid and owner_mid == mid:
- return True
- text = f"{item.get('title') or ''} {item.get('summary') or ''} {item.get('video_owner_name') or ''}"
- keywords = [str(token) for token in source.get("keywords") or [] if str(token).strip()]
- if keywords and not any(token in text for token in keywords):
- return False
- return True
-
- def _ai_daily_due_sources(self, now_dt: datetime, today: str, source_states: dict[str, Any], *, force: bool = False) -> list[dict[str, Any]]:
- now_minute = now_dt.hour * 60 + now_dt.minute
- due: list[dict[str, Any]] = []
- for source in self._ai_daily_source_items():
- key = str(source.get("key") or self._ai_daily_source_key(source))
- source["key"] = key
- state = source_states.get(key) if isinstance(source_states.get(key), dict) else {}
- if not force and state.get("last_success_date") == today:
- continue
- schedule_minutes = _safe_int(source.get("schedule_minutes"), 0, 0)
- if not force and now_minute < schedule_minutes:
- continue
- if not force and state.get("last_attempt_date") == today:
- continue
- due.append(source)
- due.sort(key=lambda item: _safe_int(item.get("schedule_minutes"), 0, 0))
- return due
-
- async def _fetch_bilibili_video_search_api_fallback(self, source: dict[str, str]) -> list[dict[str, Any]]:
- source_name = _single_line(source.get("name"), 40) or "B站 AI早报"
- mid = re.sub(r"\D+", "", str(source.get("mid") or ""))
- now_dt = datetime.now()
- today = now_dt.strftime("%Y-%m-%d")
- date_tokens = self._ai_daily_date_tokens(now_dt)
- author = _single_line(source.get("author_name"), 60) or source_name
- keywords = [str(token) for token in source.get("keywords") or [] if str(token).strip()] or ["早报", "日报"]
- queries = []
- for keyword in keywords[:4]:
- queries.extend(
- [
- f"{author} AI {keyword} {today}",
- f"{author} AI{keyword} {date_tokens[2]}",
- f"{author} AI{keyword}{date_tokens[-2]}",
- ]
- )
- queries = list(dict.fromkeys(queries))
- items: list[dict[str, Any]] = []
- seen: set[str] = set()
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=15)
- headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125 Safari/537.36",
- "Referer": "https://search.bilibili.com/",
- "Accept": "application/json, text/plain, */*",
- "Accept-Encoding": "gzip, deflate",
- }
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- for query in queries:
- if len(items) >= max(1, self.news_max_items_per_source):
- break
- url = f"https://api.bilibili.com/x/web-interface/search/all/v2?keyword={quote(query)}"
- try:
- async with session.get(url) as resp:
- if resp.status >= 400:
- continue
- payload = await resp.json(content_type=None)
- except Exception:
- continue
- if not isinstance(payload, dict) or int(payload.get("code") or 0) != 0:
- continue
- groups = (payload.get("data") or {}).get("result") if isinstance(payload.get("data"), dict) else []
- for group in groups if isinstance(groups, list) else []:
- if not isinstance(group, dict) or group.get("result_type") != "video":
- continue
- for raw in group.get("data") if isinstance(group.get("data"), list) else []:
- if not isinstance(raw, dict):
- continue
- if mid and str(raw.get("mid") or "") != mid:
- continue
- raw_title = re.sub(r"<[^>]+>", "", html.unescape(str(raw.get("title") or ""))).strip()
- desc = re.sub(r"<[^>]+>", "", html.unescape(str(raw.get("description") or ""))).strip()
- haystack = f"{raw_title} {desc}"
- if "AI" not in haystack.upper() and author not in haystack:
- continue
- if not mid and keywords and not any(token in haystack for token in keywords):
- continue
- pubdate = _safe_float(raw.get("pubdate"), 0)
- pubdate_is_today = False
- if pubdate > 0:
- try:
- pubdate_is_today = datetime.fromtimestamp(pubdate).strftime("%Y-%m-%d") == today
- except Exception:
- pubdate_is_today = False
- if not pubdate_is_today and not any(token in haystack for token in date_tokens):
- continue
- bvid = _single_line(raw.get("bvid") or self._bilibili_bvid_from_url(raw.get("arcurl")), 40)
- if not bvid or bvid in seen:
- continue
- seen.add(bvid)
- item = await self._bilibili_news_item_from_video(
- source_name=source_name,
- title=raw_title,
- desc=desc,
- bvid=bvid,
- created=raw.get("pubdate"),
- )
- if item:
- item["bilibili_integration_source"] = "search_api"
- items.append(item)
- if len(items) >= max(1, self.news_max_items_per_source):
- break
- if len(items) >= max(1, self.news_max_items_per_source):
- break
- except Exception as exc:
- logger.debug("[PrivateCompanion] B站搜索 API 兜底失败: %s", exc)
- items.sort(key=lambda item: (_safe_float(item.get("published_ts"), 0), _safe_float(item.get("fetched_ts"), 0)), reverse=True)
- return items[: max(1, self.news_max_items_per_source)]
-
- async def _fetch_bilibili_news_search_fallback(self, source: dict[str, str]) -> list[dict[str, Any]]:
- source_name = _single_line(source.get("name"), 40) or "B站 AI早报"
- mid = re.sub(r"\D+", "", str(source.get("mid") or ""))
- now_dt = datetime.now()
- today = now_dt.strftime("%Y-%m-%d")
- date_tokens = self._ai_daily_date_tokens(now_dt)
- author = _single_line(source.get("author_name"), 60) or source_name
- keywords = [str(token) for token in source.get("keywords") or [] if str(token).strip()] or ["早报", "日报"]
- queries: list[str] = []
- for keyword in keywords[:4]:
- compact_keyword = f"AI{keyword}"
- queries.extend(
- [
- f"AI {keyword} {today}",
- f"{compact_keyword} {today}",
- f"AI {keyword} {date_tokens[2]}",
- f"{compact_keyword} {date_tokens[2]}",
- f"site:mp.weixin.qq.com/s AI {keyword} {today}",
- f"site:mp.weixin.qq.com/s {compact_keyword} {today}",
- f"site:bilibili.com/video AI {keyword} {today}",
- f"site:bilibili.com/video {compact_keyword} {today}",
- ]
- )
- queries = list(dict.fromkeys(queries))
- api_items = await self._fetch_bilibili_video_search_api_fallback(source)
- if api_items:
- return api_items
- umo = self._pick_available_web_search_umo()
- if not umo and not self._astrbot_web_search_available():
- return []
- items: list[dict[str, Any]] = []
- seen_links: set[str] = set()
- for query in queries:
- if len(items) >= max(1, self.news_max_items_per_source):
- break
- results = await self._run_astrbot_web_search(query, umo=umo, topic="news")
- for result in results[: max(2, self.news_max_items_per_source)]:
- title = _single_line(result.get("title"), 160)
- link = _single_line(result.get("url"), 400)
- snippet = _single_line(result.get("snippet"), 360)
- haystack = f"{title} {snippet}"
- if not title or ("AI" not in haystack.upper() and author not in haystack):
- continue
- if not mid and keywords and not any(token in haystack for token in keywords):
- continue
- article_match = re.search(r"https?://mp\.weixin\.qq\.com/s/[^\s<>\]))\"']+", f"{link} {snippet}")
- article_link = _single_line(article_match.group(0), 400) if article_match else ""
- if "mp.weixin.qq.com/s/" in link:
- article_link = link
- if not article_link and "space.bilibili.com" in link:
- continue
- video_bvid = self._bilibili_bvid_from_url(link)
- if not article_link and video_bvid:
- item = await self._bilibili_news_item_from_video(
- source_name=source_name,
- title=title,
- desc=snippet,
- bvid=video_bvid,
- )
- if item:
- item["bilibili_integration_source"] = "web_search_video"
- if str(item.get("link") or "") not in seen_links:
- seen_links.add(str(item.get("link") or ""))
- items.append(item)
- if len(items) >= max(1, self.news_max_items_per_source):
- break
- continue
- final_link = article_link or link
- if final_link in seen_links:
- continue
- seen_links.add(final_link)
- article_payload = await self._fetch_news_article_excerpt(article_link) if article_link else {}
- article_text = str(article_payload.get("text") or "").strip()
- article_excerpt = str(article_payload.get("excerpt") or "").strip()
- article_title = _single_line(article_payload.get("title"), 120)
- summary = article_excerpt if article_excerpt else snippet
- media_type = "bilibili_search_article" if article_text else "bilibili_search_result"
- published_hint = today if any(token in haystack for token in date_tokens) else ""
- item = {
- "source": source_name,
- "title": article_title or title,
- "link": final_link,
- "summary": summary,
- "published": published_hint,
- "published_ts": 0,
- "fetched_ts": _now_ts(),
- "media_type": media_type,
- "search_query": query,
- "article_link": article_link,
- "article_title": article_title,
- "article_text": article_text,
- "article_excerpt": article_excerpt,
- "article_readable": bool(article_text),
- }
- item["key"] = self._news_item_key(item)
- if item["key"]:
- items.append(item)
- if len(items) >= max(1, self.news_max_items_per_source):
- break
- if items:
- items.sort(
- key=lambda item: (
- 1 if str(item.get("published") or "") == today else 0,
- 1 if item.get("article_readable") else 0,
- _safe_float(item.get("fetched_ts"), 0),
- ),
- reverse=True,
- )
- return items[: max(1, self.news_max_items_per_source)]
- query = queries[0]
- results = await self._run_astrbot_web_search(query, umo=umo, topic="news")
- for result in results[: max(1, self.news_max_items_per_source)]:
- title = _single_line(result.get("title"), 160)
- link = _single_line(result.get("url"), 400)
- snippet = _single_line(result.get("snippet"), 320)
- haystack = f"{title} {snippet}"
- if not title or ("AI" not in haystack.upper() and author not in haystack):
- continue
- if keywords and not any(token in haystack for token in keywords):
- continue
- item = {
- "source": source_name,
- "title": title,
- "link": link,
- "summary": snippet,
- "published": "",
- "published_ts": 0,
- "fetched_ts": _now_ts(),
- "media_type": "bilibili_search_result",
- "search_query": query,
- }
- item["key"] = self._news_item_key(item)
- if item["key"]:
- items.append(item)
- return items
-
- async def _fetch_news_article_excerpt(self, url: str) -> dict[str, str]:
- safe_url = _single_line(url, 500)
- if not safe_url.startswith(("http://", "https://")):
- return {}
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=15)
- headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125 Safari/537.36",
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
- "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
- "Referer": "https://mp.weixin.qq.com/",
- }
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- async with session.get(safe_url, allow_redirects=True) as resp:
- if resp.status >= 400:
- return {}
- raw_bytes = await resp.read()
- content_type = resp.headers.get("Content-Type", "")
- if _news_response_looks_binary(raw_bytes, content_type=content_type):
- logger.debug(
- "[PrivateCompanion] 新闻文字版跳过非文本响应 %s content-type=%s",
- _single_line(safe_url, 120),
- _single_line(content_type, 80),
- )
- return {}
- raw = _decode_news_response_text(
- raw_bytes,
- content_type=content_type,
- declared_charset=resp.charset or "",
- )
- if not raw.strip():
- return {}
- except Exception as exc:
- logger.debug("[PrivateCompanion] 新闻文字版抓取失败 %s: %s", _single_line(safe_url, 120), exc)
- return {}
-
- text = html.unescape(raw or "")
- title = ""
- title_match = re.search(r"]*>(.*?)", text, flags=re.I | re.S)
- if title_match:
- title = re.sub(r"\s+", " ", re.sub(r"<[^>]+>", "", title_match.group(1))).strip()
- for pattern in (
- r']+property=["\']og:title["\'][^>]+content=["\']([^"\']+)["\']',
- r']+name=["\']twitter:title["\'][^>]+content=["\']([^"\']+)["\']',
- ):
- match = re.search(pattern, text, flags=re.I | re.S)
- if match:
- title = match.group(1).strip()
- break
- if _text_looks_garbled(title):
- title = ""
-
- body = text
- article_match = re.search(r']+id=["\']js_content["\'][^>]*>(.*?)
\s*\s*', text, flags=re.I | re.S)
- if not article_match:
- article_match = re.search(r']*>(.*?)', text, flags=re.I | re.S)
- if article_match:
- body = article_match.group(1)
- body = re.sub(r"", " ", body, flags=re.I | re.S)
- body = re.sub(r"", " ", body, flags=re.I | re.S)
- body = re.sub(r"
|
|||", "\n", body, flags=re.I)
- body = re.sub(r"<[^>]+>", " ", body)
- body = html.unescape(body)
- body = re.sub(r"\u00a0", " ", body)
- lines = [re.sub(r"\s+", " ", line).strip() for line in body.splitlines()]
- lines = [
- line for line in lines
- if len(line) >= 8
- and not re.search(r"^(赞|在看|分享|微信扫一扫|继续滑动看下一个|向上滑动看下一个|广告)$", line)
- ]
- article_text = "\n".join(lines)
- article_text = re.sub(r"\n{3,}", "\n\n", article_text).strip()
- if len(article_text) < 80 or _text_looks_garbled(article_text[:600]):
- return {}
- return {
- "title": _single_line(title, 120),
- "text": article_text,
- "excerpt": article_text[:2400],
- }
-
- async def _fetch_bilibili_video_subtitle_text(self, bvid: str, cid: Any = 0) -> dict[str, Any]:
- safe_bvid = _single_line(bvid, 40)
- if not safe_bvid:
- return {}
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=15)
- headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125 Safari/537.36",
- "Referer": f"https://www.bilibili.com/video/{safe_bvid}",
- "Accept": "application/json, text/plain, */*",
- "Accept-Encoding": "gzip, deflate",
- }
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- safe_cid = _safe_int(cid, 0, 0)
- if safe_cid <= 0:
- async with session.get(f"https://api.bilibili.com/x/web-interface/view?bvid={safe_bvid}") as resp:
- if resp.status < 400:
- payload = await resp.json(content_type=None)
- data = payload.get("data") if isinstance(payload, dict) else {}
- if isinstance(data, dict):
- safe_cid = _safe_int(data.get("cid"), 0, 0)
- if safe_cid <= 0:
- return {}
- async with session.get(f"https://api.bilibili.com/x/player/v2?bvid={safe_bvid}&cid={safe_cid}") as resp:
- if resp.status >= 400:
- return {}
- payload = await resp.json(content_type=None)
- data = payload.get("data") if isinstance(payload, dict) else {}
- subtitle = data.get("subtitle") if isinstance(data, dict) and isinstance(data.get("subtitle"), dict) else {}
- subtitles = subtitle.get("subtitles") if isinstance(subtitle.get("subtitles"), list) else []
- if not subtitles:
- return {"cid": safe_cid, "available": False, "count": 0}
- subtitle_item = next((item for item in subtitles if isinstance(item, dict) and str(item.get("lan") or "").lower().startswith("zh")), None)
- if not subtitle_item:
- subtitle_item = next((item for item in subtitles if isinstance(item, dict)), None)
- if not isinstance(subtitle_item, dict):
- return {"cid": safe_cid, "available": False, "count": len(subtitles)}
- subtitle_url = _single_line(subtitle_item.get("subtitle_url") or subtitle_item.get("url"), 500)
- if subtitle_url.startswith("//"):
- subtitle_url = f"https:{subtitle_url}"
- if not subtitle_url.startswith(("http://", "https://")):
- return {"cid": safe_cid, "available": False, "count": len(subtitles)}
- async with session.get(subtitle_url) as resp:
- if resp.status >= 400:
- return {"cid": safe_cid, "available": False, "count": len(subtitles), "subtitle_url": subtitle_url}
- subtitle_payload = await resp.json(content_type=None)
- except Exception as exc:
- logger.debug("[PrivateCompanion] B站字幕读取失败 bvid=%s: %s", safe_bvid, exc)
- return {}
-
- body = subtitle_payload.get("body") if isinstance(subtitle_payload, dict) and isinstance(subtitle_payload.get("body"), list) else []
- lines = []
- for segment in body:
- if not isinstance(segment, dict):
- continue
- text = re.sub(r"\s+", " ", str(segment.get("content") or "")).strip()
- if text:
- lines.append(text)
- subtitle_text = "\n".join(lines).strip()
- subtitle_text = re.sub(r"\n{3,}", "\n\n", subtitle_text)
- if len(subtitle_text) < 80:
- return {"cid": safe_cid, "available": bool(subtitles), "count": len(subtitles), "subtitle_url": subtitle_url, "chars": len(subtitle_text)}
- return {
- "cid": safe_cid,
- "available": True,
- "count": len(subtitles),
- "subtitle_url": subtitle_url,
- "language": _single_line(subtitle_item.get("lan_doc") or subtitle_item.get("lan"), 40),
- "text": subtitle_text,
- "chars": len(subtitle_text),
- }
-
- @staticmethod
- def _format_bilibili_duration(seconds: Any) -> str:
- total = _safe_int(seconds, 0, 0)
- if total <= 0:
- return ""
- hours = total // 3600
- minutes = (total % 3600) // 60
- secs = total % 60
- if hours:
- return f"{hours}小时{minutes}分{secs}秒"
- return f"{minutes}分{secs}秒"
-
- async def _fetch_bilibili_video_public_context(self, bvid: str, cid: Any = 0) -> dict[str, Any]:
- """Lightweight video context inspired by BiliBot: metadata, tags, hot comments."""
- safe_bvid = _single_line(bvid, 40)
- if not safe_bvid:
- return {}
-
- context: dict[str, Any] = {"bvid": safe_bvid}
- for obj in self._find_bilibili_runtime_objects() if getattr(self, "enable_bilibili_integration", False) else []:
- try:
- oid = 0
- get_oid = getattr(obj, "_get_video_oid", None)
- if callable(get_oid):
- payload = get_oid(safe_bvid)
- if hasattr(payload, "__await__"):
- payload = await payload
- oid = _safe_int(payload, 0, 0)
- get_info = getattr(obj, "_get_video_info", None)
- if callable(get_info) and oid > 0:
- payload = get_info(oid)
- if hasattr(payload, "__await__"):
- payload = await payload
- if isinstance(payload, dict):
- context.update(self._normalize_bilibili_video_payload({"data": payload}, safe_bvid))
- context["aid"] = oid
- get_tags = getattr(obj, "_get_video_tags", None)
- if callable(get_tags):
- payload = get_tags(safe_bvid)
- if hasattr(payload, "__await__"):
- payload = await payload
- if isinstance(payload, list):
- context["tags"] = [_single_line(tag, 40) for tag in payload if _single_line(tag, 40)][:10]
- get_comments = getattr(obj, "_get_hot_comments", None)
- if callable(get_comments) and oid > 0:
- payload = get_comments(oid, limit=6)
- if hasattr(payload, "__await__"):
- payload = await payload
- if isinstance(payload, list):
- context["hot_comments"] = [_single_line(comment, 120) for comment in payload if _single_line(comment, 120)][:6]
- if context.get("title") or context.get("tags") or context.get("hot_comments"):
- break
- except Exception as exc:
- logger.debug("[PrivateCompanion] BiliBot 视频上下文联动失败 bvid=%s: %s", safe_bvid, exc)
-
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=15)
- headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125 Safari/537.36",
- "Referer": f"https://www.bilibili.com/video/{safe_bvid}",
- "Accept": "application/json, text/plain, */*",
- "Accept-Encoding": "gzip, deflate",
- }
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- if not context.get("title") or not context.get("aid") or not context.get("cid"):
- async with session.get("https://api.bilibili.com/x/web-interface/view", params={"bvid": safe_bvid}) as resp:
- if resp.status < 400:
- payload = await resp.json(content_type=None)
- if isinstance(payload, dict) and int(payload.get("code") or 0) == 0:
- data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
- context.update(self._normalize_bilibili_video_payload(payload, safe_bvid))
- context["aid"] = _safe_int(data.get("aid"), _safe_int(context.get("aid"), 0, 0), 0)
- context["duration"] = _safe_int(data.get("duration"), _safe_int(context.get("duration"), 0, 0), 0)
- stat = data.get("stat") if isinstance(data.get("stat"), dict) else {}
- context["stat"] = {
- "view": _safe_int(stat.get("view"), 0, 0),
- "danmaku": _safe_int(stat.get("danmaku"), 0, 0),
- "reply": _safe_int(stat.get("reply"), 0, 0),
- "like": _safe_int(stat.get("like"), 0, 0),
- }
- if not context.get("tags"):
- async with session.get("https://api.bilibili.com/x/tag/archive/tags", params={"bvid": safe_bvid}) as resp:
- if resp.status < 400:
- payload = await resp.json(content_type=None)
- if isinstance(payload, dict) and int(payload.get("code") or 0) == 0:
- tags = payload.get("data") if isinstance(payload.get("data"), list) else []
- context["tags"] = [
- _single_line(tag.get("tag_name"), 40)
- for tag in tags
- if isinstance(tag, dict) and _single_line(tag.get("tag_name"), 40)
- ][:10]
- aid = _safe_int(context.get("aid"), 0, 0)
- if aid > 0 and not context.get("hot_comments"):
- async with session.get(
- "https://api.bilibili.com/x/v2/reply/main",
- params={"oid": aid, "type": 1, "mode": 3, "ps": 6},
- ) as resp:
- if resp.status < 400:
- payload = await resp.json(content_type=None)
- if isinstance(payload, dict) and int(payload.get("code") or 0) == 0:
- replies = ((payload.get("data") or {}) if isinstance(payload.get("data"), dict) else {}).get("replies")
- if isinstance(replies, list):
- comments: list[str] = []
- for reply in replies:
- if not isinstance(reply, dict):
- continue
- content = reply.get("content") if isinstance(reply.get("content"), dict) else {}
- message = _single_line(content.get("message"), 120)
- if message:
- comments.append(message)
- context["hot_comments"] = comments[:6]
- except Exception as exc:
- logger.debug("[PrivateCompanion] B站视频公开上下文抓取失败 bvid=%s: %s", safe_bvid, exc)
-
- parts: list[str] = []
- owner = _single_line(context.get("owner_name"), 60)
- tname = _single_line(context.get("tname"), 40)
- duration = self._format_bilibili_duration(context.get("duration"))
- if owner:
- parts.append(f"UP主:{owner}")
- if tname:
- parts.append(f"分区:{tname}")
- if duration:
- parts.append(f"时长:{duration}")
- desc = _single_line(context.get("desc"), 360)
- if desc:
- parts.append(f"简介:{desc}")
- tags = context.get("tags") if isinstance(context.get("tags"), list) else []
- tags = [_single_line(tag, 40) for tag in tags if _single_line(tag, 40)]
- if tags:
- parts.append("标签:" + "、".join(tags[:10]))
- comments = context.get("hot_comments") if isinstance(context.get("hot_comments"), list) else []
- comments = [_single_line(comment, 120) for comment in comments if _single_line(comment, 120)]
- if comments:
- parts.append("热门评论:" + " / ".join(comments[:5]))
- context["context_text"] = "\n".join(parts).strip()
- context["context_chars"] = len(context["context_text"])
- return context
-
- async def _bilibili_news_item_from_video(
- self,
- *,
- source_name: str,
- title: Any,
- desc: Any,
- bvid: Any,
- created: Any = 0,
- cid: Any = 0,
- ) -> dict[str, Any]:
- safe_title = _single_line(title, 160)
- safe_bvid = _single_line(bvid, 40)
- if not safe_title or not safe_bvid:
- return {}
- desc_text = str(desc or "")
- article_match = re.search(r"https?://[^\s<>\]))\"']+", desc_text)
- article_link = _single_line(article_match.group(0), 400) if article_match else ""
- video_link = f"https://www.bilibili.com/video/{safe_bvid}"
- article_payload = await self._fetch_news_article_excerpt(article_link) if article_link else {}
- article_text = str(article_payload.get("text") or "").strip()
- article_excerpt = str(article_payload.get("excerpt") or "").strip()
- article_title = _single_line(article_payload.get("title"), 120)
- subtitle_payload = {} if article_text else await self._fetch_bilibili_video_subtitle_text(safe_bvid, cid)
- subtitle_text = str(subtitle_payload.get("text") or "").strip()
- subtitle_excerpt = subtitle_text[:2400]
- video_context = await self._fetch_bilibili_video_public_context(
- safe_bvid,
- cid or subtitle_payload.get("cid"),
- )
- context_text = str(video_context.get("context_text") or "").strip()
- context_excerpt = context_text[:1600]
- published_ts = _safe_float(created, 0)
- if published_ts <= 0:
- published_ts = _safe_float(video_context.get("created"), 0)
- normalized_desc = desc_text or str(video_context.get("desc") or "")
- summary = article_excerpt or subtitle_excerpt or _single_line(normalized_desc, 320) or _single_line(context_text, 320)
- item = {
- "source": source_name,
- "title": article_title or _single_line(video_context.get("title"), 160) or safe_title,
- "link": article_link or video_link,
- "summary": summary,
- "published": datetime.fromtimestamp(published_ts).isoformat() if published_ts else "",
- "published_ts": published_ts,
- "fetched_ts": _now_ts(),
- "media_type": "bilibili_video",
- "video_link": video_link,
- "video_cid": _safe_int(cid, 0, 0) or _safe_int(subtitle_payload.get("cid"), 0, 0),
- "video_aid": _safe_int(video_context.get("aid"), 0, 0),
- "video_owner_name": _single_line(video_context.get("owner_name"), 80),
- "video_owner_mid": _single_line(video_context.get("owner_mid"), 40),
- "video_tname": _single_line(video_context.get("tname"), 60),
- "video_duration": _safe_int(video_context.get("duration"), 0, 0),
- "video_pic": _single_line(video_context.get("pic"), 300),
- "video_tags": video_context.get("tags") if isinstance(video_context.get("tags"), list) else [],
- "video_hot_comments": video_context.get("hot_comments") if isinstance(video_context.get("hot_comments"), list) else [],
- "video_context_text": context_text,
- "video_context_excerpt": context_excerpt,
- "video_context_chars": len(context_text),
- "video_subtitle_text": subtitle_text,
- "video_subtitle_excerpt": subtitle_excerpt,
- "video_subtitle_readable": bool(subtitle_text),
- "video_subtitle_chars": len(subtitle_text),
- "video_subtitle_status": "read" if subtitle_text else ("missing" if subtitle_payload else "unavailable"),
- "article_link": article_link,
- "article_title": article_title,
- "article_text": article_text,
- "article_excerpt": article_excerpt,
- "article_readable": bool(article_text),
- }
- item["key"] = self._news_item_key(item)
- return item if item["key"] else {}
-
- @staticmethod
- def _normalize_bilibili_video_payload(payload: Any, bvid: str = "") -> dict[str, Any]:
- if not isinstance(payload, dict):
- return {}
- data: Any = payload
- if isinstance(payload.get("info"), dict):
- data = payload.get("info")
- elif isinstance(payload.get("data"), dict):
- data = payload.get("data")
- if not isinstance(data, dict):
- return {}
- owner = data.get("owner") if isinstance(data.get("owner"), dict) else {}
- return {
- "bvid": _single_line(data.get("bvid") or bvid, 40),
- "aid": _safe_int(data.get("aid"), 0, 0),
- "title": _single_line(data.get("title"), 180),
- "desc": str(data.get("desc") or data.get("dynamic") or ""),
- "created": data.get("pubdate") or data.get("ctime") or data.get("created") or 0,
- "owner_name": _single_line(owner.get("name") or data.get("owner_name") or data.get("up_name"), 80),
- "owner_mid": _single_line(owner.get("mid") or data.get("owner_mid") or data.get("mid"), 40),
- "tname": _single_line(data.get("tname"), 60),
- "duration": _safe_int(data.get("duration"), 0, 0),
- "pic": _single_line(data.get("pic"), 300),
- "cid": data.get("cid") or 0,
- }
-
- async def _fetch_bilibili_video_info_via_integration(self, bvid: str) -> dict[str, Any]:
- safe_bvid = _single_line(bvid, 40)
- if not safe_bvid or not self.enable_bilibili_integration:
- return {}
- for obj in self._find_bilibili_runtime_objects():
- try:
- client = getattr(obj, "bili_client", None)
- getter = getattr(client, "get_video_info", None) if client is not None else None
- if not callable(getter):
- getter = getattr(obj, "get_video_info", None)
- if callable(getter):
- payload = getter(safe_bvid)
- if hasattr(payload, "__await__"):
- payload = await payload
- normalized = self._normalize_bilibili_video_payload(payload, safe_bvid)
- if normalized.get("title"):
- logger.info("[PrivateCompanion] 已通过 B站插件客户端读取视频信息: %s", safe_bvid)
- return normalized
- http_get = getattr(obj, "_http_get", None)
- if callable(http_get):
- payload = http_get(
- "https://api.bilibili.com/x/web-interface/view",
- params={"bvid": safe_bvid},
- )
- if hasattr(payload, "__await__"):
- payload = await payload
- data = payload[0] if isinstance(payload, (list, tuple)) and payload else payload
- if isinstance(data, dict) and int(data.get("code") or 0) == 0:
- normalized = self._normalize_bilibili_video_payload(data, safe_bvid)
- if normalized.get("title"):
- logger.info("[PrivateCompanion] 已通过 BiliBot HTTP 客户端读取视频信息: %s", safe_bvid)
- return normalized
- except Exception as exc:
- logger.debug("[PrivateCompanion] B站插件视频信息联动失败 bvid=%s: %s", safe_bvid, exc)
- return {}
-
- async def _fetch_bilibili_space_payloads_via_integration(self, mid: str) -> list[dict[str, Any]]:
- safe_mid = re.sub(r"\D+", "", str(mid or ""))
- if not safe_mid or not self.enable_bilibili_integration:
- return []
- payloads: list[dict[str, Any]] = []
- for obj in self._find_bilibili_runtime_objects():
- try:
- client = getattr(obj, "bili_client", None)
- getter = getattr(client, "get_latest_dynamics", None) if client is not None else None
- if not callable(getter):
- getter = getattr(obj, "get_latest_dynamics", None)
- if callable(getter):
- payload = getter(int(safe_mid))
- if hasattr(payload, "__await__"):
- payload = await payload
- if isinstance(payload, dict):
- payloads.append(payload)
- logger.info("[PrivateCompanion] 已通过 B站插件客户端读取 UP 最新动态: mid=%s", safe_mid)
- continue
- http_get = getattr(obj, "_http_get", None)
- if callable(http_get):
- payload = http_get(
- "https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space",
- params={
- "host_mid": safe_mid,
- "offset": "",
- "timezone_offset": -480,
- "features": "itemOpusStyle,listOnlyfans,opusBigCover,onlyfansVote",
- },
- )
- if hasattr(payload, "__await__"):
- payload = await payload
- data = payload[0] if isinstance(payload, (list, tuple)) and payload else payload
- if isinstance(data, dict) and int(data.get("code") or 0) == 0:
- payloads.append(data)
- logger.info("[PrivateCompanion] 已通过 BiliBot HTTP 客户端读取 UP 最新动态: mid=%s", safe_mid)
- continue
- except Exception as exc:
- logger.debug("[PrivateCompanion] B站插件 UP 动态联动失败 mid=%s: %s", safe_mid, exc)
- return payloads
-
- async def _fetch_bilibili_video_news_source(self, source: dict[str, str]) -> list[dict[str, Any]]:
- bvid = _single_line(source.get("bvid"), 40)
- if not bvid:
- return []
- source_name = _single_line(source.get("name"), 40) or f"B站视频 {bvid}"
- integrated_info = await self._fetch_bilibili_video_info_via_integration(bvid)
- if integrated_info:
- item = await self._bilibili_news_item_from_video(
- source_name=source_name,
- title=integrated_info.get("title"),
- desc=integrated_info.get("desc"),
- bvid=integrated_info.get("bvid") or bvid,
- created=integrated_info.get("created"),
- cid=integrated_info.get("cid"),
- )
- if item:
- item["bilibili_integration_source"] = "plugin_client"
- return [item]
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=12)
- headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125 Safari/537.36",
- "Referer": f"https://www.bilibili.com/video/{bvid}",
- "Accept": "application/json, text/plain, */*",
- "Accept-Encoding": "gzip, deflate",
- }
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- async with session.get(f"https://api.bilibili.com/x/web-interface/view?bvid={bvid}") as resp:
- if resp.status >= 400:
- return await self._fetch_bilibili_news_search_fallback(source)
- payload = await resp.json(content_type=None)
- except Exception as exc:
- logger.debug("[PrivateCompanion] B站单视频新闻源抓取失败 bvid=%s: %s", bvid, exc)
- return await self._fetch_bilibili_news_search_fallback(source)
- data = payload.get("data") if isinstance(payload, dict) else {}
- if not isinstance(data, dict):
- return await self._fetch_bilibili_news_search_fallback(source)
- item = await self._bilibili_news_item_from_video(
- source_name=source_name,
- title=data.get("title"),
- desc=data.get("desc") or data.get("dynamic"),
- bvid=data.get("bvid") or bvid,
- created=data.get("pubdate") or data.get("ctime"),
- cid=data.get("cid"),
- )
- return [item] if item else await self._fetch_bilibili_news_search_fallback(source)
-
- async def _probe_bilibili_arc_search(self, mid: str, *, limit: int = 10) -> dict[str, Any]:
- safe_mid = re.sub(r"\D+", "", str(mid or ""))
- if not safe_mid:
- return {"ok": False, "error": "empty_mid"}
- url = (
- "https://api.bilibili.com/x/space/arc/search"
- f"?mid={safe_mid}&pn=1&ps={max(1, min(30, limit))}&order=pubdate&jsonp=jsonp"
- )
- probe: dict[str, Any] = {"ok": False, "url": url, "mid": safe_mid}
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=12)
- headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125 Safari/537.36",
- "Referer": f"https://space.bilibili.com/{safe_mid}",
- "Accept": "application/json, text/plain, */*",
- "Accept-Encoding": "gzip, deflate",
- }
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- async with session.get(url) as resp:
- probe["http_status"] = resp.status
- payload = await resp.json(content_type=None)
- except Exception as exc:
- probe["error"] = _single_line(str(exc), 160)
- return probe
- if not isinstance(payload, dict):
- probe["error"] = "non_json_payload"
- return probe
- probe["code"] = payload.get("code")
- probe["message"] = _single_line(payload.get("message"), 80)
- data = payload.get("data") if isinstance(payload.get("data"), dict) else {}
- vlist = (((data.get("list") or {}) if isinstance(data.get("list"), dict) else {}).get("vlist") or [])
- if not isinstance(vlist, list):
- vlist = []
- probe["vlist_count"] = len(vlist)
- if vlist and isinstance(vlist[0], dict):
- first = vlist[0]
- created = _safe_float(first.get("created"), 0)
- probe["first_title"] = _single_line(first.get("title"), 140)
- probe["first_bvid"] = _single_line(first.get("bvid"), 40)
- probe["first_created_ts"] = created
- probe["first_created"] = datetime.fromtimestamp(created).strftime("%Y-%m-%d %H:%M:%S") if created > 0 else ""
- probe["ok"] = int(payload.get("code") or 0) == 0 and bool(vlist)
- return probe
-
- async def _fetch_bilibili_news_source(self, source: dict[str, str], *, limit: int | None = None) -> list[dict[str, Any]]:
- mid = re.sub(r"\D+", "", str(source.get("mid") or ""))
- if not mid:
- return []
- item_limit = max(1, _safe_int(limit if limit is not None else self.news_max_items_per_source, self.news_max_items_per_source, 1))
- payloads: list[dict[str, Any]] = await self._fetch_bilibili_space_payloads_via_integration(mid)
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=12)
- headers = {
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125 Safari/537.36",
- "Referer": f"https://space.bilibili.com/{mid}",
- "Accept": "application/json, text/plain, */*",
- "Accept-Encoding": "gzip, deflate",
- }
- api_urls = [
- f"https://api.bilibili.com/x/space/arc/search?mid={mid}&pn=1&ps={max(1, min(30, item_limit))}&order=pubdate&jsonp=jsonp",
- f"https://api.bilibili.com/x/polymer/web-dynamic/v1/feed/space?host_mid={mid}&timezone_offset=-480&features=itemOpusStyle",
- ]
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- for url in api_urls:
- try:
- async with session.get(url) as resp:
- if resp.status >= 400:
- continue
- data = await resp.json(content_type=None)
- if isinstance(data, dict) and int(data.get("code") or 0) == 0:
- payloads.append(data)
- except Exception:
- continue
- except Exception as exc:
- logger.debug("[PrivateCompanion] B站新闻源抓取失败 mid=%s: %s", mid, exc)
- if not payloads:
- return []
-
- source_name = _single_line(source.get("name"), 40) or f"B站 UP {mid}"
- results: list[dict[str, Any]] = []
-
- async def add_video(title: Any, desc: Any, bvid: Any, created: Any) -> None:
- item = await self._bilibili_news_item_from_video(
- source_name=source_name,
- title=title,
- desc=desc,
- bvid=bvid,
- created=created,
- )
- if item:
- results.append(item)
-
- for payload in payloads:
- data = payload.get("data") if isinstance(payload, dict) else {}
- if not isinstance(data, dict):
- continue
- vlist = (((data.get("list") or {}) if isinstance(data.get("list"), dict) else {}).get("vlist") or [])
- if isinstance(vlist, list):
- for video in vlist:
- if not isinstance(video, dict):
- continue
- await add_video(video.get("title"), video.get("description") or video.get("desc"), video.get("bvid"), video.get("created"))
- dynamic_items = data.get("items") if isinstance(data.get("items"), list) else []
- for dynamic in dynamic_items:
- if not isinstance(dynamic, dict):
- continue
- modules = dynamic.get("modules") if isinstance(dynamic.get("modules"), dict) else {}
- major = ((modules.get("module_dynamic") or {}) if isinstance(modules.get("module_dynamic"), dict) else {}).get("major")
- archive = (major or {}).get("archive") if isinstance(major, dict) else {}
- if not isinstance(archive, dict):
- continue
- await add_video(
- archive.get("title"),
- archive.get("desc") or archive.get("cover"),
- archive.get("bvid"),
- archive.get("pub_ts") or dynamic.get("pub_ts"),
- )
- seen: set[str] = set()
- unique: list[dict[str, Any]] = []
- for item in results:
- key = str(item.get("key") or "")
- if key and key not in seen:
- seen.add(key)
- unique.append(item)
- unique.sort(key=lambda item: (_safe_float(item.get("published_ts"), 0), _safe_float(item.get("fetched_ts"), 0)), reverse=True)
- if unique:
- return unique[:item_limit]
- return await self._fetch_bilibili_news_search_fallback(source)
-
- async def _fetch_news_source(self, source: dict[str, str]) -> list[dict[str, Any]]:
- source_type = str(source.get("type") or "").lower()
- if source_type == "bilibili_video":
- return await self._fetch_bilibili_video_news_source(source)
- if source_type == "bilibili":
- return await self._fetch_bilibili_news_source(source)
- url = str(source.get("url") or "")
- if not url:
- return []
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=12)
- headers = {"User-Agent": f"{PLUGIN_NAME}/news-reader", "Accept-Encoding": "gzip, deflate"}
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- async with session.get(url) as resp:
- if resp.status >= 400:
- return []
- raw = await resp.text(errors="ignore")
- except Exception as exc:
- logger.debug("[PrivateCompanion] 新闻源抓取失败 %s: %s", _single_line(url, 120), exc)
- return []
- try:
- root = ET.fromstring(raw.encode("utf-8", errors="ignore"))
- except Exception as exc:
- logger.debug("[PrivateCompanion] 新闻源 XML 解析失败 %s: %s", _single_line(url, 120), exc)
- return []
-
- source_name = _single_line(source.get("name"), 40) or "新闻源"
- nodes = list(root.findall(".//item"))
- if not nodes:
- nodes = list(root.findall(".//{http://www.w3.org/2005/Atom}entry"))
- results: list[dict[str, Any]] = []
- for node in nodes[: max(1, self.news_max_items_per_source)]:
- title = self._news_xml_text(node, "title", "{http://www.w3.org/2005/Atom}title")
- link = self._news_xml_text(node, "link")
- if not link:
- atom_link = node.find("{http://www.w3.org/2005/Atom}link")
- if atom_link is not None:
- link = str(atom_link.attrib.get("href") or "").strip()
- summary = self._news_xml_text(
- node,
- "description",
- "summary",
- "{http://www.w3.org/2005/Atom}summary",
- "{http://www.w3.org/2005/Atom}content",
- )
- published = self._news_xml_text(
- node,
- "pubDate",
- "published",
- "updated",
- "{http://www.w3.org/2005/Atom}published",
- "{http://www.w3.org/2005/Atom}updated",
- )
- if not title:
- continue
- item = {
- "source": source_name,
- "title": _single_line(title, 160),
- "link": _single_line(link, 400),
- "summary": _single_line(summary, 320),
- "published": _single_line(published, 80),
- "published_ts": self._news_parse_time(published),
- "fetched_ts": _now_ts(),
- }
- item["key"] = self._news_item_key(item)
- if item["key"]:
- results.append(item)
- return results
-
- async def _fetch_news_candidates(self) -> list[dict[str, Any]]:
- sources = self._news_source_items()
- if not sources:
- return []
- batches = await asyncio.gather(*(self._fetch_news_source(source) for source in sources), return_exceptions=True)
- seen: set[str] = set()
- items: list[dict[str, Any]] = []
- for batch in batches:
- if not isinstance(batch, list):
- continue
- for item in batch:
- if not isinstance(item, dict):
- continue
- key = str(item.get("key") or "")
- if not key or key in seen:
- continue
- seen.add(key)
- items.append(item)
- items.sort(key=lambda item: (_safe_float(item.get("published_ts"), 0), _safe_float(item.get("fetched_ts"), 0)), reverse=True)
- return items[:24]
-
- async def _fetch_news_reading_candidates(self) -> list[dict[str, Any]]:
- batches = await asyncio.gather(
- self._fetch_news_candidates(),
- self._fetch_hot_trend_candidates(),
- return_exceptions=True,
- )
- seen: set[str] = set()
- items: list[dict[str, Any]] = []
- for batch in batches:
- if not isinstance(batch, list):
- continue
- for item in batch:
- if not isinstance(item, dict):
- continue
- key = str(item.get("key") or self._news_item_key(item) or self._hot_trend_key(item))
- if not key or key in seen:
- continue
- seen.add(key)
- normalized = dict(item)
- normalized["key"] = key
- if not normalized.get("summary") and normalized.get("snippet"):
- normalized["summary"] = normalized.get("snippet")
- if not normalized.get("link") and normalized.get("url"):
- normalized["link"] = normalized.get("url")
- normalized.setdefault("fetched_ts", _now_ts())
- items.append(normalized)
- items.sort(
- key=lambda item: (
- _safe_float(item.get("published_ts"), 0) or _safe_float(item.get("fetched_ts"), 0),
- _safe_float(item.get("score"), 0),
- ),
- reverse=True,
- )
- return items[:32]
-
- def _news_fallback_digest(self, items: list[dict[str, Any]]) -> dict[str, Any]:
- item = items[0] if items else {}
- title = _single_line(item.get("title"), 100)
- summary = _single_line(item.get("summary"), 180)
- source = _single_line(item.get("source"), 40)
- impression = summary
- if item.get("video_context_text") and (not impression or len(impression) < 16 or impression in {"早早早", "早", "无"}):
- impression = _single_line(item.get("video_context_text"), 180)
- if not impression and item.get("video_link"):
- subtitle_status = _single_line(item.get("video_subtitle_status"), 40)
- if subtitle_status == "missing":
- impression = "找到当天 B 站 AI 早报视频,也尝试读取字幕;字幕暂无,只能按视频公开信息和标题记录。"
- elif subtitle_status == "unavailable":
- impression = "找到当天 B 站 AI 早报视频,也尝试读取字幕,但这次没有拿到可用正文,只能按视频公开信息和标题记录。"
- else:
- impression = "找到当天 B 站 AI 早报视频,但还没有可展开的文字正文,只能按视频公开信息和标题记录。"
- if not impression:
- impression = f"从 {source or '新闻源'} 看到一条新消息,还没来得及细看。"
- return {
- "topic": title or "新闻",
- "headline": title,
- "impression": impression,
- "selected_key": _single_line(item.get("key"), 32),
- "selected_link": _single_line(item.get("link"), 400),
- "selected_source": source,
- "items": items[:8],
- "created_ts": _now_ts(),
- }
-
- async def _summarize_news_items(self, items: list[dict[str, Any]]) -> dict[str, Any]:
- if not items:
- return {}
- provider_id = self._task_provider(self.news_provider_id, self.narration_provider_id, self.llm_provider_id)
- if not provider_id:
- return self._news_fallback_digest(items)
- lines = []
- for idx, item in enumerate(items[:8], 1):
- title = _single_line(item.get("title"), 120)
- source = _single_line(item.get("source"), 24)
- if item.get("article_readable") and item.get("article_text"):
- article_text = str(item.get("article_text") or "").strip()
- lines.append(
- f"{idx}. [{source}] {title}\n"
- f"文字版链接:{_single_line(item.get('link'), 220)}\n"
- f"完整文字版正文:\n{article_text}"
- )
- continue
- if item.get("video_subtitle_readable") and item.get("video_subtitle_text"):
- subtitle_text = str(item.get("video_subtitle_text") or "").strip()
- lines.append(
- f"{idx}. [{source}] {title}\n"
- f"视频链接:{_single_line(item.get('video_link') or item.get('link'), 220)}\n"
- f"视频字幕正文:\n{subtitle_text}"
- )
- continue
- if item.get("video_context_text"):
- context_text = str(item.get("video_context_text") or "").strip()
- lines.append(
- f"{idx}. [{source}] {title}\n"
- f"视频链接:{_single_line(item.get('video_link') or item.get('link'), 220)}\n"
- f"视频公开信息:\n{context_text}"
- )
- continue
- summary = _single_line(item.get("summary"), 180)
- lines.append(f"{idx}. [{source}] {title}" + (f"|{summary}" if summary else ""))
- prompt = f"""
-请作为 Bot 私下阅读新闻后的内部整理,从下面新闻里挑一条最适合轻轻提起的内容。
-
-要求:
-1. 不要写成新闻播报,要像“刚看到一条消息后脑子里的印象”。
-2. 不要夸大事实,不要补充列表外没有的信息。
-3. 如果候选里包含“完整文字版正文”,必须以完整正文为准;如果没有文字版但包含“视频字幕正文”,必须以视频字幕为准;如果只有“视频公开信息”,可以参考 UP 主、分区、时长、简介、标签和热门评论,不要只看标题或链接。
-4. 如果都不适合分享,仍挑一个最普通、风险最低的话题。
-5. 输出 JSON,字段为 topic, headline, impression, selected_index。
-6. topic 20字以内;headline 80字以内;impression 160字以内。
-
-新闻候选:
-{chr(10).join(lines)}
-""".strip()
- raw = await self._llm_call(prompt, max_tokens=260, provider_id=provider_id, task="news_digest")
- parsed = self._parse_json_object(raw)
- if not isinstance(parsed, dict):
- return self._news_fallback_digest(items)
- index = _safe_int(parsed.get("selected_index"), 1, 1, len(items[:8])) - 1
- selected = items[index] if 0 <= index < len(items) else items[0]
- return {
- "topic": _single_line(parsed.get("topic"), 40) or _single_line(selected.get("title"), 40),
- "headline": _single_line(parsed.get("headline"), 100) or _single_line(selected.get("title"), 100),
- "impression": _single_line(parsed.get("impression"), 240) or _single_line(selected.get("summary"), 180),
- "selected_key": _single_line(selected.get("key"), 32),
- "selected_link": _single_line(selected.get("link"), 400),
- "selected_source": _single_line(selected.get("source"), 40),
- "items": items[:8],
- "created_ts": _now_ts(),
- }
-
- def _external_event_self_link_provider_id(self) -> str:
- return self._task_provider(self.news_provider_id, self.web_exploration_provider_id, self.narration_provider_id, self.llm_provider_id)
-
- def _format_external_event_stable_self_context(self) -> str:
- model_lines = []
- plugin_main = self._task_provider(self.llm_provider_id)
- if plugin_main:
- model_lines.append(f"插件主模型:{self._provider_identity_label(plugin_main)}")
- if self.news_provider_id:
- model_lines.append(f"新闻整理模型:{self._provider_identity_label(self.news_provider_id)}")
- if self.web_exploration_provider_id:
- model_lines.append(f"主动搜索整理模型:{self._provider_identity_label(self.web_exploration_provider_id)}")
- return "\n".join(
- part
- for part in (
- f"Bot 名称:{self.bot_name}",
- "当前模型环境:" + ";".join(model_lines) if model_lines else "",
- f"人格:{_single_line(self._get_default_persona_prompt(), 900)}",
- self._format_worldview_adaptation_prompt(),
- )
- if part
- )
-
- def _format_external_event_current_self_context(self) -> str:
- state = self.data.get("daily_state", {}) if isinstance(self.data.get("daily_state"), dict) else {}
- current_item = self._get_current_plan_item(self.data.get("daily_plan", {}))
- mood = _single_line(state.get("mood_bias"), 40)
- energy = _safe_int(state.get("energy"), 70, 0, 100)
- activity = _single_line((current_item or {}).get("activity"), 120)
- return "\n".join(
- part
- for part in (
- f"当前状态:{mood or '平稳'},心理能量 {energy}/100",
- f"当前日程:{activity}" if activity else "",
- )
- if part
- )
-
- def _format_external_event_self_context(self) -> str:
- stable = self._format_external_event_stable_self_context()
- current = self._format_external_event_current_self_context()
- return "\n".join(part for part in (stable, current) if part)
-
- def _external_event_fallback_wish(self, payload: dict[str, Any], *, source_type: str) -> dict[str, Any]:
- title = _single_line(payload.get("headline") or payload.get("topic") or payload.get("source_title"), 100)
- note = _single_line(payload.get("impression") or payload.get("note") or payload.get("summary"), 220)
- haystack = f"{title} {note}".lower()
- self_tokens = (
- "ai", "模型", "大模型", "llm", "视觉", "多模态", "上下文", "记忆", "agent", "智能体",
- "机器人", "bot", "搜索", "新闻", "bilibili", "doubao", "deepseek", "glm", "gemini",
- "claude", "gpt", "qwen", "豆包", "火山", "openai",
- )
- matched = []
- for token in self_tokens:
- if token.isascii():
- if re.search(rf"(?= 7 and desire >= 7,
- "share_probability": min(0.85, 0.18 + relevance * 0.055 + desire * 0.035),
- "motive": _single_line(
- f"刚读到的{('新闻' if source_type == 'news' else '搜索结果')}和自己的能力、兴趣或最近状态有一点关系,想按人格私下找用户说说",
- 180,
- ),
- "self_link": _single_line("这条外界消息可能影响我会做什么、想学什么、想试什么,或让我联想到自己的状态。", 180),
- "tone": "有分享欲,自然一点",
- "boundary": "不要说成系统通知;不要要求用户一定做什么;只表达自己的反应和一点想法。",
- }
-
- def _external_event_life_opportunity_wish(self, payload: dict[str, Any], *, source_type: str) -> dict[str, Any]:
- title = _single_line(payload.get("headline") or payload.get("topic") or payload.get("source_title"), 120)
- note = _single_line(payload.get("impression") or payload.get("note") or payload.get("summary"), 260)
- haystack = f"{title} {note}".lower()
- tokens = (
- "免单", "免费", "送", "抽奖", "福利", "优惠", "券", "红包", "周年庆",
- "奶茶", "茶百道", "咖啡", "甜品", "饮品", "碰碰运气", "试试", "薅",
- )
- if not any(token in haystack for token in tokens):
- return {}
- return {
- "relevance": 8,
- "desire": 8,
- "should_share": True,
- "share_probability": 0.86,
- "self_link": "这像是能和用户一起碰碰运气的小福利,和日常吃喝、撒娇分享都很贴近。",
- "motive": "这条活动是实在的生活福利",
- "tone": "轻快,有点心动,不要像广告",
- "boundary": "不要保证一定抢到;不要催促用户;如果正在休息,就当作醒来后顺口提起。",
- "created_ts": _now_ts(),
- "source_type": source_type,
- "boost_reason": "life_opportunity",
- }
-
- async def _build_external_event_wish(self, payload: dict[str, Any], *, source_type: str) -> dict[str, Any]:
- if not self.enable_external_event_self_link or not isinstance(payload, dict):
- return {}
- cached = self._cached_external_event_wish(payload, source_type=source_type)
- if cached:
- return cached
- provider_id = self._external_event_self_link_provider_id()
- fallback = self._external_event_fallback_wish(payload, source_type=source_type)
- life_wish = self._external_event_life_opportunity_wish(payload, source_type=source_type)
- if not provider_id:
- result = life_wish or fallback
- self._remember_external_event_wish_cache(payload, result, source_type=source_type)
- return result
- title = _single_line(payload.get("headline") or payload.get("topic") or payload.get("source_title"), 120)
- impression = _single_line(payload.get("impression") or payload.get("note") or payload.get("summary"), 360)
- source = _single_line(payload.get("selected_source") or payload.get("source_title") or payload.get("source"), 80)
- link = _single_line(payload.get("selected_link") or payload.get("source_url") or payload.get("link"), 420)
- stable_self_context = self._format_external_event_stable_self_context()
- current_self_context = self._format_external_event_current_self_context()
- prompt = f"""
-请判断 Bot 刚读到的一条外界信息,是否会在它心里产生“和我自己有关,想找用户说说”的主动意愿。
-
-这不是写给用户的消息,只是内部决策。请不要把关键词当硬触发,要根据人格、当前状态、能力边界、兴趣、近期见闻和用户关系判断。
-
-判断维度:
-1. 自我关联:这条信息是否和 Bot 的能力、模型、创作、日程、兴趣、世界观身份、正在做的事或与用户的关系有关。
-2. 意愿强度:Bot 是否会产生分享欲、求助欲、试试看、撒娇、吐槽、担心、好奇、想让用户知道等动机。
-3. 主动边界:是否适合现在主动私聊;不适合就 should_share=false。
-4. 如果适合, motive 要写成内部动机,不是最终发言。不要写插件、后台、任务、JSON 这类词。
-
-输出 JSON:
-{{
- "relevance": 0到10,
- "desire": 0到10,
- "should_share": true或false,
- "share_probability": 0到1,
- "self_link": "这件事和 Bot 自己有什么关系,80字内",
- "motive": "为什么想找用户说,100字内",
- "tone": "适合的表达气质,如撒娇/好奇/嘴硬/认真/轻轻分享",
- "boundary": "主动时要避开的表达,80字内"
-}}
-
-【Bot 稳定自我上下文】
-{stable_self_context}
-
-【来源类型】
-{source_type}
-
-【外界信息】
-标题:{title}
-来源:{source}
-链接:{link}
-内部印象:{impression}
-
-【Bot 当前短时状态】
-{current_self_context}
-""".strip()
- raw = await self._llm_call(prompt, max_tokens=360, provider_id=provider_id, task="external_event_self_link")
- parsed = self._parse_json_object(raw)
- if not isinstance(parsed, dict):
- result = life_wish or fallback
- self._remember_external_event_wish_cache(payload, result, source_type=source_type)
- return result
- relevance = _safe_int(parsed.get("relevance"), fallback["relevance"], 0, 10)
- desire = _safe_int(parsed.get("desire"), fallback["desire"], 0, 10)
- probability = _safe_float(parsed.get("share_probability"), fallback["share_probability"])
- result = {
- "relevance": relevance,
- "desire": desire,
- "should_share": bool(parsed.get("should_share", relevance >= 5 and desire >= 5)),
- "share_probability": max(0.0, min(1.0, probability)),
- "self_link": _single_line(parsed.get("self_link"), 180) or fallback["self_link"],
- "motive": _single_line(parsed.get("motive"), 180) or fallback["motive"],
- "tone": _single_line(parsed.get("tone"), 60) or fallback["tone"],
- "boundary": _single_line(parsed.get("boundary"), 140) or fallback["boundary"],
- "created_ts": _now_ts(),
- "source_type": source_type,
- }
- if life_wish:
- if not result["should_share"] or result["share_probability"] < life_wish["share_probability"]:
- result = {
- **result,
- "relevance": max(result["relevance"], life_wish["relevance"]),
- "desire": max(result["desire"], life_wish["desire"]),
- "should_share": True,
- "share_probability": max(result["share_probability"], life_wish["share_probability"]),
- "self_link": result["self_link"] if result["relevance"] >= 5 else life_wish["self_link"],
- "motive": life_wish["motive"],
- "tone": life_wish["tone"],
- "boundary": life_wish["boundary"],
- "boost_reason": life_wish["boost_reason"],
- }
- self._remember_external_event_wish_cache(payload, result, source_type=source_type)
- return result
-
- def _bot_currently_bored_enough_for_news(self) -> bool:
- now_dt = datetime.now()
- if now_dt.hour < 7 or now_dt.hour >= 24:
- return False
- state = self.data.get("daily_state", {})
- energy = _safe_int(state.get("energy") if isinstance(state, dict) else 70, 70, 0, 100)
- mood = _single_line(state.get("mood_bias") if isinstance(state, dict) else "", 24)
- current_item = self._get_current_plan_item(self.data.get("daily_plan", {}))
- activity = _single_line((current_item or {}).get("activity"), 80)
- text = f"{mood} {activity}"
- if any(token in text for token in ("无聊", "发呆", "摸鱼", "休息", "闲", "空", "刷")):
- return True
- return 30 <= energy <= 80 and random.random() < 0.28
-
- async def _perform_news_reading(self, *, reason: str = "boredom", allow_share: bool = True, force: bool = False) -> None:
- if not self.enable_news_integration:
- return
- state = self.data.setdefault("news_integration", {})
- if not isinstance(state, dict):
- self.data["news_integration"] = {}
- state = self.data["news_integration"]
- now = _now_ts()
- if not force and now - _safe_float(state.get("last_probe_at"), 0) < 45 * 60:
- return
- state["last_probe_at"] = now
- items = await self._fetch_news_reading_candidates()
- if not items:
- state["last_status"] = "no_items"
- self._save_data_sync()
- return
- read_keys = state.setdefault("read_keys", [])
- if not isinstance(read_keys, list):
- read_keys = []
- state["read_keys"] = read_keys
- fresh = [item for item in items if str(item.get("key") or "") not in set(str(key) for key in read_keys)]
- if not fresh:
- fresh = items[:8]
- digest = await self._summarize_news_items(fresh)
- if not digest:
- state["last_status"] = "digest_failed"
- self._save_data_sync()
- return
- selected_key = _single_line(digest.get("selected_key"), 32)
- if selected_key and selected_key not in read_keys:
- read_keys.append(selected_key)
- del read_keys[:-80]
- state["last_read_at"] = now
- if reason == "daily":
- state["last_daily_read_day"] = _today_key()
- state["last_status"] = "read"
- state["last_reason"] = reason
- state["last_digest"] = digest
- digests = state.setdefault("digests", [])
- if not isinstance(digests, list):
- digests = []
- state["digests"] = digests
- wish = await self._build_external_event_wish(digest, source_type="news")
- if wish:
- digest["self_link"] = wish
- share_attempts: list[dict[str, Any]] = []
- digest["share_attempts"] = share_attempts
- digest["share_status"] = "not_attempted"
-
- def _note_news_share(user_id_value: Any, status: str, reason_text: str, **extra: Any) -> None:
- item = {
- "user_id": str(user_id_value or ""),
- "status": _single_line(status, 32),
- "reason": _single_line(reason_text, 120),
- "ts": _now_ts(),
- }
- for key, value in extra.items():
- if isinstance(value, (int, float, bool)):
- item[key] = value
- else:
- item[key] = _single_line(value, 160)
- share_attempts.append(item)
-
- history_digest = {
- key: value
- for key, value in digest.items()
- if key not in {"items", "results", "raw_items", "articles"}
- }
- digests.append({**history_digest, "reason": reason})
- del digests[:-32]
-
- def _sync_digest_share_status() -> None:
- if not digests or not isinstance(digests[-1], dict):
- return
- if selected_key and _single_line(digests[-1].get("selected_key"), 32) != selected_key:
- return
- digests[-1].update({
- "share_status": digest.get("share_status", ""),
- "share_skip_reason": digest.get("share_skip_reason", ""),
- "share_attempts": share_attempts,
- })
-
- state["latest_items"] = items[:12]
- self_link_allows_share = bool(wish.get("should_share")) if isinstance(wish, dict) else False
- if not allow_share and not self_link_allows_share:
- digest["share_status"] = "blocked"
- digest["share_skip_reason"] = "本次新闻阅读不允许主动分享,且自我关联未通过"
- _sync_digest_share_status()
- self._save_data_sync()
- logger.info("[PrivateCompanion] 已完成一次新闻阅读: %s", reason)
- return
- users = self.data.get("users")
- accepted_any = False
- if isinstance(users, dict):
- for user_id, user in users.items():
- if not isinstance(user, dict) or not self._is_target_private_user(str(user_id), user) or not user.get("enabled", True) or not user.get("umo"):
- continue
- selection = self._select_external_event_for_user(user, fresh[:12] or items[:12], source_type="news", base_payload=digest, now=now)
- user_digest = selection.get("payload") if isinstance(selection, dict) else None
- if not isinstance(user_digest, dict):
- user_digest = dict(digest)
- user_preference = selection.get("preference") if isinstance(selection.get("preference"), dict) else {}
- user_selected_key = _single_line(user_digest.get("selected_key"), 32) or selected_key
- user_wish = wish
- if user_selected_key and user_selected_key != selected_key:
- user_wish = self._external_event_fallback_wish(user_digest, source_type="news")
- if isinstance(wish, dict) and wish:
- user_wish = {
- **user_wish,
- "should_share": bool(wish.get("should_share")) or bool(user_wish.get("should_share")),
- "relevance": max(_safe_int(wish.get("relevance"), 0, 0, 10), _safe_int(user_wish.get("relevance"), 0, 0, 10)),
- "desire": max(_safe_int(wish.get("desire"), 0, 0, 10), _safe_int(user_wish.get("desire"), 0, 0, 10)),
- "share_probability": max(_safe_float(wish.get("share_probability"), 0.0), _safe_float(user_wish.get("share_probability"), 0.0)),
- }
- user_digest["self_link"] = user_wish
- strong_self_link = (
- isinstance(user_wish, dict)
- and bool(user_wish)
- and (
- _safe_int(user_wish.get("relevance"), 0, 0, 10) >= 8
- or _safe_int(user_wish.get("desire"), 0, 0, 10) >= 8
- or _safe_float(user_wish.get("share_probability"), 0.0) >= 0.8
- or bool(user_wish.get("boost_reason"))
- or _safe_int(user_preference.get("score"), 0) >= 10
- )
- )
- idle_required = max(self.idle_minutes, 90) * 60
- if strong_self_link:
- idle_required = min(idle_required, max(20, self.idle_minutes) * 60)
- idle_elapsed = now - _safe_float(user.get("last_seen"), 0)
- if idle_elapsed < idle_required:
- _note_news_share(user_id, "skipped", "用户近期仍活跃,暂不主动打扰", idle_elapsed_seconds=round(idle_elapsed, 1), idle_required_seconds=round(idle_required, 1))
- continue
- if str(user.get("last_news_share_key") or "") == user_selected_key:
- _note_news_share(user_id, "skipped", "这条新闻已经给该用户排过主动")
- continue
- if now - _safe_float(user.get("last_news_share_at"), 0) < 8 * 3600:
- _note_news_share(user_id, "skipped", "新闻分享 8 小时冷却中")
- continue
- shared_link_cooldown = self._external_link_share_cooldown_remaining(user, now=now)
- if shared_link_cooldown > 0:
- _note_news_share(
- user_id,
- "skipped",
- "主动外链统一冷却中",
- cooldown_remaining_hours=round(shared_link_cooldown / 3600.0, 1),
- )
- continue
- if isinstance(user_wish, dict) and user_wish:
- if now - _safe_float(user.get("last_external_event_self_link_at"), 0) < self.external_event_self_link_cooldown_hours * 3600:
- _note_news_share(user_id, "skipped", "外界信息自我关联冷却中")
- continue
- if not user_wish.get("should_share") and _safe_int(user_preference.get("score"), 0) < 8:
- _note_news_share(user_id, "skipped", "自我关联与用户偏好都不足以主动分享", relevance=_safe_int(user_wish.get("relevance"), 0), desire=_safe_int(user_wish.get("desire"), 0), user_preference=_safe_int(user_preference.get("score"), 0))
- continue
- decision = self._external_event_share_decision(
- user,
- user_digest,
- source_type="news",
- wish=user_wish,
- base_probability=self.news_share_probability,
- now=now,
- )
- if decision.get("duplicate"):
- _note_news_share(user_id, "skipped", "近期同类外界信息已经处理过")
- continue
- if not decision.get("should_share"):
- _note_news_share(
- user_id,
- "skipped",
- "统一评分认为这条新闻不值得现在主动分享",
- score=_safe_int(decision.get("score"), 0, 0, 100),
- user_match=_safe_int(decision.get("user_match"), 0, 0, 10),
- user_preference=_safe_int(user_preference.get("score"), 0),
- )
- continue
- share_probability = max(self.news_share_probability, _safe_float(decision.get("probability"), self.news_share_probability))
- share_probability *= self.external_event_self_link_probability
- if strong_self_link:
- share_probability = max(share_probability, min(0.95, _safe_float(user_wish.get("share_probability"), share_probability)))
- if _safe_int(user_preference.get("score"), 0) >= 8:
- share_probability = min(0.95, share_probability + 0.10)
- else:
- decision = self._external_event_share_decision(
- user,
- user_digest,
- source_type="news",
- wish={"relevance": 4, "desire": 4, "should_share": True},
- base_probability=self.news_share_probability,
- now=now,
- )
- if decision.get("duplicate") or not decision.get("should_share"):
- _note_news_share(user_id, "skipped", "统一评分认为这条新闻不值得现在主动分享")
- continue
- share_probability = self.news_share_probability
- if random.random() > max(0.0, min(1.0, share_probability)):
- _note_news_share(user_id, "skipped", "分享概率未命中", probability=round(max(0.0, min(1.0, share_probability)), 3))
- continue
- self_link_motive = _single_line(user_wish.get("motive") if isinstance(user_wish, dict) else "", 180)
- self_link_tone = _single_line(user_wish.get("tone") if isinstance(user_wish, dict) else "", 60)
- self_link_boundary = _single_line(user_wish.get("boundary") if isinstance(user_wish, dict) else "", 140)
- accepted = self._offer_proactive_candidate(
- str(user_id),
- user,
- {
- "source": "news",
- "reason": "news_share",
- "action": "message",
- "scheduled_ts": now + random.randint(10, 55) * 60,
- "topic": _single_line(user_digest.get("topic"), 48) or "新闻",
- "score": max(4 if self_link_motive else 3, _safe_int(decision.get("score"), 0, 0, 100)),
- "motive": self_link_motive
- or "这条新闻和对方兴趣相关",
- "context_key": "news_context",
- "context": {
- **user_digest,
- "share_tone": self_link_tone,
- "share_boundary": self_link_boundary,
- "share_decision": decision,
- "preference_match": user_preference,
- },
- },
- )
- if accepted:
- accepted_any = True
- _note_news_share(user_id, "accepted", "已按用户偏好进入主动候选", probability=round(max(0.0, min(1.0, share_probability)), 3), user_preference=_safe_int(user_preference.get("score"), 0), selected_key=user_selected_key)
- user["news_context"] = {
- **user_digest,
- "share_tone": self_link_tone,
- "share_boundary": self_link_boundary,
- "share_decision": decision,
- "preference_match": user_preference,
- }
- user["last_news_share_key"] = user_selected_key
- user["last_news_share_at"] = now
- self._note_external_link_candidate(user, now=now)
- if isinstance(user_wish, dict) and user_wish:
- user["last_external_event_self_link_at"] = now
- self._remember_external_event(user_digest, source_type="news", reason="news_share")
- else:
- _note_news_share(user_id, "blocked", "主动候选被计划队列拒绝,可能已有更早主动或主题重复")
- if accepted_any:
- digest["share_status"] = "accepted"
- elif share_attempts:
- digest["share_status"] = "skipped"
- digest["share_skip_reason"] = share_attempts[-1].get("reason", "")
- else:
- digest["share_status"] = "no_target"
- digest["share_skip_reason"] = "没有可用的目标私聊用户"
- _sync_digest_share_status()
- self._save_data_sync()
- logger.info("[PrivateCompanion] 已完成一次新闻阅读: %s", reason)
-
- def _ai_daily_state(self) -> dict[str, Any]:
- state = self.data.setdefault("news_integration", {})
- if not isinstance(state, dict):
- self.data["news_integration"] = {}
- state = self.data["news_integration"]
- ai_state = state.setdefault("ai_daily", {})
- if not isinstance(ai_state, dict):
- ai_state = {}
- state["ai_daily"] = ai_state
- return ai_state
-
- @staticmethod
- def _news_item_is_today(item: dict[str, Any], today: str | None = None) -> bool:
- today = today or _today_key()
- published_ts = _safe_float(item.get("published_ts"), 0)
- if published_ts > 0:
- try:
- return datetime.fromtimestamp(published_ts).strftime("%Y-%m-%d") == today
- except Exception:
- pass
- text = f"{item.get('title') or ''} {item.get('published') or ''} {item.get('summary') or ''}"
- now_dt = datetime.now()
- today_cn = now_dt.strftime("%Y年%m月%d日").replace("年0", "年").replace("月0", "月")
- today_dash = now_dt.strftime("%Y-%m-%d")
- today_slash = now_dt.strftime("%Y/%m/%d")
- today_md = f"{now_dt.month}月{now_dt.day}日"
- today_compact = now_dt.strftime("%m%d")
- today_short_compact = f"{now_dt.month}{now_dt.day:02d}"
- return any(token in text for token in (today_cn, today_dash, today_slash, today_md, today_compact, today_short_compact))
-
- def _ai_daily_candidate_snapshot(self, items: list[dict[str, Any]], today: str) -> list[dict[str, Any]]:
- snapshot: list[dict[str, Any]] = []
- for item in items[:10]:
- if not isinstance(item, dict):
- continue
- published_ts = _safe_float(item.get("published_ts"), 0)
- published_date = ""
- if published_ts > 0:
- try:
- published_date = datetime.fromtimestamp(published_ts).strftime("%Y-%m-%d %H:%M:%S")
- except Exception:
- published_date = ""
- snapshot.append(
- {
- "title": _single_line(item.get("title"), 140),
- "published": published_date or _single_line(item.get("published"), 80),
- "link": _single_line(item.get("video_link") or item.get("link"), 420),
- "media_type": _single_line(item.get("media_type"), 40),
- "is_today": self._news_item_is_today(item, today),
- }
- )
- return snapshot
-
- async def _read_ai_daily_source(
- self,
- source: dict[str, Any],
- *,
- ai_state: dict[str, Any],
- source_state: dict[str, Any],
- today: str,
- now: float,
- ) -> bool:
- source_key = str(source.get("key") or self._ai_daily_source_key(source))
- source_name = _single_line(source.get("name"), 40) or "AI日报"
- source_author = _single_line(source.get("author_name"), 60)
- items = await self._fetch_bilibili_news_search_fallback(source)
- today_items = [
- item for item in items
- if isinstance(item, dict) and self._ai_daily_item_matches_source(item, source, today)
- ]
- ai_state["last_candidates"] = self._ai_daily_candidate_snapshot(items, today)
- source_state.update(
- {
- "date": today,
- "last_attempt_date": today,
- "last_checked_at": now,
- "last_candidate_count": len(items),
- "last_candidates": self._ai_daily_candidate_snapshot(items, today),
- }
- )
- if not today_items:
- source_state["status"] = "waiting_today_video"
- ai_state.update(
- {
- "date": today,
- "status": "waiting_today_video",
- "last_checked_at": now,
- "last_candidate_count": len(items),
- "last_source_name": source_name,
- "last_source_author": source_author,
- "last_source_mid": _single_line(source.get("mid"), 40),
- "last_source_key": source_key,
- "last_source_schedule": _single_line(source.get("schedule"), 10),
- }
- )
- return False
- today_items.sort(key=lambda item: (_safe_float(item.get("published_ts"), 0), _safe_float(item.get("fetched_ts"), 0)), reverse=True)
- item = today_items[0]
- bvid = _single_line(item.get("video_link"), 120)
- bvid_match = re.search(r"(BV[0-9A-Za-z]+)", bvid)
- bvid_key = bvid_match.group(1) if bvid_match else _single_line(item.get("key"), 32)
- if bvid_key and str(source_state.get("last_video_bvid") or "") == bvid_key:
- source_state["status"] = "already_read_today_video"
- source_state["last_success_date"] = today
- ai_state.update(
- {
- "date": today,
- "status": "already_read_today_video",
- "last_success_date": today,
- "last_checked_at": now,
- "last_source_name": source_name,
- "last_source_author": source_author,
- "last_source_mid": _single_line(source.get("mid"), 40),
- "last_source_key": source_key,
- "last_source_schedule": _single_line(source.get("schedule"), 10),
- }
- )
- return True
- if getattr(self, "ai_daily_prefer_text_version", True) and not item.get("article_readable"):
- source_state.update(
- {
- "status": "today_video_without_text",
- "last_video_bvid": bvid_key,
- "last_video_title": _single_line(item.get("title"), 120),
- }
- )
- # 仍然继续用简介整理,避免文字版偶发缺失时今天完全没读到。
- read_basis = "完整文字版正文" if item.get("article_readable") and item.get("article_text") else (
- "视频字幕" if item.get("video_subtitle_readable") and item.get("video_subtitle_text") else (
- "视频公开信息" if item.get("video_context_text") else "视频标题/简介"
- )
- )
- digest = await self._summarize_news_items([item])
- if not digest:
- source_state["status"] = "digest_failed"
- ai_state.update(
- {
- "date": today,
- "status": "digest_failed",
- "last_checked_at": now,
- "last_source_name": source_name,
- "last_source_author": source_author,
- "last_source_mid": _single_line(source.get("mid"), 40),
- "last_source_key": source_key,
- "last_source_schedule": _single_line(source.get("schedule"), 10),
- }
- )
- return False
- wish = await self._build_external_event_wish(digest, source_type="news")
- if wish:
- digest["self_link"] = wish
- state = self.data.setdefault("news_integration", {})
- if not isinstance(state, dict):
- self.data["news_integration"] = {}
- state = self.data["news_integration"]
- state["last_read_at"] = now
- state["last_status"] = "read"
- state["last_reason"] = "ai_daily"
- state["last_digest"] = digest
- state["latest_items"] = [item]
- digests = state.setdefault("digests", [])
- if not isinstance(digests, list):
- digests = []
- state["digests"] = digests
- history_digest = {
- key: value
- for key, value in digest.items()
- if key not in {"items", "results", "raw_items", "articles"}
- }
- digests.append({**history_digest, "reason": "ai_daily"})
- del digests[:-32]
- read_keys = state.setdefault("read_keys", [])
- if isinstance(read_keys, list):
- selected_key = _single_line(digest.get("selected_key"), 32)
- if selected_key and selected_key not in read_keys:
- read_keys.append(selected_key)
- del read_keys[:-80]
- result_state = {
- "status": "read",
- "last_success_date": today,
- "last_checked_at": now,
- "last_source_name": source_name,
- "last_source_author": source_author,
- "last_source_mid": _single_line(source.get("mid"), 40),
- "last_source_key": source_key,
- "last_source_schedule": _single_line(source.get("schedule"), 10),
- "last_video_bvid": bvid_key,
- "last_video_title": _single_line(item.get("title"), 120),
- "last_video_pub_ts": _safe_float(item.get("published_ts"), 0),
- "last_video_link": _single_line(item.get("video_link") or item.get("link"), 400),
- "last_video_owner_name": _single_line(item.get("video_owner_name"), 80),
- "last_video_owner_mid": _single_line(item.get("video_owner_mid"), 40),
- "last_video_tname": _single_line(item.get("video_tname"), 60),
- "last_video_duration": _safe_int(item.get("video_duration"), 0, 0),
- "last_video_context_chars": len(str(item.get("video_context_text") or "")),
- "last_video_tags": list(item.get("video_tags") or [])[:10] if isinstance(item.get("video_tags"), list) else [],
- "last_video_hot_comments": list(item.get("video_hot_comments") or [])[:5] if isinstance(item.get("video_hot_comments"), list) else [],
- "last_text_link": _single_line(item.get("article_link"), 400),
- "last_text_readable": bool(item.get("article_readable") and item.get("article_text")),
- "last_text_chars": len(str(item.get("article_text") or "")),
- "last_text_excerpt_chars": len(str(item.get("article_excerpt") or "")),
- "last_video_subtitle_readable": bool(item.get("video_subtitle_readable") and item.get("video_subtitle_text")),
- "last_video_subtitle_chars": len(str(item.get("video_subtitle_text") or "")),
- "last_video_subtitle_status": _single_line(item.get("video_subtitle_status"), 40),
- "last_read_basis": read_basis,
- "last_digest": digest,
- }
- source_state.update(result_state)
- ai_state.update({"date": today, **result_state})
- logger.info(
- "[PrivateCompanion] 已读取今日 %s: %s text_readable=%s text_chars=%s basis=%s",
- source_name,
- _single_line(item.get("title"), 120),
- bool(item.get("article_readable") and item.get("article_text")),
- len(str(item.get("article_text") or "")),
- read_basis,
- )
- return True
-
- async def _maybe_track_ai_daily(self, *, force: bool = False) -> None:
- if not (self.enable_news_integration and self.enable_ai_daily_watch):
- return
- ai_state = self._ai_daily_state()
- today = _today_key()
- now = _now_ts()
- now_dt = datetime.now()
- source_states = ai_state.setdefault("source_states", {})
- if not isinstance(source_states, dict):
- source_states = {}
- ai_state["source_states"] = source_states
- configured_sources = self._ai_daily_source_items()
- ai_state["sources"] = [
- {
- "key": _single_line(source.get("key") or self._ai_daily_source_key(source), 80),
- "name": _single_line(source.get("name"), 40),
- "author_name": _single_line(source.get("author_name"), 60),
- "mid": _single_line(source.get("mid"), 40),
- "schedule": _single_line(source.get("schedule"), 10),
- "keywords": [_single_line(token, 20) for token in source.get("keywords", [])[:6]],
- }
- for source in configured_sources
- ]
- due_sources = self._ai_daily_due_sources(now_dt, today, source_states, force=force)
- if not due_sources:
- now_minute = now_dt.hour * 60 + now_dt.minute
- future_sources = [
- source for source in configured_sources
- if _safe_int(source.get("schedule_minutes"), 0, 0) > now_minute
- and not (
- isinstance(source_states.get(str(source.get("key") or "")), dict)
- and source_states[str(source.get("key") or "")].get("last_success_date") == today
- )
- ]
- status = "waiting_schedule" if future_sources else "all_sources_done"
- if ai_state.get("date") != today or ai_state.get("status") != status:
- ai_state.update({"date": today, "status": status, "last_checked_at": ai_state.get("last_checked_at", 0)})
- self._save_data_sync()
- return
- ai_state.update({"date": today, "last_checked_at": now, "status": "checking"})
- self._save_data_sync()
- any_read = False
- for source in due_sources:
- key = str(source.get("key") or self._ai_daily_source_key(source))
- source_state = source_states.setdefault(key, {})
- if not isinstance(source_state, dict):
- source_state = {}
- source_states[key] = source_state
- source_state.update(
- {
- "name": _single_line(source.get("name"), 40),
- "author_name": _single_line(source.get("author_name"), 60),
- "mid": _single_line(source.get("mid"), 40),
- "schedule": _single_line(source.get("schedule"), 10),
- "status": "checking",
- }
- )
- read = await self._read_ai_daily_source(
- source,
- ai_state=ai_state,
- source_state=source_state,
- today=today,
- now=now,
- )
- any_read = any_read or read
- if not any_read and ai_state.get("status") == "checking":
- ai_state["status"] = "waiting_today_video"
- self._save_data_sync()
-
- async def _maybe_trigger_news_boredom_read(self) -> None:
- if not (self.enable_news_integration and self.enable_news_boredom_read):
- return
- if not self._bot_currently_bored_enough_for_news():
- return
- state = self.data.setdefault("news_integration", {})
- if not isinstance(state, dict):
- self.data["news_integration"] = {}
- state = self.data["news_integration"]
- now = _now_ts()
- min_interval = max(1, self.news_min_interval_hours) * 3600
- if now - _safe_float(state.get("last_read_at"), 0) < min_interval:
- return
- if random.random() > 0.42:
- return
- await self._perform_news_reading(reason="boredom", allow_share=True, force=False)
-
- async def _ensure_daily_news_reading(self, *, force: bool = False) -> None:
- if not (self.enable_news_integration and self.enable_news_daily_hot_read):
- return
- state = self.data.setdefault("news_integration", {})
- if not isinstance(state, dict):
- self.data["news_integration"] = {}
- state = self.data["news_integration"]
- today = _today_key()
- if not force and state.get("last_daily_read_day") == today:
- return
- await self._perform_news_reading(reason="daily", allow_share=False, force=True)
-
- def _astrbot_web_search_provider_settings(self, umo: str = "") -> dict[str, Any]:
- try:
- cfg = self.context.get_config(umo=umo) if umo else self.context.get_config()
- except Exception:
- try:
- cfg = self.context.get_config()
- except Exception:
- cfg = {}
- settings = cfg.get("provider_settings", {}) if isinstance(cfg, dict) else {}
- return dict(settings or {}) if isinstance(settings, dict) else {}
-
- def _astrbot_web_search_available(self, umo: str = "") -> bool:
- settings = self._astrbot_web_search_provider_settings(umo)
- if not settings.get("web_search", False):
- return False
- provider = str(settings.get("websearch_provider") or "").strip()
- if provider == "tavily":
- return bool(settings.get("websearch_tavily_key"))
- if provider == "bocha":
- return bool(settings.get("websearch_bocha_key"))
- if provider == "brave":
- return bool(settings.get("websearch_brave_key"))
- if provider == "firecrawl":
- return bool(settings.get("websearch_firecrawl_key"))
- if provider == "baidu_ai_search":
- return bool(settings.get("websearch_baidu_app_builder_key"))
- return False
-
- def _web_search_candidate_umos(self) -> list[str]:
- candidates = [""]
- users = self.data.get("users") if isinstance(self.data.get("users"), dict) else {}
- for uid, item in users.items():
- if not isinstance(item, dict):
- continue
- if not self._is_target_private_user(str(uid), item) or not item.get("enabled", True):
- continue
- umo = str(item.get("umo") or "").strip()
- if umo and umo not in candidates:
- candidates.append(umo)
- return candidates
-
- def _astrbot_any_web_search_available(self) -> bool:
- return any(self._astrbot_web_search_available(umo) for umo in self._web_search_candidate_umos())
-
- @staticmethod
- def _normalize_web_exploration_api_base_url(value: Any) -> str:
- raw = str(value or "").strip()
- if not raw:
- return ""
- if raw.startswith(("http://", "https://")):
- return raw
- if re.match(r"^[a-z][a-z0-9+.-]*://", raw, flags=re.I):
- return ""
- local_pattern = r"^(localhost|127\.|10\.|172\.(1[6-9]|2\d|3[0-1])\.|192\.168\.|\[?::1\]?)"
- scheme = "http://" if re.match(local_pattern, raw, flags=re.I) else "https://"
- return f"{scheme}{raw}"
-
- def _custom_web_exploration_search_configured(self) -> bool:
- return bool(self._normalize_web_exploration_api_base_url(getattr(self, "web_exploration_api_base_url", "")))
-
- def _custom_web_exploration_get_url(self, base_url: str, query: str, *, topic: str = "general", model: str = "") -> str:
- cleaned_query = _single_line(query, 240)
- if not base_url or not cleaned_query:
- return ""
- max_results = str(max(1, min(20, self.web_exploration_max_results)))
- values = {
- "query": cleaned_query,
- "q": cleaned_query,
- "keyword": cleaned_query,
- "keywords": cleaned_query,
- "wd": cleaned_query,
- "text": cleaned_query,
- "topic": "news" if topic == "news" else "general",
- "max_results": max_results,
- "limit": max_results,
- "count": max_results,
- "model": str(model or "").strip(),
- }
- formatted = base_url
- replaced = False
- for key, value in values.items():
- encoded = quote(str(value), safe="")
- for token in (f"{{{{{key}}}}}", f"{{{key}}}", f"${{{key}}}"):
- if token in formatted:
- formatted = formatted.replace(token, encoded)
- replaced = True
- if replaced:
- return formatted
- if formatted.endswith(("?", "&")):
- return f"{formatted}query={quote(cleaned_query, safe='')}"
- if re.search(r"[?&][^=&?#]+=$", formatted):
- return f"{formatted}{quote(cleaned_query, safe='')}"
- return ""
-
- def _web_exploration_search_available(self) -> bool:
- return self._custom_web_exploration_search_configured() or self._astrbot_any_web_search_available()
-
- def _pick_available_web_search_umo(self, preferred: str = "") -> str:
- candidates = []
- preferred = str(preferred or "").strip()
- if preferred:
- candidates.append(preferred)
- for umo in self._web_search_candidate_umos():
- if umo not in candidates:
- candidates.append(umo)
- for umo in candidates:
- if self._astrbot_web_search_available(umo):
- return umo
- return ""
-
- def _web_search_runtime_state(self) -> dict[str, Any]:
- state = self.data.setdefault("web_search_runtime", {})
- if not isinstance(state, dict):
- self.data["web_search_runtime"] = {}
- state = self.data["web_search_runtime"]
- return state
-
- def _web_search_cooldown_remaining(self, provider: str) -> float:
- provider = _single_line(provider, 80) or "unknown"
- state = self.data.get("web_search_runtime") if isinstance(self.data.get("web_search_runtime"), dict) else {}
- item = state.get(provider) if isinstance(state, dict) else None
- if not isinstance(item, dict):
- return 0.0
- retry_after = _safe_float(item.get("retry_after"), 0.0, 0.0)
- return max(0.0, retry_after - _now_ts())
-
- def _web_search_error_cooldown_seconds(self, error: Any) -> tuple[float, str]:
- text = str(error or "")
- if "QUOTA_USER_DAILY_FREE" in text or "Daily free quota" in text:
- now_dt = datetime.now()
- tomorrow = (now_dt + timedelta(days=1)).replace(hour=0, minute=10, second=0, microsecond=0)
- return max(3600.0, min(24 * 3600.0, (tomorrow - now_dt).total_seconds())), "daily_quota"
- if "RATE_LIMIT_SEARCH_QPS" in text or "QPS" in text:
- return 10 * 60.0, "qps_limit"
- if "429" in text or "rate limit" in text.lower() or "quota" in text.lower():
- return 30 * 60.0, "rate_or_quota"
- return 0.0, ""
-
- def _mark_web_search_cooldown(self, provider: str, error: Any) -> None:
- seconds, reason = self._web_search_error_cooldown_seconds(error)
- if seconds <= 0:
- return
- provider = _single_line(provider, 80) or "unknown"
- state = self._web_search_runtime_state()
- state[provider] = {
- "retry_after": _now_ts() + seconds,
- "reason": reason,
- "last_error": _single_line(error, 240),
- "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
- }
- try:
- self._save_data_sync()
- except Exception:
- pass
- logger.warning(
- "[PrivateCompanion] 网页搜索进入冷却: provider=%s reason=%s retry=%ss error=%s",
- provider,
- reason,
- int(seconds),
- _single_line(error, 180),
- )
-
- @staticmethod
- def _extract_custom_web_search_content(payload: Any) -> str:
- if isinstance(payload, str):
- return payload
- if not isinstance(payload, dict):
- return ""
- choices = payload.get("choices")
- if isinstance(choices, list) and choices:
- first = choices[0] if isinstance(choices[0], dict) else {}
- message = first.get("message") if isinstance(first, dict) else {}
- if isinstance(message, dict):
- content = message.get("content")
- if isinstance(content, str):
- return content
- if isinstance(content, list):
- parts: list[str] = []
- for item in content:
- if isinstance(item, dict):
- text = item.get("text") or item.get("content")
- if isinstance(text, str):
- parts.append(text)
- elif isinstance(item, str):
- parts.append(item)
- return "\n".join(parts)
- text = first.get("text") if isinstance(first, dict) else ""
- if isinstance(text, str):
- return text
- for key in ("answer", "content", "text", "summary"):
- value = payload.get(key)
- if isinstance(value, str):
- return value
- return ""
-
- def _custom_web_search_items_from_payload(self, payload: Any) -> list[Any]:
- if isinstance(payload, list):
- return payload
- if isinstance(payload, str):
- text = re.sub(r"^```(?:json)?\s*|\s*```$", "", payload.strip(), flags=re.I | re.S).strip()
- candidates = [text]
- match = re.search(r"\[.*\]", text, flags=re.S)
- if match:
- candidates.append(match.group(0))
- for candidate in candidates:
- try:
- parsed = json.loads(candidate)
- except Exception:
- continue
- if isinstance(parsed, list):
- return parsed
- if isinstance(parsed, dict):
- return self._custom_web_search_items_from_payload(parsed)
- return []
- if not isinstance(payload, dict):
- return []
- for key in ("results", "items", "search_results", "web_results", "documents", "organic"):
- value = payload.get(key)
- if isinstance(value, list):
- return value
- data = payload.get("data")
- if isinstance(data, list):
- return data
- if isinstance(data, dict):
- for key in ("results", "items", "search_results", "web_results", "documents", "organic"):
- value = data.get(key)
- if isinstance(value, list):
- return value
- content = self._extract_custom_web_search_content(payload)
- items = self._custom_web_search_items_from_payload(content)
- if items:
- return items
- parsed = self._parse_json_object(content)
- if isinstance(parsed, dict):
- return self._custom_web_search_items_from_payload(parsed)
- return []
-
- def _normalize_custom_web_search_results(self, payload: Any, query: str) -> list[dict[str, Any]]:
- cleaned_query = _single_line(query, 120)
- items = self._custom_web_search_items_from_payload(payload)
- results: list[dict[str, Any]] = []
- for item in items:
- if not isinstance(item, dict):
- text = _single_line(item, 360)
- if not text:
- continue
- title = text[:80]
- url = ""
- snippet = text
- else:
- title = _single_line(
- item.get("title")
- or item.get("name")
- or item.get("headline")
- or item.get("source_title")
- or item.get("site_name"),
- 140,
- )
- url = _single_line(
- item.get("url")
- or item.get("link")
- or item.get("href")
- or item.get("source_url")
- or item.get("page_url"),
- 420,
- )
- snippet = _single_line(
- item.get("snippet")
- or item.get("summary")
- or item.get("content")
- or item.get("description")
- or item.get("text")
- or item.get("body"),
- 360,
- )
- if not title and not snippet:
- continue
- key = hashlib.sha1(f"custom|{cleaned_query}|{title}|{url}|{snippet}".encode("utf-8", errors="ignore")).hexdigest()[:16]
- results.append({"key": key, "title": title or snippet[:80], "url": url, "snippet": snippet, "provider": "custom_web_exploration"})
- if len(results) >= self.web_exploration_max_results:
- break
- if results:
- return results[: self.web_exploration_max_results]
-
- content = _single_line(self._extract_custom_web_search_content(payload), 720)
- if content:
- key = hashlib.sha1(f"custom|{cleaned_query}|{content}".encode("utf-8", errors="ignore")).hexdigest()[:16]
- return [
- {
- "key": key,
- "title": cleaned_query or "自定义主动搜索结果",
- "url": "",
- "snippet": content,
- "provider": "custom_web_exploration",
- }
- ]
- return []
-
- async def _run_custom_web_exploration_search(self, query: str, *, topic: str = "general") -> list[dict[str, Any]]:
- cleaned_query = _single_line(query, 120)
- base_url = self._normalize_web_exploration_api_base_url(getattr(self, "web_exploration_api_base_url", ""))
- api_key = str(getattr(self, "web_exploration_api_key", "") or "").strip()
- model = str(getattr(self, "web_exploration_api_model", "") or "").strip()
- if not cleaned_query or not base_url:
- return []
- if not base_url.startswith(("http://", "https://")):
- self._last_web_search_error = "custom_web_exploration:invalid_url"
- return []
- cooldown = self._web_search_cooldown_remaining("custom_web_exploration")
- if cooldown > 0:
- self._last_web_search_error = f"custom_web_exploration_cooldown:{int(cooldown)}s"
- logger.info(
- "[PrivateCompanion] 自定义主动搜索冷却中,跳过请求: retry=%ss query=%s",
- int(cooldown),
- cleaned_query,
- )
- return []
-
- headers = {
- "Accept": "application/json, text/plain, */*",
- "User-Agent": f"{PLUGIN_NAME}/web-exploration",
- }
- if api_key:
- headers["Authorization"] = f"Bearer {api_key}"
- lower_url = base_url.lower()
- get_url = self._custom_web_exploration_get_url(base_url, cleaned_query, topic=topic, model=model)
- if get_url:
- payload = None
- elif "/chat/completions" in lower_url:
- payload: dict[str, Any] = {
- "messages": [
- {
- "role": "system",
- "content": (
- "你是搜索接口适配器。请基于可用联网搜索能力返回 JSON, 格式为 "
- '{"results":[{"title":"","url":"","snippet":""}]}。'
- ),
- },
- {"role": "user", "content": cleaned_query},
- ],
- "temperature": 0.2,
- }
- if model:
- payload["model"] = model
- else:
- payload = {
- "query": cleaned_query,
- "topic": "news" if topic == "news" else "general",
- "max_results": max(1, min(20, self.web_exploration_max_results)),
- }
- if model:
- payload["model"] = model
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=20)
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- if get_url:
- resp_ctx = session.get(get_url)
- else:
- post_headers = {"Content-Type": "application/json"}
- resp_ctx = session.post(base_url, headers=post_headers, json=payload)
- async with resp_ctx as resp:
- body_text = await resp.text()
- if resp.status >= 400:
- raise RuntimeError(f"HTTP {resp.status}: {_single_line(body_text, 180)}")
- try:
- raw_payload: Any = json.loads(body_text)
- except Exception:
- raw_payload = body_text
- except asyncio.TimeoutError as exc:
- detail = "请求超时"
- self._last_web_search_error = f"custom_web_exploration:{detail}"
- self._mark_web_search_cooldown("custom_web_exploration", detail)
- logger.warning("[PrivateCompanion] 自定义主动搜索失败: query=%s err=%s", cleaned_query, detail)
- return []
- except Exception as exc:
- detail = _single_line(exc, 220) or exc.__class__.__name__
- self._last_web_search_error = f"custom_web_exploration:{detail}"
- self._mark_web_search_cooldown("custom_web_exploration", exc)
- logger.warning("[PrivateCompanion] 自定义主动搜索失败: query=%s err=%s", cleaned_query, exc)
- return []
-
- results = self._normalize_custom_web_search_results(raw_payload, cleaned_query)
- if not results:
- self._last_web_search_error = "custom_web_exploration:no_usable_results"
- return results
-
- async def _run_astrbot_web_search(self, query: str, *, umo: str = "", topic: str = "general", usage: str = "general") -> list[dict[str, Any]]:
- cleaned_query = _single_line(query, 120)
- self._last_web_search_error = ""
- if not cleaned_query:
- return []
- if usage == "web_exploration" and self._custom_web_exploration_search_configured():
- return await self._run_custom_web_exploration_search(cleaned_query, topic=topic)
- settings = self._astrbot_web_search_provider_settings(umo)
- if not settings.get("web_search", False):
- return []
- provider = str(settings.get("websearch_provider") or "").strip()
- if provider == "default":
- return []
- cooldown = self._web_search_cooldown_remaining(provider)
- if cooldown > 0:
- self._last_web_search_error = f"web_search_cooldown:{provider}:{int(cooldown)}s"
- logger.info(
- "[PrivateCompanion] AstrBot 网页搜索冷却中,跳过请求: provider=%s retry=%ss query=%s",
- provider,
- int(cooldown),
- cleaned_query,
- )
- return []
- for key in (
- "websearch_tavily_key",
- "websearch_bocha_key",
- "websearch_brave_key",
- "websearch_firecrawl_key",
- ):
- value = settings.get(key)
- if isinstance(value, str):
- value = value.strip()
- settings[key] = [value] if value else []
- baidu_key = settings.get("websearch_baidu_app_builder_key")
- if isinstance(baidu_key, list):
- settings["websearch_baidu_app_builder_key"] = str(baidu_key[0] if baidu_key else "").strip()
- elif isinstance(baidu_key, str):
- settings["websearch_baidu_app_builder_key"] = baidu_key.strip()
- try:
- from astrbot.core.tools import web_search_tools as ws
- if provider == "tavily":
- payload = {
- "query": cleaned_query,
- "max_results": max(5, min(20, self.web_exploration_max_results)),
- "include_favicon": True,
- "search_depth": "basic",
- "topic": "news" if topic == "news" else "general",
- }
- if topic == "news":
- payload["days"] = 7
- raw_results = await ws._tavily_search(settings, payload)
- elif provider == "bocha":
- raw_results = await ws._bocha_search(
- settings,
- {
- "query": cleaned_query,
- "count": max(1, min(50, self.web_exploration_max_results)),
- "summary": True,
- "freshness": "noLimit",
- },
- )
- elif provider == "brave":
- raw_results = await ws._brave_search(
- settings,
- {
- "q": cleaned_query,
- "count": max(1, min(20, self.web_exploration_max_results)),
- "country": "CN",
- "search_lang": "zh-hans",
- },
- )
- elif provider == "firecrawl":
- raw_results = await ws._firecrawl_search(
- settings,
- {"query": cleaned_query, "limit": max(1, min(20, self.web_exploration_max_results)), "sources": ["web"]},
- )
- elif provider == "baidu_ai_search":
- raw_results = await ws._baidu_search(
- settings,
- {
- "messages": [{"role": "user", "content": cleaned_query[:72]}],
- "search_source": "baidu_search_v2",
- "resource_type_filter": [{"type": "web", "top_k": max(1, min(50, self.web_exploration_max_results))}],
- },
- )
- else:
- return []
- except Exception as exc:
- self._last_web_search_error = _single_line(str(exc), 240)
- self._mark_web_search_cooldown(provider, exc)
- logger.warning("[PrivateCompanion] AstrBot 网页搜索失败: provider=%s query=%s err=%s", provider, cleaned_query, exc)
- return []
- results: list[dict[str, Any]] = []
- for item in raw_results or []:
- title = _single_line(getattr(item, "title", "") if not isinstance(item, dict) else item.get("title"), 140)
- url = _single_line(getattr(item, "url", "") if not isinstance(item, dict) else item.get("url"), 420)
- snippet = _single_line(getattr(item, "snippet", "") if not isinstance(item, dict) else item.get("snippet"), 360)
- if not title and not snippet:
- continue
- key = hashlib.sha1(f"{title}|{url}|{snippet}".encode("utf-8", errors="ignore")).hexdigest()[:16]
- results.append({"key": key, "title": title, "url": url, "snippet": snippet, "provider": provider})
- return results[: self.web_exploration_max_results]
-
- def _web_exploration_recent_context(self) -> str:
- state = self.data.get("daily_state", {})
- mood = _single_line(state.get("mood_bias") if isinstance(state, dict) else "", 30)
- energy = _safe_int(state.get("energy") if isinstance(state, dict) else 70, 70, 0, 100)
- current_item = self._get_current_plan_item(self.data.get("daily_plan", {}))
- activity = _single_line((current_item or {}).get("activity"), 80)
- recent_user = ""
- users = self.data.get("users") if isinstance(self.data.get("users"), dict) else {}
- latest_user = max(
- (item for item in users.values() if isinstance(item, dict)),
- key=lambda item: _safe_float(item.get("last_seen"), 0),
- default={},
- )
- if isinstance(latest_user, dict):
- recent_user = _single_line(latest_user.get("last_user_message"), 120)
- news_state = self.data.get("news_integration") if isinstance(self.data.get("news_integration"), dict) else {}
- news_digest = news_state.get("last_digest") if isinstance(news_state.get("last_digest"), dict) else {}
- news_topic = _single_line(news_digest.get("topic") or news_digest.get("headline"), 100)
- return "\n".join(
- part
- for part in (
- f"当前状态:{mood or '平稳'},能量 {energy}/100",
- f"当前日程:{activity}" if activity else "",
- f"最近用户提到:{recent_user}" if recent_user else "",
- f"今日新闻见闻:{news_topic}" if news_topic else "",
- f"兴趣倾向配置:{_single_line(self.web_exploration_interests, 240)}",
- )
- if part
- )
-
- def _hot_trend_source_names(self) -> list[str]:
- raw = str(self.news_hot_sources or "")
- names = []
- for item in re.split(r"[,,\n]+", raw):
- name = item.strip().lower()
- if name in {"weibo", "微博", "微博热搜"}:
- name = "weibo"
- elif name in {"hn", "hackernews", "hacker news"}:
- name = "hackernews"
- else:
- continue
- if name not in names:
- names.append(name)
- return names or ["weibo", "hackernews"]
-
- def _hot_trend_key(self, item: dict[str, Any]) -> str:
- raw = "|".join(
- _single_line(item.get(key), 240)
- for key in ("source", "title", "url")
- if _single_line(item.get(key), 240)
- )
- return hashlib.sha1(raw.encode("utf-8", errors="ignore")).hexdigest()[:16] if raw else ""
-
- async def _fetch_weibo_hot_trends(self) -> list[dict[str, Any]]:
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=12)
- headers = {
- "User-Agent": f"{PLUGIN_NAME}/hot-trends",
- "Accept": "application/json",
- "Referer": "https://weibo.com/",
- }
- async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session:
- async with session.get("https://weibo.com/ajax/side/hotSearch") as resp:
- if resp.status >= 400:
- return []
- data = await resp.json(content_type=None)
- except Exception as exc:
- logger.debug("[PrivateCompanion] 微博热搜抓取失败: %s", exc)
- return []
- rows = (((data or {}).get("data") or {}).get("realtime") or []) if isinstance(data, dict) else []
- items: list[dict[str, Any]] = []
- for index, row in enumerate(rows[: max(1, self.news_hot_max_items)], 1):
- if not isinstance(row, dict):
- continue
- topic = _single_line(row.get("note") or row.get("word"), 80)
- if not topic:
- continue
- score = _safe_float(row.get("num") or row.get("raw_hot"), 0)
- item = {
- "source": "weibo",
- "title": topic,
- "snippet": f"微博热搜第 {index} 位" + (f",热度 {int(score)}" if score > 0 else ""),
- "url": f"https://s.weibo.com/weibo?q={quote('#' + topic + '#')}",
- "score": score or max(1, self.news_hot_max_items - index + 1),
- "rank": index,
- "published": "",
- "published_ts": 0,
- "created_ts": _now_ts(),
- }
- item["summary"] = item["snippet"]
- item["link"] = item["url"]
- item["key"] = self._hot_trend_key(item)
- items.append(item)
- return items
-
- async def _fetch_hackernews_hot_trends(self) -> list[dict[str, Any]]:
- try:
- import aiohttp
-
- timeout = aiohttp.ClientTimeout(total=12)
- async with aiohttp.ClientSession(timeout=timeout, headers={"User-Agent": f"{PLUGIN_NAME}/hot-trends"}) as session:
- async with session.get(
- "https://hn.algolia.com/api/v1/search",
- params={"tags": "front_page", "hitsPerPage": max(3, min(30, self.news_hot_max_items))},
- ) as resp:
- if resp.status >= 400:
- return []
- data = await resp.json(content_type=None)
- except Exception as exc:
- logger.debug("[PrivateCompanion] Hacker News 热点抓取失败: %s", exc)
- return []
- hits = data.get("hits") if isinstance(data, dict) else []
- items: list[dict[str, Any]] = []
- for index, row in enumerate((hits or [])[: max(1, self.news_hot_max_items)], 1):
- if not isinstance(row, dict):
- continue
- title = _single_line(row.get("title") or row.get("story_title"), 120)
- if not title:
- continue
- object_id = _single_line(row.get("objectID"), 40)
- url = _single_line(row.get("url"), 420) or (f"https://news.ycombinator.com/item?id={object_id}" if object_id else "")
- points = _safe_float(row.get("points"), 0)
- comments = _safe_int(row.get("num_comments"), 0, 0, 999999)
- item = {
- "source": "hackernews",
- "title": title,
- "snippet": f"Hacker News 首页热点,{int(points)} points,{comments} comments",
- "url": url,
- "score": points + comments * 0.35,
- "rank": index,
- "published": _single_line(row.get("created_at"), 80),
- "published_ts": self._news_parse_time(str(row.get("created_at") or "")),
- "created_ts": _now_ts(),
- }
- item["summary"] = item["snippet"]
- item["link"] = item["url"]
- item["key"] = self._hot_trend_key(item)
- items.append(item)
- return items
-
- async def _fetch_hot_trend_candidates(self) -> list[dict[str, Any]]:
- if not self.enable_news_daily_hot_read:
- return []
- tasks = []
- for source in self._hot_trend_source_names():
- if source == "weibo":
- tasks.append(self._fetch_weibo_hot_trends())
- elif source == "hackernews":
- tasks.append(self._fetch_hackernews_hot_trends())
- if not tasks:
- return []
- batches = await asyncio.gather(*tasks, return_exceptions=True)
- seen: set[str] = set()
- items: list[dict[str, Any]] = []
- for batch in batches:
- if not isinstance(batch, list):
- continue
- for item in batch:
- if not isinstance(item, dict):
- continue
- key = str(item.get("key") or "")
- if not key or key in seen:
- continue
- seen.add(key)
- items.append(item)
- items.sort(key=lambda item: (_safe_float(item.get("score"), 0), -_safe_float(item.get("rank"), 999)), reverse=True)
- return items[: max(3, min(30, self.news_hot_max_items))]
-
- def _format_hot_trend_candidates_for_prompt(self, hot_items: list[dict[str, Any]]) -> str:
- lines = []
- for idx, item in enumerate(hot_items[:10], 1):
- lines.append(
- f"{idx}. [{_single_line(item.get('source'), 20)}] {_single_line(item.get('title'), 80)}"
- + (f"|{_single_line(item.get('snippet'), 120)}" if _single_line(item.get("snippet"), 120) else "")
- )
- return "\n".join(lines)
-
- async def _choose_web_exploration_query(self, hot_items: list[dict[str, Any]] | None = None) -> dict[str, Any]:
- provider_id = self._task_provider(self.web_exploration_provider_id, self.news_provider_id, self.llm_provider_id)
- fallback_topics = [
- "今天有什么有趣的新鲜事",
- "最近流行的网络梗",
- "最近值得了解的科技新闻",
- "适合睡前看的冷知识",
- "最近有什么有意思的游戏或动画消息",
- ]
- hot_items = hot_items or []
- if not provider_id:
- if hot_items:
- hot = random.choice(hot_items[: min(5, len(hot_items))])
- query = _single_line(hot.get("title"), 50) or random.choice(fallback_topics)
- return {"query": query, "reason": f"从{_single_line(hot.get('source'), 20)}热点里挑了一个想了解的话题", "topic": "news"}
- return {"query": random.choice(fallback_topics), "reason": "无模型时随机探索", "topic": "general"}
- hot_context = self._format_hot_trend_candidates_for_prompt(hot_items)
- prompt = f"""
-请作为 Bot 自己,决定这会儿想上网搜索了解什么。
-
-要求:
-1. 选题要符合当前人格、状态、日程或最近聊天,可以是新闻、作品、技术、生活知识、流行梗、兴趣爱好、新鲜事物。
-2. 不要总是搜新闻;也不要总是围着用户转。Bot 可以有自己的好奇心。
-3. 如果热点候选里有符合 Bot 兴趣的内容,可以围绕它继续搜索;不合适也可以完全不选。
-4. 搜索词要具体,适合直接丢给网页搜索。
-5. 输出 JSON:query, reason, topic。topic 只能是 general 或 news。
-6. query 40字以内;reason 80字以内。
-
-【Bot 名称】
-{self.bot_name}
-
-【人格】
-{self._get_default_persona_prompt()}
-
-【当前上下文】
-{self._web_exploration_recent_context()}
-
-【公开热点候选】
-{hot_context or "暂无可用热点候选"}
-""".strip()
- raw = await self._llm_call(prompt, max_tokens=220, provider_id=provider_id, task="web_exploration_query")
- parsed = self._parse_json_object(raw)
- if not isinstance(parsed, dict):
- query = random.choice(fallback_topics)
- return {"query": query, "reason": "模型选题失败后随机探索", "topic": "general"}
- topic = str(parsed.get("topic") or "general").strip().lower()
- if topic not in {"general", "news"}:
- topic = "general"
- query = _single_line(parsed.get("query"), 60) or random.choice(fallback_topics)
- return {"query": query, "reason": _single_line(parsed.get("reason"), 120), "topic": topic}
-
- async def _summarize_web_exploration(self, query_info: dict[str, Any], results: list[dict[str, Any]]) -> dict[str, Any]:
- if not results:
- return {}
-
- def fallback_digest() -> dict[str, Any]:
- first = results[0] if results else {}
- note = fallback_note() or _single_line(first.get("snippet"), 260) or _single_line(first.get("title"), 120)
- return {
- "query": _single_line(query_info.get("query"), 80),
- "topic": _single_line(first.get("title"), 80) or _single_line(query_info.get("query"), 80) or "主动搜索",
- "note": note or "这次搜索拿到了结果,但还没整理出清晰笔记。",
- "source_title": _single_line(first.get("title"), 120),
- "source_url": _single_line(first.get("url"), 420),
- "reason": _single_line(query_info.get("reason"), 120),
- "possible_share": False,
- "results": results[:6],
- "created_ts": _now_ts(),
- "fallback": True,
- }
-
- def fallback_note() -> str:
- parts = []
- for item in results[:3]:
- title = _single_line(item.get("title"), 90)
- snippet = _single_line(item.get("snippet"), 160)
- if title and snippet:
- parts.append(f"{title}:{snippet}")
- elif title:
- parts.append(title)
- elif snippet:
- parts.append(snippet)
- return _single_line(";".join(parts), 360)
-
- provider_id = self._task_provider(self.web_exploration_provider_id, self.news_provider_id, self.llm_provider_id)
- if not provider_id:
- first = results[0]
- return {
- "query": _single_line(query_info.get("query"), 80),
- "topic": _single_line(first.get("title"), 80),
- "note": _single_line(first.get("snippet"), 220) or fallback_note(),
- "source_title": _single_line(first.get("title"), 120),
- "source_url": _single_line(first.get("url"), 420),
- "reason": _single_line(query_info.get("reason"), 120),
- "results": results[:6],
- "created_ts": _now_ts(),
- }
- lines = []
- for idx, item in enumerate(results[:8], 1):
- lines.append(
- f"{idx}. {_single_line(item.get('title'), 120)}"
- + (f"|{_single_line(item.get('snippet'), 180)}" if _single_line(item.get("snippet"), 180) else "")
- + (f"|{_single_line(item.get('url'), 160)}" if _single_line(item.get("url"), 160) else "")
- )
- prompt = f"""
-请把 Bot 这次自主网页探索整理成一条内部探索笔记。
-
-要求:
-1. 像 Bot 自己刚了解完后的留痕,不是给用户的正式回答。
-2. 不要编造搜索结果外的事实;不确定就写成“看起来/大概/还想再查”。
-3. 输出 JSON:topic, note, source_index, possible_share。
-4. topic 40字以内;note 180字以内;source_index 是 1 到 {min(8, len(results))};possible_share 是布尔值。
-
-搜索动机:{_single_line(query_info.get('reason'), 120)}
-搜索词:{_single_line(query_info.get('query'), 80)}
-
-结果:
-{chr(10).join(lines)}
-""".strip()
- raw = await self._llm_call(prompt, max_tokens=280, provider_id=provider_id, task="web_exploration_digest")
- parsed = self._parse_json_object(raw)
- if not isinstance(parsed, dict):
- return fallback_digest()
- source_index = _safe_int(parsed.get("source_index"), 1, 1, len(results[:8])) - 1
- source = results[source_index] if 0 <= source_index < len(results) else results[0]
- note = (
- _single_line(parsed.get("note") or parsed.get("summary") or parsed.get("impression") or parsed.get("content"), 360)
- or _single_line(source.get("snippet"), 260)
- or fallback_note()
- )
- return {
- "query": _single_line(query_info.get("query"), 80),
- "topic": _single_line(parsed.get("topic"), 80) or _single_line(source.get("title"), 80),
- "note": note,
- "source_title": _single_line(source.get("title"), 120),
- "source_url": _single_line(source.get("url"), 420),
- "reason": _single_line(query_info.get("reason"), 120),
- "possible_share": bool(parsed.get("possible_share", True)),
- "results": results[:6],
- "created_ts": _now_ts(),
- }
-
- async def _maybe_trigger_web_exploration(self) -> None:
- if not (self.enable_web_exploration and self.enable_web_exploration_boredom_search):
- return
- state = self.data.setdefault("web_exploration", {})
- if not isinstance(state, dict):
- self.data["web_exploration"] = {}
- state = self.data["web_exploration"]
- now = _now_ts()
- min_interval = max(1, self.web_exploration_min_interval_hours) * 3600
- if now - _safe_float(state.get("last_explore_at"), 0) < min_interval:
- return
- if now - _safe_float(state.get("last_probe_at"), 0) < 45 * 60:
- return
- if not self._bot_currently_bored_enough_for_news():
- return
- users = self.data.get("users") if isinstance(self.data.get("users"), dict) else {}
- target_users = [
- (str(uid), item)
- for uid, item in users.items()
- if isinstance(item, dict) and self._is_target_private_user(str(uid), item) and item.get("enabled", True) and item.get("umo")
- ]
- target_user = random.choice(target_users)[1] if target_users else {}
- target_umo = str((target_user.get("umo") if isinstance(target_user, dict) else "") or "")
- use_custom_search = self._custom_web_exploration_search_configured()
- search_umo = "" if use_custom_search else self._pick_available_web_search_umo(target_umo)
- if not (use_custom_search or search_umo):
- state["last_probe_at"] = now
- state["last_status"] = "web_search_disabled_or_unconfigured"
- self._save_data_sync()
- return
- if random.random() > 0.46:
- return
- state["last_probe_at"] = now
- query_info = await self._choose_web_exploration_query()
- results: list[dict[str, Any]] = []
- results = await self._run_astrbot_web_search(
- str(query_info.get("query") or ""),
- umo=search_umo,
- topic=str(query_info.get("topic") or "general"),
- usage="web_exploration",
- )
- if not results:
- error_text = _single_line(getattr(self, "_last_web_search_error", ""), 240)
- state["last_status"] = "search_failed" if error_text else "no_results"
- state["last_query"] = query_info
- state["last_explore_at"] = now
- state["last_digest"] = {
- "query": _single_line(query_info.get("query"), 80),
- "topic": _single_line(query_info.get("query"), 80) or "主动搜索",
- "note": f"搜索调用失败:{error_text}" if error_text else "这次搜索没有拿到可用结果。",
- "reason": _single_line(query_info.get("reason"), 120),
- "results": [],
- "created_ts": now,
- "no_results": not bool(error_text),
- "search_failed": bool(error_text),
- }
- self._save_data_sync()
- return
- digest = await self._summarize_web_exploration(query_info, results)
- notes = state.setdefault("notes", [])
- if not isinstance(notes, list):
- notes = []
- state["notes"] = notes
- wish = await self._build_external_event_wish(digest, source_type="web_exploration")
- if wish:
- digest["self_link"] = wish
- notes.append(
- {
- key: value
- for key, value in digest.items()
- if key not in {"results", "raw_results", "pages"}
- }
- )
- del notes[:-40]
- state["last_explore_at"] = now
- state["last_status"] = "explored"
- state["last_query"] = query_info
- state["last_digest"] = digest
- state["latest_results"] = results[:8]
- if digest.get("possible_share") and target_users:
- random.shuffle(target_users)
- for user_id, user in target_users[:3]:
- if now - _safe_float(user.get("last_seen"), 0) < max(self.idle_minutes, 90) * 60:
- continue
- if now - _safe_float(user.get("last_web_exploration_share_at"), 0) < 10 * 3600:
- continue
- if self._external_link_share_cooldown_remaining(user, now=now) > 0:
- continue
- if isinstance(wish, dict) and wish:
- if now - _safe_float(user.get("last_external_event_self_link_at"), 0) < self.external_event_self_link_cooldown_hours * 3600:
- continue
- if not wish.get("should_share"):
- continue
- decision = self._external_event_share_decision(
- user,
- digest,
- source_type="web_exploration",
- wish=wish,
- base_probability=self.web_exploration_share_probability,
- now=now,
- )
- if decision.get("duplicate") or not decision.get("should_share"):
- continue
- share_probability = max(self.web_exploration_share_probability, _safe_float(decision.get("probability"), 0.0))
- share_probability *= self.external_event_self_link_probability
- else:
- decision = self._external_event_share_decision(
- user,
- digest,
- source_type="web_exploration",
- wish={"relevance": 4, "desire": 4, "should_share": True},
- base_probability=self.web_exploration_share_probability,
- now=now,
- )
- if decision.get("duplicate") or not decision.get("should_share"):
- continue
- share_probability = self.web_exploration_share_probability
- if random.random() > max(0.0, min(1.0, share_probability)):
- continue
- self_link_motive = _single_line(wish.get("motive") if isinstance(wish, dict) else "", 180)
- self_link_tone = _single_line(wish.get("tone") if isinstance(wish, dict) else "", 60)
- self_link_boundary = _single_line(wish.get("boundary") if isinstance(wish, dict) else "", 140)
- accepted = self._offer_proactive_candidate(
- user_id,
- user,
- {
- "source": "web_exploration",
- "reason": "web_exploration_share",
- "action": "message",
- "scheduled_ts": now + random.randint(12, 70) * 60,
- "topic": _single_line(digest.get("topic"), 48) or "新发现",
- "score": max(4 if self_link_motive else 3, _safe_int(decision.get("score"), 0, 0, 100)),
- "motive": self_link_motive or "这条内容和对方可能感兴趣的东西相关",
- "context_key": "web_exploration_context",
- "context": {
- **digest,
- "share_tone": self_link_tone,
- "share_boundary": self_link_boundary,
- "share_decision": decision,
- },
- },
- )
- if accepted:
- user["web_exploration_context"] = {
- **digest,
- "share_tone": self_link_tone,
- "share_boundary": self_link_boundary,
- "share_decision": decision,
- }
- user["last_web_exploration_share_at"] = now
- self._note_external_link_candidate(user, now=now)
- if isinstance(wish, dict) and wish:
- user["last_external_event_self_link_at"] = now
- self._remember_external_event(digest, source_type="web_exploration", reason="web_exploration_share")
- break
- self._save_data_sync()
- logger.info("[PrivateCompanion] 已完成一次网页探索: %s", _single_line(digest.get("topic"), 80))
diff --git a/page_api.py b/page_api.py
index f8eb1dd..5b54dea 100644
--- a/page_api.py
+++ b/page_api.py
@@ -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]]:
diff --git a/page_api_qzone.py b/page_api_qzone.py
deleted file mode 100644
index ddada77..0000000
--- a/page_api_qzone.py
+++ /dev/null
@@ -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
diff --git a/pages/陪伴面板/app.js b/pages/陪伴面板/app.js
index 9639d04..4cff67a 100644
--- a/pages/陪伴面板/app.js
+++ b/pages/陪伴面板/app.js
@@ -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 = `QQ 空间面板脚本未加载。请刷新拓展页;若仍失败,检查 qzone-panel.js 是否被浏览器拦截。
`;
+ if (feed && !feed.innerHTML.trim()) feed.innerHTML = `该面板已从运维版移除。
`;
}
} 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 私聊主动 群聊唤醒 群主动插话";
diff --git a/pages/陪伴面板/css/qzone-mobile.css b/pages/陪伴面板/css/qzone-mobile.css
deleted file mode 100644
index d19d53b..0000000
--- a/pages/陪伴面板/css/qzone-mobile.css
+++ /dev/null
@@ -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;
- }
-}
diff --git a/pages/陪伴面板/index.html b/pages/陪伴面板/index.html
index 011fe44..92f1b41 100644
--- a/pages/陪伴面板/index.html
+++ b/pages/陪伴面板/index.html
@@ -6,7 +6,6 @@
陪伴面板
-
-