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 @@ 陪伴面板 - - diff --git a/pages/陪伴面板/js/panels/qzone-panel.js b/pages/陪伴面板/js/panels/qzone-panel.js deleted file mode 100644 index 7358ea3..0000000 --- a/pages/陪伴面板/js/panels/qzone-panel.js +++ /dev/null @@ -1,656 +0,0 @@ -window.PrivateCompanionQzonePanel = (() => { - const state = { - initialized: false, - status: null, - scope: "friends", - targetUin: "", - posts: [], - selectedId: "", - loading: false, - loaded: false, - page: 1, - pendingLikes: new Set(), - pendingDeletes: new Set(), - deleteConfirmId: "", - deleteConfirmAt: 0, - detailLoadingId: "", - context: null, - }; - - function text(value) { - return String(value ?? ""); - } - - function postById(id) { - return state.posts.find((item) => item.id === id) || null; - } - - function setNotice(message = "", tone = "info") { - const notice = document.getElementById("qzoneNotice"); - if (!notice) return; - notice.hidden = !message; - notice.textContent = message; - notice.dataset.tone = tone; - } - - function isRouteMissingError(error) { - return /未找到该路由|找不到该路由|路由不存在|route\s*(?:not\s*found|missing)|not\s*found.*route|^not\s*found$|HTTP\s*404|\b404\b/i.test(String(error?.message || "").trim()); - } - - async function qzoneFetch(paths) { - const candidates = Array.isArray(paths) ? paths : [paths]; - let lastError = null; - for (const path of candidates) { - try { - return await state.context.fetchJson(path); - } catch (error) { - lastError = error; - if (!isRouteMissingError(error)) break; - } - } - throw lastError || new Error("QQ 空间请求失败"); - } - - async function qzonePost(paths, body = {}) { - const candidates = Array.isArray(paths) ? paths : [paths]; - let lastError = null; - for (const path of candidates) { - try { - return await state.context.postJson(path, body); - } catch (error) { - lastError = error; - if (!isRouteMissingError(error)) break; - } - } - throw lastError || new Error("QQ 空间请求失败"); - } - - async function refreshCookies() { - return qzonePost([ - "/qzone/refresh_cookies", - "/qzone/refresh-cookies", - "/qzone/cookies/refresh", - "/qzone/refresh", - "/qzone/cookie/refresh", - ], {}); - } - - function renderAccount() { - const login = state.status?.login || {}; - const summary = state.status?.summary || {}; - const name = document.getElementById("qzoneAccountName"); - const meta = document.getElementById("qzoneAccountMeta"); - const accountName = login.nickname || (login.uin ? `QQ ${login.uin}` : "未绑定"); - if (name) name.textContent = accountName; - const avatar = document.getElementById("qzoneAccountAvatar"); - const avatarFallback = document.getElementById("qzoneAccountAvatarFallback"); - const avatarUrl = text(login.avatar).trim(); - if (avatar) { - if (avatarUrl) avatar.src = avatarUrl; - else avatar.removeAttribute("src"); - avatar.hidden = !avatarUrl; - } - if (avatarFallback) { - avatarFallback.hidden = Boolean(avatarUrl); - avatarFallback.textContent = Array.from(accountName.trim())[0] || "Q"; - } - const accountStatus = document.getElementById("qzoneAccountStatus"); - if (accountStatus) { - const tone = !state.status ? "idle" : (summary.enabled ? "ready" : (summary.available ? "warn" : "error")); - const label = !state.status ? "同步中" : (summary.enabled ? "已连接" : (summary.available ? "未启用" : "不可用")); - accountStatus.dataset.tone = tone; - accountStatus.textContent = label; - } - if (meta) { - meta.textContent = !state.status - ? "正在读取 QQ 空间状态" - : summary.enabled - ? `QQ 空间已启用 · ${summary.last_status || "等待操作"}` - : (summary.available ? "QQ 空间模块已加载,但整合开关未开启" : (summary.unavailable_reason || "QQ 空间模块不可用")); - } - const summaryBox = document.getElementById("qzoneQuickSummary"); - if (summaryBox) { - const imageStatus = summary.last_life_publish_generated_image_status || ""; - const imageNote = summary.last_life_publish_generated_image_note || ""; - const imageLabel = summary.last_life_publish_images > 0 - ? `${summary.last_life_publish_images} 张` - : (imageStatus ? imageStatus.replace(/^skipped:/, "跳过:").replace(/^failed:/, "失败:") : `${state.posts.length} 条`); - const referenceMeta = summary.last_life_publish_generated_image_reference - ? `参考图${summary.last_life_publish_generated_image_reference_exists ? "可用" : "不可用"}` - : ""; - const designMeta = [summary.last_life_publish_generated_image_anchor, summary.last_life_publish_generated_image_composition] - .filter(Boolean) - .join(" / "); - const imageMeta = summary.generated_image_enabled - ? ([imageNote, designMeta, referenceMeta].filter(Boolean).join(" · ") || `配图概率 ${Math.round(Number(summary.generated_image_probability || 0) * 100)}%`) - : "说说配图关闭"; - summaryBox.innerHTML = ` -
生活说说${summary.life_publish_enabled ? "开启" : "关闭"}
-
评论收件箱${summary.comment_inbox_enabled ? "开启" : "关闭"}
-
最近配图${state.context.escapeHtml(imageLabel)}
- `; - } - } - - function postAuthorName(post) { - return post.author?.nickname || post.author?.uin || "QQ空间用户"; - } - - function renderPostIdentity(post) { - const { escapeHtml } = state.context; - const author = postAuthorName(post); - const initial = Array.from(String(author).trim())[0] || "Q"; - return ` -
- -
- ${escapeHtml(author)} - ${escapeHtml(post.created_at_text || "刚刚")} -
-
- `; - } - - function renderPostMetrics(post) { - const { escapeHtml } = state.context; - return ` -
- ${escapeHtml(post.stats?.likes ?? 0)} 赞 - ${escapeHtml(post.stats?.comments ?? 0)} 评论 -
- `; - } - - function qzoneImageItems(post) { - const rawItems = Array.isArray(post?.image_items) && post.image_items.length - ? post.image_items - : (Array.isArray(post?.images) ? post.images : []); - return rawItems.map((item) => { - if (item && typeof item === "object") { - const previewUrl = text(item.preview_url || item.thumbnail_url || item.thumb_url || item.url || item.src || item.image_url).trim(); - const fullUrl = text(item.full_url || item.original_url || item.origin_url || item.raw_url || item.large_url || item.url || item.src || item.image_url).trim(); - return { previewUrl: previewUrl || fullUrl, fullUrl: fullUrl || previewUrl }; - } - const source = text(item).trim(); - return { previewUrl: source, fullUrl: source }; - }).filter((item) => item.previewUrl || item.fullUrl); - } - - function renderPreviewImage(item, post) { - const { escapeHtml } = state.context; - const author = postAuthorName(post); - const alt = `${author}的说说图片`; - const meta = ["QQ 空间图片", author, post.created_at_text || "刚刚"].filter(Boolean).join(" · "); - const previewUrl = text(item?.previewUrl).trim(); - const fullUrl = text(item?.fullUrl || previewUrl).trim(); - if (!previewUrl || !fullUrl) return ""; - return `${escapeHtml(alt)}`; - } - - function openImagePreview(image) { - if (!image || !state.context) return false; - const preview = window.PrivateCompanionDailyOutfit?.openImagePreview; - const source = image.dataset.qzonePreviewSrc || image.currentSrc || image.src || image.getAttribute("src") || ""; - const fallbackSrc = image.dataset.qzonePreviewFallbackSrc || image.currentSrc || image.src || image.getAttribute("src") || ""; - if (!preview || !source) return false; - return preview({ ...state.context, document }, { - src: source, - fallbackSrc, - alt: image.alt || "QQ 空间图片", - meta: image.dataset.qzonePreviewMeta || image.alt || "QQ 空间图片", - }); - } - - function renderFeed() { - const feed = document.getElementById("qzoneFeed"); - const meta = document.getElementById("qzoneFeedMeta"); - const feedState = document.getElementById("qzoneFeedState"); - if (!feed || !meta) return; - if (feedState) { - feedState.dataset.state = state.loading ? "loading" : (state.loaded ? "ready" : "idle"); - feedState.textContent = state.loading ? "同步中" : (state.loaded ? "已同步" : "待同步"); - } - meta.textContent = state.loading - ? "正在同步动态..." - : `${state.scope === "profile" ? (state.targetUin || "指定 QQ") : state.scope === "friends" ? "好友动态" : "我的空间"} · ${state.posts.length} 条`; - if (!state.posts.length) { - feed.innerHTML = state.loading - ? `
` - : `
暂无可显示的说说可以先刷新,或切换到指定 QQ 试试。
`; - renderDetail(); - return; - } - const { escapeHtml } = state.context; - feed.innerHTML = state.posts.map((post) => ` -
-
- ${renderPostIdentity(post)} - ${post.can_delete ? "我的说说" : "动态"} -
-

${escapeHtml(post.content || "无正文")}

- ${qzoneImageItems(post).length ? ` -
- ${qzoneImageItems(post).slice(0, 4).map((item) => renderPreviewImage(item, post)).join("")} -
- ` : ""} -
- ${renderPostMetrics(post)} -
- - - ${post.can_delete ? `` : ""} -
-
-
- `).join(""); - renderDetail(); - } - - function renderDetail() { - const empty = document.getElementById("qzoneDetailEmpty"); - const detail = document.getElementById("qzoneDetailContent"); - if (!empty || !detail) return; - const post = postById(state.selectedId); - if (!post) { - empty.hidden = false; - detail.hidden = true; - detail.innerHTML = ""; - return; - } - empty.hidden = true; - detail.hidden = false; - const { escapeHtml } = state.context; - detail.innerHTML = ` -
-
- ${renderPostIdentity(post)} -
- - ${post.can_delete ? `` : ""} -
-
-

${escapeHtml(post.content || "无正文")}

- ${qzoneImageItems(post).length ? ` -
- ${qzoneImageItems(post).map((item) => renderPreviewImage(item, post)).join("")} -
- ` : ""} - ${renderPostMetrics(post)} -
-
-
- 全部评论 - ${escapeHtml(post.comments?.length ?? 0)} 条 -
-
- ${(post.comments || []).length ? post.comments.map((comment) => ` -
- ${escapeHtml(comment.author?.nickname || comment.author?.uin || "QQ空间用户")} -

${escapeHtml(comment.content || "")}

-
- `).join("") : `
还没有评论。
`} -
-
- - -
-
- `; - const form = document.getElementById("qzoneCommentForm"); - form?.addEventListener("submit", async (event) => { - event.preventDefault(); - const input = document.getElementById("qzoneCommentInput"); - const content = input?.value || ""; - await sendComment(content); - if (input) input.value = ""; - }); - } - - async function loadStatus(force = false) { - if (state.status && !force) return state.status; - try { - state.status = await qzoneFetch(["/qzone/status", "/qzone/summary", "/qzone/state", "/qzone/health"]); - renderAccount(); - return state.status; - } catch (error) { - state.status = state.status || { login: { bound: false, uin: 0, nickname: "", avatar: "" }, summary: { enabled: false, available: false } }; - setNotice(`状态加载失败:${error.message}`, "error"); - renderAccount(); - throw error; - } - } - - async function loadFeed(force = false) { - if (state.scope === "profile" && !state.targetUin.trim()) { - state.posts = []; - state.loaded = false; - state.loading = false; - setNotice("输入 QQ 号后查看指定空间。", "warn"); - renderFeed(); - return state.posts; - } - if (state.loaded && !force) { - renderFeed(); - return state.posts; - } - state.loading = true; - setNotice("", "info"); - renderFeed(); - try { - const params = new URLSearchParams(); - params.set("scope", state.scope); - params.set("page", String(state.page || 1)); - if (state.scope === "profile" && state.targetUin.trim()) params.set("hostuin", state.targetUin.trim()); - const query = params.toString(); - const payload = await qzoneFetch([ - `/qzone/feed?${query}`, - `/qzone/feeds?${query}`, - `/qzone/list?${query}`, - ]); - state.posts = Array.isArray(payload.items) ? payload.items : []; - state.loaded = true; - if (!state.selectedId && state.posts[0]) state.selectedId = state.posts[0].id; - renderAccount(); - renderFeed(); - return state.posts; - } catch (error) { - state.posts = []; - state.loaded = false; - state.selectedId = ""; - setNotice(`动态加载失败:${error.message}`, "error"); - renderFeed(); - throw error; - } finally { - state.loading = false; - renderFeed(); - } - } - - async function openDetail(id) { - if (!id) return; - state.selectedId = id; - state.detailLoadingId = id; - renderFeed(); - try { - const encodedId = encodeURIComponent(id); - const payload = await qzoneFetch([ - `/qzone/detail?id=${encodedId}`, - `/qzone/post?id=${encodedId}`, - `/qzone/item?id=${encodedId}`, - ]); - const post = payload.post; - if (post) { - state.posts = state.posts.map((item) => (item.id === id ? post : item)); - } - } finally { - state.detailLoadingId = ""; - renderFeed(); - } - } - - async function likePost(id) { - const post = postById(id); - if (!post) return; - state.pendingLikes.add(id); - renderFeed(); - try { - const payload = await qzonePost(["/qzone/like", "/qzone/post/like"], { id }); - state.posts = state.posts.map((item) => ( - item.id === id - ? { - ...item, - liked: Boolean(payload?.liked), - stats: { - ...(item.stats || {}), - likes: Number(item.stats?.likes || 0) + (!item.liked && payload?.liked ? 1 : 0), - }, - } - : item - )); - state.context.showToast(payload?.verified ? "点赞已确认" : (payload?.verify_message || "已发送点赞请求")); - } catch (error) { - state.context.showToast(`点赞失败:${error.message}`, "error"); - } finally { - state.pendingLikes.delete(id); - renderFeed(); - } - } - - async function sendComment(content) { - const post = postById(state.selectedId); - const clean = text(content).trim(); - if (!post || !clean) return; - try { - const payload = await qzonePost(["/qzone/comment", "/qzone/post/comment"], { id: post.id, content: clean }); - if (payload?.post) { - state.posts = state.posts.map((item) => (item.id === post.id ? payload.post : item)); - } - state.context.showToast("评论已发送"); - renderFeed(); - } catch (error) { - state.context.showToast(`评论失败:${error.message}`, "error"); - } - } - - function confirmDeletePost(id, button = null) { - const now = Date.now(); - if (state.deleteConfirmId === id && now - state.deleteConfirmAt <= 6000) return true; - state.deleteConfirmId = id; - state.deleteConfirmAt = now; - if (button) { - if (!button.dataset.originalText) button.dataset.originalText = button.textContent || "删除"; - button.textContent = "再次点击删除"; - button.classList.add("is-confirming"); - window.setTimeout(() => { - if (state.deleteConfirmId === id && Date.now() - state.deleteConfirmAt >= 5900) { - state.deleteConfirmId = ""; - state.deleteConfirmAt = 0; - } - if (button.isConnected && button.dataset.originalText) { - button.textContent = button.dataset.originalText; - delete button.dataset.originalText; - button.classList.remove("is-confirming"); - } - }, 6000); - } - state.context.showToast("再次点击会删除这条说说", "warn"); - return false; - } - - async function deletePost(id, button = null) { - const cleanId = text(id).trim(); - if (!cleanId) { - state.context.showToast("没有拿到说说 ID,请刷新动态后重试", "error"); - return; - } - const post = postById(cleanId); - if (!post) { - state.context.showToast("这条说说的页面引用已失效,请刷新动态后重试", "error"); - return; - } - if (!post.can_delete) { - state.context.showToast("只能删除当前登录 QQ 自己发布的说说", "error"); - return; - } - if (state.pendingDeletes.has(cleanId)) return; - if (!confirmDeletePost(cleanId, button)) return; - state.deleteConfirmId = ""; - state.deleteConfirmAt = 0; - state.pendingDeletes.add(cleanId); - renderFeed(); - try { - state.context.showToast("正在删除说说..."); - await qzonePost(["/qzone/delete", "/qzone/post/delete"], { id: cleanId }); - state.posts = state.posts.filter((item) => item.id !== cleanId); - if (state.selectedId === cleanId) state.selectedId = state.posts[0]?.id || ""; - state.context.showToast("说说已删除"); - } catch (error) { - state.context.showToast(`删除失败:${error.message}`, "error"); - } finally { - state.pendingDeletes.delete(cleanId); - renderAccount(); - renderFeed(); - } - } - - async function publish() { - const input = document.getElementById("qzonePublishContent"); - const content = text(input?.value).trim(); - if (!content) { - state.context.showToast("说说内容不能为空", "error"); - return; - } - try { - await qzonePost(["/qzone/publish", "/qzone/post/publish", "/qzone/post"], { content }); - if (input) input.value = ""; - state.context.showToast("说说已发布"); - await loadFeed(true); - } catch (error) { - state.context.showToast(`发布失败:${error.message}`, "error"); - } - } - - function bindDeleteEvents() { - const panel = document.getElementById("panel-qzone"); - if (!panel || panel.dataset.qzoneDeleteBound === "1") return; - panel.dataset.qzoneDeleteBound = "1"; - panel.addEventListener("click", async (event) => { - const element = event.target instanceof Element ? event.target : null; - const deleteButton = element?.closest("[data-qzone-delete]"); - if (!deleteButton || !panel.contains(deleteButton)) return; - event.preventDefault(); - event.stopPropagation(); - if (typeof event.stopImmediatePropagation === "function") event.stopImmediatePropagation(); - await deletePost(deleteButton.dataset.qzoneDelete || "", deleteButton); - }, true); - } - - function bindEvents() { - const panel = document.getElementById("panel-qzone"); - if (!panel || panel.dataset.bound === "1") return; - panel.dataset.bound = "1"; - panel.addEventListener("click", async (event) => { - const element = event.target instanceof Element ? event.target : null; - const previewImage = element?.closest("[data-qzone-preview-image]"); - if (previewImage && panel.contains(previewImage)) { - event.preventDefault(); - event.stopPropagation(); - openImagePreview(previewImage); - return; - } - const like = element?.closest("[data-qzone-like]"); - if (like) { - await likePost(like.dataset.qzoneLike || ""); - return; - } - const deleteButton = element?.closest("[data-qzone-delete]"); - if (deleteButton) { - event.preventDefault(); - event.stopPropagation(); - await deletePost(deleteButton.dataset.qzoneDelete || "", deleteButton); - return; - } - const open = element?.closest("[data-qzone-open]"); - if (open) { - await openDetail(open.dataset.qzoneOpen || ""); - return; - } - const scopeButton = element?.closest("[data-qzone-scope]"); - if (scopeButton) { - state.scope = scopeButton.dataset.qzoneScope || "self"; - state.page = 1; - document.querySelectorAll("[data-qzone-scope]").forEach((item) => { - const active = item === scopeButton; - item.classList.toggle("active", active); - item.setAttribute("aria-pressed", String(active)); - }); - state.loaded = false; - try { - await loadFeed(true); - } catch (error) { - state.context.showToast(`动态加载失败:${error.message}`, "error"); - } - return; - } - }); - panel.addEventListener("keydown", (event) => { - if (event.key !== "Enter" && event.key !== " ") return; - const element = event.target instanceof Element ? event.target : null; - const previewImage = element?.closest("[data-qzone-preview-image]"); - if (!previewImage || !panel.contains(previewImage)) return; - event.preventDefault(); - event.stopPropagation(); - openImagePreview(previewImage); - }); - document.getElementById("qzoneTargetForm")?.addEventListener("submit", async (event) => { - event.preventDefault(); - const target = document.getElementById("qzoneTargetUin"); - state.targetUin = text(target?.value).trim(); - state.scope = "profile"; - state.page = 1; - document.querySelectorAll("[data-qzone-scope]").forEach((item) => { - const active = item.dataset.qzoneScope === "profile"; - item.classList.toggle("active", active); - item.setAttribute("aria-pressed", String(active)); - }); - state.loaded = false; - try { - await loadFeed(true); - } catch (error) { - state.context.showToast(`查询失败:${error.message}`, "error"); - } - }); - document.getElementById("qzonePublishForm")?.addEventListener("submit", async (event) => { - event.preventDefault(); - await publish(); - }); - document.getElementById("qzoneRefreshBtn")?.addEventListener("click", async () => { - try { - await loadStatus(true); - await loadFeed(true); - } catch (error) { - state.context.showToast(`刷新失败:${error.message}`, "error"); - } - }); - document.getElementById("qzoneRefreshCookiesBtn")?.addEventListener("click", async () => { - try { - const payload = await refreshCookies(); - state.context.showToast(`Cookies 已刷新:QQ ${payload?.uin || "未知"}`); - await loadStatus(true); - await loadFeed(true); - } catch (error) { - setNotice(`刷新 Cookies 失败:${error.message}`, "error"); - state.context.showToast(`刷新 Cookies 失败:${error.message}`, "error"); - } - }); - document.getElementById("qzoneAccountAvatar")?.addEventListener("error", (event) => { - const avatar = event.currentTarget; - const avatarFallback = document.getElementById("qzoneAccountAvatarFallback"); - avatar.hidden = true; - if (avatarFallback) avatarFallback.hidden = false; - }); - } - - async function render(context) { - state.context = context; - bindDeleteEvents(); - bindEvents(); - renderAccount(); - renderFeed(); - try { - await loadStatus(); - if (state.status?.summary?.platform_supported === false) { - state.posts = []; - state.loaded = true; - renderFeed(); - setNotice(state.status.summary.unavailable_reason || "当前平台不支持 QQ 空间。", "warn"); - return; - } - await loadFeed(); - } catch (error) { - setNotice(error.message || "QQ 空间面板初始化失败", "error"); - } - } - - return { render }; -})(); diff --git a/qzone_integration.py b/qzone_integration.py deleted file mode 100644 index 8a71b38..0000000 --- a/qzone_integration.py +++ /dev/null @@ -1,3421 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import annotations - -import asyncio -import json -import hashlib -import html -import random -import re -import time -from http.cookies import SimpleCookie -from pathlib import Path -from types import SimpleNamespace -from typing import Any -from urllib.parse import urlparse - -from astrbot.api import logger -from astrbot.api.event import AstrMessageEvent - -from .helpers import _now_ts, _safe_float, _safe_int, _single_line -from .qzone_media import QzoneIntegrationError, QzoneMediaMixin - - -class QzoneMixin(QzoneMediaMixin): - """QQ Zone integration helpers.""" - - _QZONE_COOKIE_DOMAIN = "user.qzone.qq.com" - _QZONE_COOKIE_ACTIONS = ("get_cookies", "get_credentials") - _QZONE_LOGIN_INFO_ACTIONS = ("get_login_info",) - _QZONE_ACTION_CALLER_ATTRS = ("call_action", "call_api", "call", "api_call", "send_action") - _QZONE_ACTION_OWNER_ATTRS = ( - "api", - "bot", - "client", - "adapter", - "connection", - "onebot", - "platform", - "platform_impl", - "impl", - "instance", - ) - _QZONE_COOKIE_VALUE_KEYS = ( - "cookies", - "cookie", - "cookie_text", - "cookie_str", - "cookies_str", - "data", - "result", - "retdata", - "ret_data", - "payload", - "response", - ) - _QZONE_COOKIE_SECRET_KEYS = ("p_skey", "skey", "pskey", "skey2") - _QZONE_COOKIE_DOMAIN_FALLBACKS = ( - "user.qzone.qq.com", - "qzone.qq.com", - "h5.qzone.qq.com", - "mobile.qzone.qq.com", - "taotao.qzone.qq.com", - "qun.qzone.qq.com", - "ti.qq.com", - "qq.com", - ) - - def _qzone_plugin_dir(self) -> Path: - candidates = [ - Path(__file__).resolve().parent.parent / "astrbot_plugin_qzone", - Path(self.data_dir).parent.parent / "plugins" / "astrbot_plugin_qzone", - ] - for path in candidates: - if (path / "main.py").exists(): - return path - return candidates[0] - - def _find_qzone_instance(self) -> Any | None: - return None - - def _qzone_platform_supported(self, event: AstrMessageEvent | None = None) -> bool: - platform_supports = getattr(self, "_platform_supports", None) - if event is not None and callable(platform_supports): - return bool(platform_supports("qzone", event=event)) - platform_available = getattr(self, "_platform_kind_available", None) - if callable(platform_available): - return bool(platform_available("onebot")) - return True - - @staticmethod - def _qzone_platform_unavailable_message() -> str: - return "QQ 官方机器人不支持 QQ 空间;该能力仅在 OneBot/aiocqhttp 平台可用。" - - def _qzone_available(self, event: AstrMessageEvent | None = None) -> bool: - return bool(self.enable_qzone_integration and self._qzone_platform_supported(event)) - - def _qzone_note_event_bot(self, event: AstrMessageEvent | None) -> None: - """Cache the latest OneBot connection for background Qzone jobs.""" - if event is not None and not self._qzone_platform_supported(event): - return - bot = getattr(event, "bot", None) if event is not None else None - if bot is None: - return - for candidate in self._qzone_runtime_bot_candidates(bot): - if self._qzone_runtime_bot_usable(candidate): - self._qzone_last_bot = candidate - self._qzone_clear_no_onebot_auth_failure() - return - self._qzone_last_bot = bot - - def _qzone_clear_no_onebot_auth_failure(self) -> None: - state = self._qzone_state_dict() - if not isinstance(state, dict): - return - reason = str(state.get("last_auth_failure_reason") or "") - if "没有可用的 OneBot 连接" not in reason and "未配置手动 QZONE_COOKIE" not in reason: - return - clearer = getattr(self, "_qzone_clear_auth_failure", None) - if callable(clearer): - clearer(state) - - @staticmethod - def _qzone_runtime_bot_usable(candidate: Any) -> bool: - if candidate is None: - return False - if any(callable(getattr(candidate, name, None)) for name in ("get_cookies", "get_credentials", "get_login_info")): - return True - if any(callable(getattr(candidate, name, None)) for name in QzoneMixin._QZONE_ACTION_CALLER_ATTRS): - return True - api = getattr(candidate, "api", None) - return any(callable(getattr(api, name, None)) for name in QzoneMixin._QZONE_ACTION_CALLER_ATTRS) - - def _qzone_runtime_bot_candidates(self, source: Any) -> list[Any]: - """Return likely OneBot client objects from an AstrBot platform wrapper.""" - if source is None: - return [] - candidates: list[Any] = [source] - for attr in ( - "bot", - "client", - "adapter", - "connection", - "onebot", - "platform", - "platform_impl", - "impl", - "instance", - ): - try: - value = getattr(source, attr, None) - except Exception: - value = None - if value is not None: - candidates.append(value) - api = getattr(source, "api", None) - if api is not None: - candidates.append(api) - deduped: list[Any] = [] - seen: set[int] = set() - for item in candidates: - marker = id(item) - if marker in seen: - continue - seen.add(marker) - deduped.append(item) - return deduped - - @staticmethod - def _qzone_unique_texts(items: list[str]) -> list[str]: - seen: set[str] = set() - result: list[str] = [] - for item in items: - text = str(item or "").strip() - if not text or text in seen: - continue - seen.add(text) - result.append(text) - return result - - def _qzone_cookie_domain_candidates(self, configured_domain: str = "") -> list[str]: - domain = str(configured_domain or self._QZONE_COOKIE_DOMAIN or "").strip() - candidates: list[str] = [] - if domain: - candidates.append(domain) - if "://" in domain: - parsed = urlparse(domain) - host = parsed.netloc or parsed.path - if host: - candidates.extend([host, f"https://{host}", f"https://{host}/"]) - else: - candidates.extend([f"https://{domain}", f"https://{domain}/"]) - for fallback in self._QZONE_COOKIE_DOMAIN_FALLBACKS: - candidates.extend([fallback, f"https://{fallback}", f"https://{fallback}/"]) - return self._qzone_unique_texts(candidates) - - def _qzone_iter_action_callers(self, bot: Any) -> list[Any]: - callers: list[Any] = [] - seen_owners: set[int] = set() - seen_callers: set[int] = set() - owners: list[Any] = [bot] - index = 0 - while index < len(owners): - owner = owners[index] - index += 1 - if owner is None: - continue - marker = id(owner) - if marker in seen_owners: - continue - seen_owners.add(marker) - for attr in self._QZONE_ACTION_CALLER_ATTRS: - try: - caller = getattr(owner, attr, None) - except Exception: - caller = None - if callable(caller) and id(caller) not in seen_callers: - seen_callers.add(id(caller)) - callers.append(caller) - for attr in self._QZONE_ACTION_OWNER_ATTRS: - try: - nested = getattr(owner, attr, None) - except Exception: - nested = None - if nested is not None and id(nested) not in seen_owners: - owners.append(nested) - return callers - - @staticmethod - def _qzone_invoke_action_callable(callable_obj: Any, action: str, params: dict[str, Any]) -> Any: - attempts: list[tuple[tuple[Any, ...], dict[str, Any]]] = [] - if action: - envelope = dict(params) - attempts.extend( - [ - ((action,), dict(params)), - ((), {"action": action, **params}), - ((action, params), {}), - ((action,), {"params": params}), - ((), {"action": action, "params": params}), - (({"action": action, "params": envelope},), {}), - (({"action": action, "data": envelope},), {}), - (({"action": action, "payload": envelope},), {}), - (({"api": action, "params": envelope},), {}), - (({"api": action, "data": envelope},), {}), - ((action,), {"data": params}), - ((), {"action": action, "data": params}), - ((action,), {"payload": params}), - ((), {"action": action, "payload": params}), - ] - ) - else: - attempts.extend( - [ - ((), dict(params)), - ((params,), {}), - ((), {"params": params}), - ((), {"data": params}), - ((), {"payload": params}), - ] - ) - last_error: TypeError | None = None - for args, kwargs in attempts: - try: - return callable_obj(*args, **kwargs) - except TypeError as exc: - last_error = exc - continue - if last_error is not None: - raise last_error - return callable_obj(action, **params) if action else callable_obj(**params) - - async def _qzone_call_onebot_action(self, bot: Any, action: str, **params: Any) -> Any: - direct = getattr(bot, action, None) - if callable(direct): - result = self._qzone_invoke_action_callable(direct, "", params) - return await result if hasattr(result, "__await__") else result - last_error: Exception | None = None - for caller in self._qzone_iter_action_callers(bot): - try: - result = self._qzone_invoke_action_callable(caller, action, params) - return await result if hasattr(result, "__await__") else result - except Exception as exc: - last_error = exc - continue - if last_error is not None: - raise last_error - raise RuntimeError("OneBot client does not expose get_cookies/get_credentials") - - def _qzone_find_runtime_bot(self) -> Any | None: - bot = getattr(self, "_qzone_last_bot", None) - if self._qzone_runtime_bot_usable(bot): - return bot - context = getattr(self, "context", None) - if context is not None: - try: - platform = context.get_platform("aiocqhttp") - except Exception: - platform = None - if platform is not None: - direct_bot = getattr(platform, "bot", None) - if self._qzone_runtime_bot_usable(direct_bot): - self._qzone_last_bot = direct_bot - return direct_bot - for candidate in self._qzone_runtime_bot_candidates(platform): - if self._qzone_runtime_bot_usable(candidate): - self._qzone_last_bot = candidate - return candidate - for candidate in self._qzone_runtime_bot_candidates(bot): - if self._qzone_runtime_bot_usable(candidate): - self._qzone_last_bot = candidate - return candidate - platform_manager = getattr(getattr(self, "context", None), "platform_manager", None) - platform_lists: list[Any] = [] - for attr in ("platform_insts", "platform_instances", "instances", "platforms"): - try: - value = getattr(platform_manager, attr, None) - except Exception: - value = None - if value: - platform_lists.append(value.values() if isinstance(value, dict) else value) - for platforms in platform_lists: - try: - iterable = list(platforms or []) - except Exception: - iterable = [] - for inst in iterable: - for candidate in self._qzone_runtime_bot_candidates(inst): - if self._qzone_runtime_bot_usable(candidate): - self._qzone_last_bot = candidate - return candidate - return None - - async def _qzone_try_direct_cookie_fetch(self, bot: Any, domain: str) -> dict[str, str]: - merged: dict[str, str] = {} - login_uin = await self._qzone_fetch_login_uin(bot) - for action in self._QZONE_COOKIE_ACTIONS: - for candidate_domain in self._qzone_cookie_domain_candidates(domain): - for params in ({"domain": candidate_domain}, {}): - try: - result = await asyncio.wait_for(self._qzone_call_onebot_action(bot, action, **params), timeout=8.0) - except Exception: - continue - cookie_text = self._qzone_extract_cookie_text(result) - if not cookie_text: - continue - cookies = self._qzone_parse_cookie_text(cookie_text) - if login_uin and not self._qzone_normalize_uin(cookies): - cookies["uin"] = f"o{login_uin}" - cookies["p_uin"] = f"o{login_uin}" - merged.update(cookies) - if self._qzone_cookie_has_identity_and_secret(merged): - return merged - return merged - - @staticmethod - def _qzone_gtk(p_skey: str) -> str: - hash_val = 5381 - for ch in str(p_skey or ""): - hash_val += (hash_val << 5) + ord(ch) - return str(hash_val & 0x7FFFFFFF) - - @staticmethod - def _qzone_normalize_cookie_fields(cookies: dict[str, Any]) -> dict[str, str]: - aliases = { - "pskey": "p_skey", - "p-skey": "p_skey", - "p_skey": "p_skey", - "p_uin": "p_uin", - "ptui_loginuin": "ptui_loginuin", - "csrf-token": "csrf_token", - "csrf_token": "csrf_token", - "bkn": "g_tk", - "gtk": "g_tk", - } - normalized: dict[str, str] = {} - for key, value in (cookies or {}).items(): - if value in (None, ""): - continue - original = str(key).strip() - if not original: - continue - text = str(value).strip().strip('"') - if not text: - continue - alias_key = original.lower().replace("-", "_") - canonical = aliases.get(alias_key, aliases.get(original.lower(), original)) - normalized.setdefault(original, text) - normalized.setdefault(canonical, text) - if "uin" in normalized and "p_uin" not in normalized: - normalized["p_uin"] = normalized["uin"] - if "p_uin" in normalized and "uin" not in normalized: - normalized["uin"] = normalized["p_uin"] - return normalized - - @classmethod - def _qzone_parse_cookie_text(cls, cookie_text: str) -> dict[str, str]: - raw = str(cookie_text or "").strip() - if not raw: - return {} - if raw.lower().startswith("cookie:"): - raw = raw.split(":", 1)[1].strip() - raw = raw.replace("\r", ";").replace("\n", ";") - if raw.startswith(("{", "[")): - try: - payload = json.loads(raw) - except Exception: - payload = None - if isinstance(payload, dict): - return cls._qzone_normalize_cookie_fields(payload) - try: - return cls._qzone_normalize_cookie_fields({key: morsel.value for key, morsel in SimpleCookie(raw).items()}) - except Exception: - parsed: dict[str, str] = {} - for part in raw.split(";"): - if "=" not in part: - continue - key, value = part.split("=", 1) - key = key.strip() - if key: - parsed[key] = value.strip().strip('"') - return cls._qzone_normalize_cookie_fields(parsed) - - @staticmethod - def _qzone_cookie_header(cookies: dict[str, Any]) -> str: - return "; ".join(f"{key}={value}" for key, value in (cookies or {}).items() if key and value not in (None, "")) - - def _qzone_extract_cookie_text(self, payload: Any, *, _depth: int = 0, _seen: set[int] | None = None) -> str: - if _seen is None: - _seen = set() - if payload is None or _depth > 8: - return "" - if isinstance(payload, bytes): - try: - payload = payload.decode("utf-8") - except Exception: - return "" - if isinstance(payload, str): - text = payload.strip() - if text.startswith(("{", "[")): - try: - return self._qzone_extract_cookie_text(json.loads(text), _depth=_depth + 1, _seen=_seen) - except Exception: - pass - return text if "=" in text and re.search(r"\b(?:uin|p_uin|skey|p_skey|pskey|g_tk|gtk|bkn)\s*=", text, re.I) else "" - if isinstance(payload, (list, tuple)): - parts = [self._qzone_extract_cookie_text(item, _depth=_depth + 1, _seen=_seen) for item in payload] - cookies: dict[str, str] = {} - for part in parts: - cookies.update(self._qzone_parse_cookie_text(part)) - return self._qzone_cookie_header(cookies) - if not isinstance(payload, dict): - return "" - obj_id = id(payload) - if obj_id in _seen: - return "" - _seen.add(obj_id) - name = payload.get("name") or payload.get("key") - value = payload.get("value") - if name and value not in (None, ""): - return f"{name}={value}" - cookie_keys = set(self._QZONE_COOKIE_VALUE_KEYS) - allow = { - "uin", - "p_uin", - "ptui_loginuin", - "luin", - "skey", - "p_skey", - "pskey", - "skey2", - "pt4_token", - "pt_key", - "pt_login_sig", - "clientkey", - "superkey", - "qzonetoken", - "qm_keyst", - "qm_sid", - "o_cookie", - "uin_cookie", - "rv2", - "ptcz", - "lskey", - "ldw", - "g_tk", - "gtk", - "bkn", - "csrf_token", - "qqmusic_key", - } - cookies = { - str(key): value - for key, value in payload.items() - if str(key).lower().replace("-", "_") in allow and value not in (None, "") - } - parts = [self._qzone_cookie_header(self._qzone_normalize_cookie_fields(cookies))] if cookies else [] - for key in cookie_keys: - if key in payload: - text = self._qzone_extract_cookie_text(payload.get(key), _depth=_depth + 1, _seen=_seen) - if text: - parts.append(text) - for value in payload.values(): - if isinstance(value, (dict, list, tuple, str, bytes)): - text = self._qzone_extract_cookie_text(value, _depth=_depth + 1, _seen=_seen) - if text: - parts.append(text) - merged: dict[str, str] = {} - for part in parts: - merged.update(self._qzone_parse_cookie_text(part)) - return self._qzone_cookie_header(merged) - - @staticmethod - def _qzone_normalize_uin(cookies: dict[str, Any]) -> int: - for key in ("uin", "p_uin", "ptui_loginuin", "luin"): - raw = str(cookies.get(key) or "").strip().lstrip("oO") - if raw.isdigit(): - return int(raw) - return 0 - - def _qzone_cookie_has_identity_and_secret(self, cookies: dict[str, Any]) -> bool: - normalized = self._qzone_normalize_cookie_fields(cookies or {}) - return bool( - self._qzone_normalize_uin(normalized) - and any(str(normalized.get(key) or "").strip() for key in self._QZONE_COOKIE_SECRET_KEYS) - ) - - def _qzone_note_cookie_fetch_status( - self, - status: str, - *, - cookies: dict[str, Any] | None = None, - ctx: dict[str, Any] | None = None, - reason: str = "", - ) -> None: - try: - state = self.data.setdefault("qzone_integration", {}) - if not isinstance(state, dict): - self.data["qzone_integration"] = {} - state = self.data["qzone_integration"] - source = ctx.get("cookies") if isinstance(ctx, dict) else cookies - normalized = self._qzone_normalize_cookie_fields(source or {}) - state["last_cookie_fetch_status"] = _single_line(status, 40) - state["last_cookie_fetch_at"] = _now_ts() - state["last_cookie_fetch_has_uin"] = bool(self._qzone_normalize_uin(normalized)) - state["last_cookie_fetch_has_skey"] = bool(normalized.get("skey")) - state["last_cookie_fetch_has_p_skey"] = bool(normalized.get("p_skey") or normalized.get("pskey")) - if isinstance(ctx, dict) and ctx.get("uin"): - state["last_cookie_fetch_uin"] = str(ctx.get("uin")) - if reason: - state["last_cookie_fetch_reason"] = _single_line(reason, 160) - elif status == "ok": - state.pop("last_cookie_fetch_reason", None) - if callable(getattr(self, "_save_data_sync", None)): - self._save_data_sync() - except Exception: - logger.debug("[PrivateCompanion] QQ 空间 Cookie 状态记录失败", exc_info=True) - - async def _qzone_fetch_login_uin(self, bot: Any) -> int: - for action in self._QZONE_LOGIN_INFO_ACTIONS: - try: - payload = await asyncio.wait_for(self._qzone_call_onebot_action(bot, action), timeout=5.0) - except Exception: - continue - if isinstance(payload, str) and payload.strip().startswith(("{", "[")): - try: - payload = json.loads(payload) - except Exception: - pass - candidates: list[Any] = [] - if isinstance(payload, dict): - candidates.extend( - [ - payload.get("user_id"), - payload.get("uin"), - payload.get("qq"), - payload.get("self_id"), - ] - ) - for key in ("data", "result", "retdata", "payload", "response"): - nested = payload.get(key) - if isinstance(nested, dict): - candidates.extend([nested.get("user_id"), nested.get("uin"), nested.get("qq"), nested.get("self_id")]) - for value in candidates: - cleaned = str(value or "").strip().lstrip("oO") - if cleaned.isdigit(): - return int(cleaned) - return 0 - - def _qzone_context_from_cookies(self, cookies_str: str) -> dict[str, Any]: - parsed = self._qzone_parse_cookie_text(cookies_str) - uin = self._qzone_normalize_uin(parsed) - if not uin: - raise RuntimeError("Cookie 中缺少合法 uin") - p_skey = parsed.get("p_skey") or parsed.get("pskey") or "" - skey = parsed.get("skey") or "" - existing_gtk = str(parsed.get("g_tk") or parsed.get("gtk") or parsed.get("bkn") or parsed.get("csrf_token") or "") - secret = p_skey or skey or parsed.get("skey2") or "" - gtk = self._qzone_gtk(secret) if secret else (existing_gtk if existing_gtk.isdigit() else "") - if not gtk: - raise RuntimeError("Cookie 中缺少 p_skey/skey,无法计算 g_tk") - cookies = {**parsed, "uin": f"o{uin}"} - if skey: - cookies["skey"] = skey - if p_skey: - cookies["p_skey"] = p_skey - return { - "uin": int(uin), - "skey": skey, - "p_skey": p_skey, - "qzonetoken": parsed.get("qzonetoken") or parsed.get("qzone_token") or "", - "gtk": gtk, - "cookies": cookies, - "cookie_header": self._qzone_cookie_header(cookies), - } - - async def _qzone_get_cookies(self, event: AstrMessageEvent | None = None) -> str: - if not self._qzone_platform_supported(event): - raise QzoneIntegrationError("平台不支持", self._qzone_platform_unavailable_message()) - manual_cookie = str(getattr(self, "qzone_cookie", "") or "").strip() - if manual_cookie: - try: - ctx = self._qzone_context_from_cookies(manual_cookie) - except Exception as exc: - self._qzone_note_cookie_fetch_status("manual_failed", cookies=self._qzone_parse_cookie_text(manual_cookie), reason=str(exc)) - raise RuntimeError( - "手动 QZONE_COOKIE 不可用:" - f"{_single_line(exc, 120)};" - "需包含 uin/p_uin 与 p_skey 或 skey,可从已登录 QQ 空间的浏览器请求头 Cookie 复制" - ) from exc - logger.debug("[PrivateCompanion] QQ 空间使用手动 QZONE_COOKIE: uin=%s", ctx.get("uin")) - self._qzone_note_cookie_fetch_status("manual_ok", ctx=ctx) - return ctx["cookie_header"] - bot = getattr(event, "bot", None) if event is not None else None - if bot is not None: - usable_bot = None - for candidate in self._qzone_runtime_bot_candidates(bot): - if self._qzone_runtime_bot_usable(candidate): - usable_bot = candidate - break - bot = usable_bot or bot - if bot is None or not self._qzone_runtime_bot_usable(bot): - bot = self._qzone_find_runtime_bot() - if bot is not None: - self._qzone_last_bot = bot - if bot is None: - self._qzone_note_cookie_fetch_status("failed", reason="没有可用的 OneBot 连接,且未配置手动 QZONE_COOKIE") - raise RuntimeError( - "没有可用的 OneBot 连接,且未配置手动 QZONE_COOKIE;" - "请在配置页填写浏览器 QQ 空间 Cookie,或确认 OneBot 已连接并支持 get_cookies/get_credentials" - ) - merged = await self._qzone_try_direct_cookie_fetch(bot, self._QZONE_COOKIE_DOMAIN) - if self._qzone_cookie_has_identity_and_secret(merged): - cookie_text = self._qzone_cookie_header(self._qzone_normalize_cookie_fields(merged)) - ctx = self._qzone_context_from_cookies(cookie_text) - logger.debug("[PrivateCompanion] QQ 空间自动获取 Cookie 成功: uin=%s", ctx.get("uin")) - self._qzone_note_cookie_fetch_status("ok", ctx=ctx) - return ctx["cookie_header"] - self._qzone_note_cookie_fetch_status("failed", cookies=merged) - raise RuntimeError( - "获取 QQ 空间 Cookie 失败" - f"(uin={'有' if self._qzone_normalize_uin(merged) else '无'}" - f",skey={'有' if bool(merged.get('skey')) else '无'}" - f",p_skey={'有' if bool(merged.get('p_skey') or merged.get('pskey')) else '无'});" - "可改填手动 QZONE_COOKIE,需包含 uin/p_uin 与 p_skey 或 skey" - ) - - @staticmethod - def _qzone_response_object_candidates(raw: str) -> list[str]: - source = str(raw or "") - candidates: list[str] = [] - for start, char in enumerate(source): - if char != "{": - continue - depth = 0 - quote = "" - escaped = False - for index in range(start, len(source)): - current = source[index] - if quote: - if escaped: - escaped = False - elif current == "\\": - escaped = True - elif current == quote: - quote = "" - continue - if current in {"'", '"'}: - quote = current - continue - if current == "{": - depth += 1 - continue - if current == "}": - depth -= 1 - if depth == 0: - candidates.append(source[start : index + 1]) - break - if len(candidates) >= 24: - break - return candidates - - @staticmethod - def _qzone_load_response_payload(payload: str) -> dict[str, Any]: - normalized = str(payload or "").replace("undefined", "null") - try: - parsed = json.loads(normalized) - except Exception: - try: - relaxed = re.sub(r",\s*([}\]])", r"\1", normalized) - relaxed = re.sub(r"([{,]\s*)([A-Za-z_$][\w$]*)\s*:", r'\1"\2":', relaxed) - parsed = json.loads(relaxed) - except Exception: - import json5 # type: ignore - - parsed = json5.loads(normalized) - if isinstance(parsed, dict): - return parsed - return {"code": -1, "message": "接口响应不是对象"} - - @staticmethod - def _qzone_parse_response(text: str) -> dict[str, Any]: - raw = str(text or "") - if not raw.strip(): - return {"code": -1, "message": "接口返回空响应"} - candidates = QzoneMixin._qzone_response_object_candidates(raw) - if not candidates: - return {"code": -1, "message": "接口响应缺少 JSON"} - - def normalize(parsed: dict[str, Any]) -> dict[str, Any]: - if isinstance(parsed.get("data"), dict): - nested = dict(parsed.get("data") or {}) - nested.setdefault("_raw_code", parsed.get("code", parsed.get("ret"))) - nested.setdefault("_raw_message", parsed.get("message") or parsed.get("msg")) - return nested - return parsed - - first_object: dict[str, Any] | None = None - last_error = "" - response_keys = {"code", "ret", "message", "msg", "data", "subcode"} - for payload in candidates: - try: - parsed = QzoneMixin._qzone_load_response_payload(payload) - except Exception as exc: - last_error = _single_line(exc, 80) - continue - if not isinstance(parsed, dict): - continue - if first_object is None: - first_object = parsed - if response_keys & set(parsed): - return normalize(parsed) - if first_object is not None: - return normalize(first_object) - return {"code": -1, "message": f"JSON 解析失败:{last_error or '没有可解析对象'}"} - - async def _qzone_request( - self, - event: AstrMessageEvent | None, - method: str, - url: str, - *, - params: dict[str, Any] | None = None, - data: dict[str, Any] | None = None, - headers: dict[str, str] | None = None, - timeout_seconds: float = 20.0, - cookie_header: str | None = None, - ) -> dict[str, Any]: - import aiohttp - - if cookie_header is None: - cookie_header = await self._qzone_get_cookies(event) - ctx = self._qzone_context_from_cookies(cookie_header) - parsed_url = urlparse(url) - origin = f"{parsed_url.scheme}://{parsed_url.netloc}" if parsed_url.scheme and parsed_url.netloc else "https://user.qzone.qq.com" - request_headers = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36", - "Cookie": ctx["cookie_header"], - "Referer": f"https://user.qzone.qq.com/{ctx['uin']}", - "Origin": "https://user.qzone.qq.com", - "Host": parsed_url.netloc or "user.qzone.qq.com", - "Connection": "keep-alive", - } - if headers: - request_headers.update(headers) - timeout = aiohttp.ClientTimeout(total=timeout_seconds) - async with aiohttp.ClientSession(timeout=timeout, headers=request_headers) as session: - async with session.request(method, url, params=params, data=data) as response: - text = await response.text() - parsed = self._qzone_parse_response(text) - parsed.setdefault("_http_status", response.status) - if parsed.get("message") == "接口返回空响应": - parsed["message"] = f"接口返回空响应(HTTP {response.status})" - if response.status == 403 and parsed.get("code") in {-1, None}: - parsed["message"] = "无权限访问 QQ 空间或 Cookie 已失效" - return parsed - - @staticmethod - def _qzone_norm_key(key: Any) -> str: - return str(key or "").strip().lower().replace("-", "_") - - @classmethod - def _qzone_comment_content(cls, item: dict[str, Any]) -> str: - normalized = {cls._qzone_norm_key(key): value for key, value in (item or {}).items()} - raw = "" - for key in ("content", "comment", "text", "msg", "con", "html"): - value = normalized.get(key) - if value not in (None, ""): - raw = str(value) - break - if not raw: - return "" - cleaned = html.unescape(re.sub(r"<[^>]+>", "", raw)) - cleaned = re.sub(r"\s+", " ", cleaned).strip() - return _single_line(cleaned, 180) - - @classmethod - def _qzone_comment_identity(cls, item: dict[str, Any]) -> tuple[int, str]: - normalized = {cls._qzone_norm_key(key): value for key, value in (item or {}).items()} - raw_uin = str(normalized.get("uin") or normalized.get("user_uin") or normalized.get("qq") or normalized.get("uin_str") or "").strip().lstrip("oO") - uin = _safe_int(raw_uin, 0, 0) - name = "" - for key in ("name", "nickname", "nick", "user_name", "username"): - value = normalized.get(key) - if value not in (None, ""): - name = _single_line(value, 40) - break - return uin, name - - @classmethod - def _qzone_comment_time(cls, item: dict[str, Any]) -> float: - normalized = {cls._qzone_norm_key(key): value for key, value in (item or {}).items()} - for key in ("create_time", "created_time", "time", "timestamp", "abstime", "pubtime"): - value = normalized.get(key) - if value not in (None, ""): - return _safe_float(value, 0) - return 0.0 - - @classmethod - def _qzone_comment_id(cls, post_tid: str, item: dict[str, Any]) -> str: - normalized = {cls._qzone_norm_key(key): value for key, value in (item or {}).items()} - for key in ("commentid", "comment_id", "cid", "id", "tid", "replyid", "reply_id", "cellid", "rootid"): - value = normalized.get(key) - if value not in (None, ""): - return f"{post_tid or 'post'}:{_single_line(value, 80)}" - return cls._qzone_comment_fingerprint(post_tid, item) - - @classmethod - def _qzone_comment_legacy_fallback_id(cls, post_tid: str, item: dict[str, Any]) -> str: - uin, name = cls._qzone_comment_identity(item) - content = cls._qzone_comment_content(item) - created = cls._qzone_comment_time(item) - digest = hashlib.sha1(f"{post_tid}|{uin}|{name}|{content}|{created}".encode("utf-8", "ignore")).hexdigest()[:20] - return f"{post_tid or 'post'}:sha1:{digest}" - - @classmethod - def _qzone_comment_fingerprint(cls, post_tid: str, item: dict[str, Any]) -> str: - uin, name = cls._qzone_comment_identity(item) - content = cls._qzone_comment_content(item) - author = str(uin or "").strip() - if not author: - author = re.sub(r"\s+", "", _single_line(name, 40).lower()) or "unknown" - normalized_content = re.sub(r"\s+", "", _single_line(content, 180)).lower() - digest = hashlib.sha1(f"{post_tid or 'post'}|{author}|{normalized_content}".encode("utf-8", "ignore")).hexdigest()[:20] - return f"{post_tid or 'post'}:fp:{digest}" - - @classmethod - def _qzone_looks_like_comment(cls, item: Any) -> bool: - if not isinstance(item, dict): - return False - if not cls._qzone_comment_content(item): - return False - normalized = {cls._qzone_norm_key(key) for key in item.keys()} - identity_keys = { - "uin", - "user_uin", - "qq", - "name", - "nickname", - "nick", - "commentid", - "comment_id", - "cid", - "replyid", - "reply_id", - "create_time", - "created_time", - "abstime", - } - return bool(normalized & identity_keys) - - @classmethod - def _qzone_collect_comment_items( - cls, - payload: Any, - *, - _depth: int = 0, - _inside_comment_branch: bool = False, - ) -> list[dict[str, Any]]: - if payload is None or _depth > 5: - return [] - if isinstance(payload, list): - items: list[dict[str, Any]] = [] - for entry in payload: - if cls._qzone_looks_like_comment(entry): - items.append(entry) - elif isinstance(entry, (dict, list)): - items.extend( - cls._qzone_collect_comment_items( - entry, - _depth=_depth + 1, - _inside_comment_branch=_inside_comment_branch, - ) - ) - return items - if not isinstance(payload, dict): - return [] - items: list[dict[str, Any]] = [] - if _inside_comment_branch and cls._qzone_looks_like_comment(payload): - return [payload] - for key, value in payload.items(): - norm = cls._qzone_norm_key(key) - is_comment_branch = _inside_comment_branch or any(token in norm for token in ("comment", "reply")) - if not is_comment_branch: - continue - if cls._qzone_looks_like_comment(value): - items.append(value) - elif isinstance(value, (dict, list)): - items.extend( - cls._qzone_collect_comment_items( - value, - _depth=_depth + 1, - _inside_comment_branch=True, - ) - ) - return items - - @classmethod - def _qzone_parse_comments_from_msg(cls, msg: dict[str, Any]) -> list[Any]: - post_tid = str(msg.get("tid") or "") - seen: set[str] = set() - comments: list[Any] = [] - for item in cls._qzone_collect_comment_items(msg): - if not isinstance(item, dict): - continue - content = cls._qzone_comment_content(item) - if not content: - continue - comment_id = cls._qzone_comment_id(post_tid, item) - if comment_id in seen: - continue - seen.add(comment_id) - uin, name = cls._qzone_comment_identity(item) - comment_key = cls._qzone_comment_fingerprint(post_tid, item) - comments.append( - SimpleNamespace( - comment_id=comment_id, - comment_key=comment_key, - comment_legacy_id=cls._qzone_comment_legacy_fallback_id(post_tid, item), - uin=uin, - name=name, - content=content, - create_time=cls._qzone_comment_time(item), - raw=item, - ) - ) - comments.sort(key=lambda item: _safe_float(getattr(item, "create_time", 0), 0)) - return comments - - def _qzone_parse_feeds(self, msglist: list[Any]) -> list[Any]: - posts: list[Any] = [] - for msg in msglist: - if not isinstance(msg, dict): - continue - images: list[str] = [] - for image in msg.get("pic", []) if isinstance(msg.get("pic"), list) else []: - if not isinstance(image, dict): - continue - for key in ("url2", "url3", "url1", "smallurl"): - raw = image.get(key) - if raw: - images.append(str(raw)) - break - for video in msg.get("video", []) if isinstance(msg.get("video"), list) else []: - if isinstance(video, dict) and (video.get("url1") or video.get("pic_url")): - images.append(str(video.get("url1") or video.get("pic_url"))) - posts.append( - SimpleNamespace( - tid=str(msg.get("tid") or ""), - uin=int(msg.get("uin") or 0), - name=str(msg.get("name") or ""), - text=str(msg.get("content") or "").strip(), - rt_con=str((msg.get("rt_con") or {}).get("content") or "") if isinstance(msg.get("rt_con"), dict) else "", - images=images, - comments=self._qzone_parse_comments_from_msg(msg), - create_time=msg.get("created_time") or 0, - appid=str(msg.get("appid") or "311"), - typeid=str(msg.get("typeid") or msg.get("type") or "0"), - abstime=_safe_int(msg.get("created_time") or msg.get("abstime"), 0, 0), - fid=str(msg.get("tid") or msg.get("fid") or ""), - unikey=str(msg.get("unikey") or msg.get("likeKey") or msg.get("like_key") or ""), - curkey=str(msg.get("curkey") or msg.get("curlikekey") or msg.get("likeKey") or msg.get("like_key") or ""), - raw=msg, - status="approved", - ) - ) - return posts - - @staticmethod - def _qzone_post_value(post: Any, key: str, default: Any = "") -> Any: - value = getattr(post, key, None) - if value not in (None, ""): - return value - raw = getattr(post, "raw", None) - if isinstance(raw, dict): - value = raw.get(key) - if value not in (None, ""): - return value - return default - - def _qzone_post_like_url(self, post: Any, *, uin: str, tid: str) -> str: - raw = getattr(post, "raw", None) - for key in ("unikey", "curkey", "curlikekey", "likeKey", "like_key", "url"): - value = getattr(post, key, None) - if value not in (None, ""): - return str(value) - if isinstance(raw, dict) and raw.get(key) not in (None, ""): - return str(raw.get(key)) - html_text = str(raw.get("html") or "") if isinstance(raw, dict) else "" - if html_text: - for attr in ("data-unikey", "data-curkey", "unikey", "curkey"): - match = re.search(rf"""{re.escape(attr)}\s*=\s*["']([^"']+)["']""", html_text, flags=re.IGNORECASE) - if match: - return html.unescape(match.group(1)).strip() - return f"https://user.qzone.qq.com/{uin}/mood/{tid}" - - async def _qzone_query_feeds( - self, - event: AstrMessageEvent | None = None, - *, - target_id: str | None = None, - pos: int = 0, - num: int = 1, - with_detail: bool = False, - cookie_header: str | None = None, - ) -> list[Any]: - if cookie_header is None: - cookie_header = await self._qzone_get_cookies(event) - ctx = self._qzone_context_from_cookies(cookie_header) - target = _single_line(target_id, 40) - if not target: - target = str(ctx["uin"]) - payload = await self._qzone_request( - event, - "GET", - "https://user.qzone.qq.com/proxy/domain/taotao.qq.com/cgi-bin/emotion_cgi_msglist_v6", - params={ - "g_tk": ctx["gtk"], - "uin": target, - "ftype": 0, - "sort": 0, - "pos": max(0, int(pos or 0)), - "num": max(1, int(num or 1)), - "replynum": 100, - "callback": "_preloadCallback", - "code_version": 1, - "format": "json", - "need_comment": 1 if with_detail else 0, - "need_private_comment": 1 if with_detail else 0, - }, - cookie_header=cookie_header, - ) - code = payload.get("code", 0) - if code not in {0, "0"}: - raise RuntimeError(_single_line(payload.get("message") or payload.get("msg") or f"查询失败 code={code}", 160)) - msglist = payload.get("msglist") or [] - if not isinstance(msglist, list): - msglist = [] - return self._qzone_parse_feeds(msglist) - - async def _qzone_verify_like_post( - self, - event: AstrMessageEvent | None, - post: Any, - *, - cookie_header: str, - target_liked: bool = True, - ) -> dict[str, Any]: - tid = str(getattr(post, "tid", "") or "") - uin = str(getattr(post, "uin", "") or "") - fid = str(self._qzone_post_value(post, "fid", tid) or tid) - if not tid or not uin: - return {"verified": False, "liked": None, "message": "缺少说说 tid 或 uin,无法反查点赞状态"} - for attempt, delay in enumerate((0.0, 0.45, 1.2), start=1): - if delay > 0: - await asyncio.sleep(delay) - try: - feeds = await self._qzone_query_feeds( - event, - target_id=uin, - pos=0, - num=10, - with_detail=False, - cookie_header=cookie_header, - ) - except Exception as exc: - if attempt >= 3: - return {"verified": False, "liked": None, "message": f"点赞反查失败:{_single_line(exc, 120)}"} - continue - for feed in feeds: - feed_tid = str(getattr(feed, "tid", "") or "") - feed_fid = str(self._qzone_post_value(feed, "fid", feed_tid) or feed_tid) - if (tid and feed_tid == tid) or (fid and feed_fid == fid): - liked = bool(getattr(feed, "liked", False)) - try: - setattr(post, "liked", liked) - except Exception: - pass - if liked == bool(target_liked): - return {"verified": True, "liked": liked, "message": "已反查到点赞状态"} - if attempt >= 3: - return { - "verified": False, - "liked": liked, - "message": "点赞请求已受理,但最近动态反查到的状态仍未变化", - } - if attempt >= 3: - return {"verified": False, "liked": None, "message": "点赞请求已受理,但最近动态中暂未反查到这条说说"} - return {"verified": False, "liked": None, "message": "点赞请求已受理,但暂未完成反查"} - - async def _qzone_like_post(self, event: AstrMessageEvent | None, post: Any) -> dict[str, Any]: - cookie_header = await self._qzone_get_cookies(event) - ctx = self._qzone_context_from_cookies(cookie_header) - tid = str(getattr(post, "tid", "") or "") - uin = str(getattr(post, "uin", "") or "") - if not tid or not uin: - raise RuntimeError("说说 tid 或 uin 为空,无法点赞") - like_url = self._qzone_post_like_url(post, uin=uin, tid=tid) - curkey = str(self._qzone_post_value(post, "curkey", "") or "") or like_url - unikey = str(self._qzone_post_value(post, "unikey", "") or "") or like_url - appid = str(self._qzone_post_value(post, "appid", "311") or "311") - typeid = str(self._qzone_post_value(post, "typeid", "0") or "0") - fid = str(self._qzone_post_value(post, "fid", tid) or tid) - abstime = _safe_int(self._qzone_post_value(post, "abstime", 0), 0, 0) - if abstime <= 0: - abstime = _safe_int(getattr(post, "create_time", 0), 0, 0) or int(time.time()) - payload = await self._qzone_request( - event, - "POST", - "https://user.qzone.qq.com/proxy/domain/w.qzone.qq.com/cgi-bin/likes/internal_dolike_app", - params={"g_tk": ctx["gtk"]}, - data={ - "qzreferrer": f"https://user.qzone.qq.com/{ctx['uin']}", - "opuin": ctx["uin"], - "unikey": unikey, - "curkey": curkey, - "appid": appid, - "from": 1, - "typeid": typeid, - "abstime": abstime, - "fid": fid, - "active": 0, - "format": "json", - "fupdate": 1, - }, - headers={ - "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", - "Referer": f"https://user.qzone.qq.com/{uin}/mood/{tid}", - "Origin": "https://user.qzone.qq.com", - }, - cookie_header=cookie_header, - ) - code = payload.get("code", 0) - if code not in {0, "0"}: - logger.warning( - "[PrivateCompanion] QQ 空间点赞失败: code=%s message=%s uin=%s tid=%s appid=%s typeid=%s fid=%s http=%s", - code, - _single_line(payload.get("message") or payload.get("msg") or payload.get("_raw_message"), 100), - uin, - tid, - appid, - typeid, - fid, - payload.get("_http_status"), - ) - raise RuntimeError(_single_line(payload.get("message") or payload.get("msg") or f"点赞失败 code={code}", 160)) - verification = await self._qzone_verify_like_post(event, post, cookie_header=cookie_header, target_liked=True) - logger.info( - "[PrivateCompanion] QQ 空间点赞成功: uin=%s tid=%s appid=%s typeid=%s fid=%s verified=%s", - uin, - tid, - appid, - typeid, - fid, - bool(verification.get("verified")), - ) - return { - "success": True, - "liked": True if verification.get("liked") is None else bool(verification.get("liked")), - "verified": bool(verification.get("verified")), - "verify_message": verification.get("message") or "", - "tid": tid, - "uin": uin, - "fid": fid, - } - - async def _qzone_delete_post( - self, - event: AstrMessageEvent | None, - post: Any, - *, - cookie_header: str | None = None, - ) -> None: - if cookie_header is None: - cookie_header = await self._qzone_get_cookies(event) - ctx = self._qzone_context_from_cookies(cookie_header) - tid = str(getattr(post, "tid", "") or "") - uin = str(getattr(post, "uin", "") or "") - if not tid or not uin: - raise RuntimeError("说说 tid 或 uin 为空,无法删除") - if str(ctx.get("uin") or "") != uin: - raise RuntimeError("只能删除当前登录 QQ 自己发布的说说") - appid = str(self._qzone_post_value(post, "appid", "311") or "311") - fid = str(self._qzone_post_value(post, "fid", tid) or tid) - unikey = str(self._qzone_post_value(post, "unikey", "") or "") or f"https://user.qzone.qq.com/{uin}/mood/{tid}" - curkey = str(self._qzone_post_value(post, "curkey", "") or "") or unikey - abstime = _safe_int(self._qzone_post_value(post, "abstime", 0), 0, 0) - if abstime <= 0: - abstime = _safe_int(getattr(post, "create_time", 0), 0, 0) - payload = await self._qzone_request( - event, - "POST", - "https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_delete_v6", - params={"g_tk": ctx["gtk"]}, - data={ - "hostuin": uin, - "tid": tid, - "t1_source": 1, - "code_version": 1, - "format": "json", - "qzreferrer": f"https://user.qzone.qq.com/{uin}/mood/{tid}", - "topicId": f"{uin}_{tid}__1", - "uin": uin, - "feedsType": 100, - "feedsAppid": appid, - "feedsKey": fid or tid, - "feedsTime": abstime, - "unikey": unikey, - "curkey": curkey, - }, - headers={ - "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", - "Accept": "application/json, text/javascript, */*; q=0.01", - "Referer": f"https://user.qzone.qq.com/{uin}/mood/{tid}", - "Origin": "https://user.qzone.qq.com", - "X-Requested-With": "XMLHttpRequest", - }, - cookie_header=cookie_header, - ) - code = payload.get("code", payload.get("ret", payload.get("_raw_code", 0))) - if code not in {0, "0", None, ""}: - logger.warning( - "[PrivateCompanion] QQ 空间删除说说失败: code=%s message=%s uin=%s tid=%s http=%s", - code, - _single_line(payload.get("message") or payload.get("msg") or payload.get("_raw_message"), 100), - uin, - tid, - payload.get("_http_status"), - ) - raise RuntimeError(_single_line(payload.get("message") or payload.get("msg") or f"删除失败 code={code}", 160)) - logger.info("[PrivateCompanion] QQ 空间删除说说成功: uin=%s tid=%s", uin, tid) - - async def _qzone_generate_comment(self, post: Any) -> str: - prompt = f""" -请以当前 Bot 人格,为下面这条 QQ 空间说说写一句自然评论。 -只输出评论正文,不要解释。 - -要求: -- 8 到 40 字。 -- 像真实熟人评论,不要像客服或总结。 -- 不要泄露私聊内容、插件内部信息、关系网资料或状态数值。 -- 如果内容信息不足,可以写轻量回应。 - -【作者】 -{_single_line(getattr(post, "name", ""), 40) or _single_line(getattr(post, "uin", ""), 40) or "对方"} - -【说说内容】 -{_single_line(getattr(post, "text", "") or getattr(post, "rt_con", ""), 240) or "无文本"} -""".strip() - text = await self._llm_call( - prompt, - max_tokens=80, - provider_id=self._task_provider(self.mai_style_provider_id, self.llm_provider_id), - task="qzone_comment", - ) - return _single_line(text, 80) - - async def _qzone_comment_post(self, event: AstrMessageEvent | None, post: Any, content: str = "") -> str: - cookie_header = await self._qzone_get_cookies(event) - ctx = self._qzone_context_from_cookies(cookie_header) - tid = str(getattr(post, "tid", "") or "") - uin = str(getattr(post, "uin", "") or "") - if not tid or not uin: - raise RuntimeError("说说 tid 或 uin 为空,无法评论") - comment = _single_line(content, 120) or await self._qzone_generate_comment(post) - if not comment: - raise RuntimeError("评论内容为空") - payload = await self._qzone_request( - event, - "POST", - "https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_re_feeds", - params={"g_tk": ctx["gtk"]}, - data={ - "topicId": f"{uin}_{tid}__1", - "uin": ctx["uin"], - "hostUin": uin, - "feedsType": 100, - "inCharset": "utf-8", - "outCharset": "utf-8", - "plat": "qzone", - "source": "ic", - "platformid": 52, - "format": "fs", - "ref": "feeds", - "content": comment, - }, - cookie_header=cookie_header, - ) - code = payload.get("code", 0) - if code not in {0, "0"}: - raise RuntimeError(_single_line(payload.get("message") or payload.get("msg") or f"评论失败 code={code}", 160)) - return comment - - @staticmethod - def _qzone_trim_id_list(values: Any, *, limit: int = 500) -> list[str]: - result: list[str] = [] - for value in values if isinstance(values, list) else []: - text = _single_line(value, 120) - if text and text not in result: - result.append(text) - return result[-max(1, int(limit or 500)) :] - - @staticmethod - def _qzone_normalized_comment_text(text: Any) -> str: - cleaned = html.unescape(re.sub(r"<[^>]+>", "", str(text or ""))) - cleaned = re.sub(r"\s+", "", cleaned).lower() - cleaned = re.sub(r"[,,。.!!??~~…·、;;::\"'“”‘’\[\]()()\s]+", "", cleaned) - return _single_line(cleaned, 160) - - def _qzone_comment_author_key(self, comment: Any) -> str: - uin = _safe_int(getattr(comment, "uin", 0), 0, 0) - if uin: - return f"uin:{uin}" - name = re.sub(r"\s+", "", _single_line(getattr(comment, "name", ""), 40).lower()) - return f"name:{name}" if name else "unknown" - - def _qzone_comment_author_post_key(self, post: Any, comment: Any) -> str: - post_tid = _single_line(getattr(post, "tid", ""), 80) or "post" - return f"{post_tid}|{self._qzone_comment_author_key(comment)}" - - def _qzone_trim_comment_records( - self, - values: Any, - *, - now: float, - max_age_seconds: float = 7 * 24 * 3600, - limit: int = 160, - ) -> list[dict[str, Any]]: - result: list[dict[str, Any]] = [] - seen: set[str] = set() - for item in values if isinstance(values, list) else []: - if not isinstance(item, dict): - continue - ts = _safe_float(item.get("ts"), 0) - if ts and now - ts > max_age_seconds: - continue - key = _single_line(item.get("key") or item.get("signature"), 160) - post_tid = _single_line(item.get("post_tid"), 80) - text_norm = _single_line(item.get("text_norm"), 160) - if not key and post_tid and text_norm: - key = f"{post_tid}|{text_norm}" - if not key or key in seen: - continue - seen.add(key) - result.append( - { - "key": key, - "post_tid": post_tid, - "author_key": _single_line(item.get("author_key"), 80), - "text_norm": text_norm, - "text": _single_line(item.get("text"), 120), - "ts": ts or now, - } - ) - return result[-max(1, int(limit or 160)) :] - - def _qzone_recent_sent_comment_records(self, state: dict[str, Any], *, now: float) -> list[dict[str, Any]]: - records = self._qzone_trim_comment_records( - state.get("comment_inbox_recent_sent_comments") if isinstance(state, dict) else [], - now=now, - max_age_seconds=7 * 24 * 3600, - limit=160, - ) - if isinstance(state, dict): - state["comment_inbox_recent_sent_comments"] = records - return records - - def _qzone_recent_author_reply_records(self, state: dict[str, Any], *, now: float) -> list[dict[str, Any]]: - records = self._qzone_trim_comment_records( - state.get("comment_inbox_recent_author_replies") if isinstance(state, dict) else [], - now=now, - max_age_seconds=24 * 3600, - limit=160, - ) - if isinstance(state, dict): - state["comment_inbox_recent_author_replies"] = records - return records - - def _qzone_comment_matches_recent_sent(self, state: dict[str, Any], post: Any, comment: Any, *, now: float) -> bool: - post_tid = _single_line(getattr(post, "tid", ""), 80) or "post" - content_norm = self._qzone_normalized_comment_text(getattr(comment, "content", "")) - if not content_norm: - return False - for item in self._qzone_recent_sent_comment_records(state, now=now): - if item.get("post_tid") == post_tid and item.get("text_norm") == content_norm: - return True - return False - - def _qzone_comment_is_self(self, state: dict[str, Any], post: Any, comment: Any, *, own_uin: int, now: float) -> bool: - comment_uin = _safe_int(getattr(comment, "uin", 0), 0, 0) - if own_uin and comment_uin == int(own_uin): - return True - comment_name = re.sub(r"\s+", "", _single_line(getattr(comment, "name", ""), 40).lower()) - post_name = re.sub(r"\s+", "", _single_line(getattr(post, "name", ""), 40).lower()) - if comment_name and post_name and comment_name == post_name: - return True - return self._qzone_comment_matches_recent_sent(state, post, comment, now=now) - - def _qzone_author_post_recently_replied(self, state: dict[str, Any], post: Any, comment: Any, *, now: float, cooldown_seconds: float = 6 * 3600) -> bool: - key = self._qzone_comment_author_post_key(post, comment) - if not key: - return False - for item in self._qzone_recent_author_reply_records(state, now=now): - if item.get("key") == key and now - _safe_float(item.get("ts"), 0) < cooldown_seconds: - return True - return False - - def _qzone_note_comment_inbox_sent(self, state: dict[str, Any], post: Any, comment: Any, sent_text: str, *, now: float) -> None: - if not isinstance(state, dict): - return - post_tid = _single_line(getattr(post, "tid", ""), 80) or "post" - text_norm = self._qzone_normalized_comment_text(sent_text) - if text_norm: - sent_records = self._qzone_recent_sent_comment_records(state, now=now) - sent_records.append( - { - "key": f"{post_tid}|{text_norm}", - "post_tid": post_tid, - "author_key": "self", - "text_norm": text_norm, - "text": _single_line(sent_text, 120), - "ts": now, - } - ) - state["comment_inbox_recent_sent_comments"] = self._qzone_trim_comment_records(sent_records, now=now, limit=160) - author_key = self._qzone_comment_author_post_key(post, comment) - author_records = self._qzone_recent_author_reply_records(state, now=now) - author_records.append( - { - "key": author_key, - "post_tid": post_tid, - "author_key": self._qzone_comment_author_key(comment), - "text_norm": self._qzone_normalized_comment_text(getattr(comment, "content", "")), - "text": _single_line(getattr(comment, "content", ""), 120), - "ts": now, - } - ) - state["comment_inbox_recent_author_replies"] = self._qzone_trim_comment_records( - author_records, - now=now, - max_age_seconds=24 * 3600, - limit=160, - ) - - def _qzone_comment_reply_leaks_private(self, text: str) -> bool: - compact = str(text or "") - if not compact.strip(): - return True - patterns = ( - r"私聊", - r"主人", - r"主要用户", - r"朋友用户", - r"次要用户", - r"插件", - r"模型", - r"系统提示", - r"token", - r"后台", - r"内部", - r"记忆注入", - ) - return any(re.search(pattern, compact, flags=re.IGNORECASE) for pattern in patterns) - - @staticmethod - def _qzone_clean_comment_reply_text(value: Any, commenter_name: Any = "") -> str: - reply = _single_line(value, 80).strip(" ,,。") - name = _single_line(commenter_name, 40).strip().lstrip("@") - if name: - reply = re.sub(rf"^(?:@?{re.escape(name)}[\s,,::]+)+", "", reply).strip() - while reply: - codepoint = ord(reply[-1]) - if ( - 0x1F000 <= codepoint <= 0x1FAFF - or 0x2600 <= codepoint <= 0x27BF - or codepoint in {0x200D, 0xFE0E, 0xFE0F} - ): - reply = reply[:-1].rstrip() - continue - break - return reply.strip(" ,,。") - - def _qzone_comment_author_context(self, comment: Any) -> str: - uin = _single_line(getattr(comment, "uin", ""), 40) - name = _single_line(getattr(comment, "name", ""), 40) - profile: dict[str, Any] | None = None - match_note = "" - if uin and uin != "0": - profile = self._worldbook_profile_by_user_id(uin) - if profile: - match_note = "按 QQ 号命中关系网。" - if not profile and name: - matches = self._resolve_worldbook_member_by_name(name) - if len(matches) == 1: - profile = matches[0] - match_note = "按评论显示名弱命中关系网。" - elif len(matches) > 1: - names = "、".join(_single_line(item.get("name"), 24) for item in matches[:3] if _single_line(item.get("name"), 24)) - return ( - "【评论者身份】\n" - f"评论显示名:{name};QQ:{uin or '未知'}。\n" - f"关系网里有多个同名/近似对象:{names or '多个候选'};本轮不要擅自认定身份,也不要当成主要用户。" - ) - if not profile: - return ( - "【评论者身份】\n" - f"评论显示名:{name or '未知'};QQ:{uin or '未知'}。\n" - "关系网未确认此人;按普通空间评论者处理,不要把对方当成主要用户、私聊对象或熟人。" - ) - - profile_uid = _single_line(profile.get("linked_qq_user_id") or profile.get("user_id") or uin, 40) - stable_name = _single_line(profile.get("name"), 40) or name or profile_uid - aliases = [] - for token in [*(profile.get("aliases") or []), *(profile.get("observed_names") or [])]: - value = _single_line(token, 24) - if value and value != stable_name and value not in aliases: - aliases.append(value) - if len(aliases) >= 4: - break - identity_note = _single_line(profile.get("identity_note") or profile.get("note") or profile.get("content"), 120) - lines = [ - "【评论者身份】", - f"已识别:{stable_name}[QQ:{profile_uid or uin or '未知'}];{match_note or '命中关系网。'}", - ] - if name and name != stable_name: - lines.append(f"当前空间显示名:{name}。") - if aliases: - lines.append(f"别名/常见名:{'、'.join(aliases)}。") - if identity_note: - lines.append(f"关系备注:{identity_note}") - lines.append("这些资料只用于判断称呼和边界,公开回复里不要复述关系网资料。") - return "\n".join(lines) - - def _qzone_post_time_text(self, value: Any) -> str: - ts = _safe_float(value, 0) - if ts <= 0: - return "" - try: - formatter = getattr(self, "_environment_fromtimestamp", None) - if callable(formatter): - return formatter(ts).strftime("%Y-%m-%d %H:%M") - return time.strftime("%Y-%m-%d %H:%M", time.localtime(ts)) - except Exception: - return "" - - def _qzone_post_brief_context(self, post: Any) -> str: - tid = _single_line(getattr(post, "tid", ""), 80) - author = _single_line(getattr(post, "name", ""), 40) or _single_line(getattr(post, "uin", ""), 40) or "我" - text = _single_line(getattr(post, "text", "") or getattr(post, "rt_con", ""), 240) or "无文本" - rt_text = _single_line(getattr(post, "rt_con", ""), 160) - images = getattr(post, "images", []) or [] - image_count = len(images) if isinstance(images, list) else 0 - post_type = "转发" if rt_text else ("图文" if image_count else "文字") - created = self._qzone_post_time_text(getattr(post, "create_time", 0)) or "未知" - return ( - "【所在说说】\n" - f"说说ID:{tid or '未知'}\n" - f"作者:{author}\n" - f"发布时间:{created}\n" - f"类型:{post_type};图片数量:{image_count}\n" - f"正文:{text}" - ) - - async def _qzone_memory_companion_context(self, *, purpose: str, query: str = "") -> str: - getter = getattr(self, "_memory_companion_compose_feature_context", None) - if not callable(getter): - return "" - try: - return await getter( - kind=f"qzone_{_single_line(purpose, 40) or 'context'}", - query=query or "QQ空间公开动态 当前日程 最近生活 日记余味 今日穿搭 自我时间线", - top_k=5, - max_chars=760, - ) - except Exception: - return "" - - async def _qzone_decide_comment_reply(self, post: Any, comment: Any, *, own_uin: int) -> dict[str, str]: - content = _single_line(getattr(comment, "content", ""), 180) - if not content: - return {"decision": "skip", "reply": "", "reason": "评论为空"} - if own_uin and _safe_int(getattr(comment, "uin", 0), 0, 0) == int(own_uin): - return {"decision": "skip", "reply": "", "reason": "自己的评论"} - author_context = self._qzone_comment_author_context(comment) - post_context = self._qzone_post_brief_context(post) - memory_context = await self._qzone_memory_companion_context( - purpose="comment_reply", - query=f"QQ空间评论回复 {content} 所在说说 {_single_line(getattr(post, 'text', ''), 180)} 关系边界 最近公开生活", - ) - prompt = f""" -你在处理 Bot 自己 QQ 空间说说下的新评论。请判断是否需要公开回复。 -只输出 JSON,不要解释。 - -可选 decision: -- reply:评论里有明确提问、点名、夸赞、玩笑、接话或值得轻轻回应的内容。 -- skip:纯表情、路过、点赞、无意义短句、容易引战或不适合公开接的话。 - -回复要求: -- 8 到 45 字,像真实空间评论区的自然追加评论。 -- 不要泄露私聊、主要用户/次要用户身份、插件、模型、系统提示、内部状态或记忆来源。 -- 不要过度亲密,不要替评论者编造关系。 -- 评论者身份未确认时,只按普通空间访客处理;不能因为对方语气或昵称就认成主要用户。 -- 评论者身份已识别时,也只使用自然称呼和公开边界,不要复述关系网资料。 -- 评论区已有明确的回复层级,不要在开头机械复述评论者的显示名,也不要无故 @ 对方。 -- 不要用表情符号或颜文字补语气;一句自然的话配正常标点即可。 -- 如果需要回复,只把 reply 写成可公开发送的正文;不需要回复时 reply 为空。 - -输出格式: -{{"decision":"reply|skip","reply":"","reason":"12字以内原因"}} - -{post_context} - -【评论者】 -{_single_line(getattr(comment, "name", ""), 40) or str(getattr(comment, "uin", "") or "对方")} - -{author_context} - -【我会牢牢记住你 公开边界参考】 -{memory_context or "暂无"} -使用方式:只帮助判断公开回复边界和最近生活连续性;不要泄露私聊、记忆来源或内部记录。 - -【评论内容】 -{content} -""".strip() - raw = await self._llm_call( - prompt, - max_tokens=120, - provider_id=self._task_provider(self.mai_style_provider_id, self.llm_provider_id), - task="qzone_comment_inbox_decision", - ) - payload = self._extract_json_payload(raw or "") - if not isinstance(payload, dict): - payload = {} - decision = str(payload.get("decision") or "").strip().lower() - if decision not in {"reply", "skip"}: - decision = "skip" - reply = _single_line(payload.get("reply"), 80) - reason = _single_line(payload.get("reason"), 40) - if decision == "reply": - if len(reply) < 2 or self._qzone_comment_reply_leaks_private(reply): - return {"decision": "skip", "reply": "", "reason": "回复不安全"} - reply = self._qzone_clean_comment_reply_text( - reply.strip(" 「」\"'"), - getattr(comment, "name", ""), - ) - if len(reply) < 2: - return {"decision": "skip", "reply": "", "reason": "回复过短"} - return {"decision": decision, "reply": reply, "reason": reason} - - async def _qzone_reply_to_comment(self, event: AstrMessageEvent | None, post: Any, comment: Any, reply_text: str) -> str: - reply = self._qzone_clean_comment_reply_text(reply_text, getattr(comment, "name", "")) - if not reply: - raise RuntimeError("评论回复内容为空") - return await self._qzone_comment_post(event, post, content=_single_line(reply, 120)) - - async def _maybe_process_qzone_comment_inbox(self) -> None: - if not (self._qzone_available() and getattr(self, "enable_qzone_comment_inbox", False)): - return - now = _now_ts() - state = self._qzone_state_dict() - seen_ids: list[str] = [] - replied_ids: list[str] = [] - seen_keys: list[str] = [] - replied_keys: list[str] = [] - replied_set: set[str] = set() - replied_key_set: set[str] = set() - interval_seconds = max(5, _safe_int(getattr(self, "qzone_comment_inbox_interval_minutes", 60), 60, 5, 1440)) * 60 - if now - _safe_float(state.get("last_comment_inbox_checked_at"), 0) < interval_seconds: - return - if now - _safe_float(state.get("last_comment_inbox_failed_at"), 0) < 15 * 60: - return - try: - cookie_header = await self._qzone_get_cookies(None) - ctx = self._qzone_context_from_cookies(cookie_header) - own_uin = _safe_int(ctx.get("uin"), 0, 0) - recent_posts = _safe_int(getattr(self, "qzone_comment_inbox_recent_posts", 5), 5, 1, 20) - max_replies = _safe_int(getattr(self, "qzone_comment_inbox_max_replies_per_tick", 1), 1, 1, 5) - posts = await self._qzone_query_feeds(None, target_id=str(own_uin), pos=0, num=recent_posts, with_detail=True) - observed: list[tuple[Any, Any, str, str, list[str], bool, bool]] = [] - for post in posts: - for comment in list(getattr(post, "comments", []) or []): - comment_id = _single_line(getattr(comment, "comment_id", ""), 120) - post_tid = _single_line(getattr(post, "tid", ""), 80) - raw_comment = getattr(comment, "raw", None) - if isinstance(raw_comment, dict): - comment_key = self._qzone_comment_fingerprint(post_tid, raw_comment) - comment_legacy_id = self._qzone_comment_legacy_fallback_id(post_tid, raw_comment) - else: - author = _single_line(getattr(comment, "uin", ""), 40) or _single_line(getattr(comment, "name", ""), 40) - content = re.sub(r"\s+", "", _single_line(getattr(comment, "content", ""), 180)).lower() - digest = hashlib.sha1(f"{post_tid or 'post'}|{author}|{content}".encode("utf-8", "ignore")).hexdigest()[:20] - comment_key = f"{post_tid or 'post'}:fp:{digest}" - comment_legacy_id = _single_line(getattr(comment, "comment_legacy_id", ""), 120) - comment_key = _single_line(getattr(comment, "comment_key", "") or comment_key, 120) - comment_legacy_id = _single_line(getattr(comment, "comment_legacy_id", "") or comment_legacy_id, 120) - if comment_id or comment_key: - id_candidates = self._qzone_trim_id_list([comment_id, comment_legacy_id, comment_key], limit=5) - is_self_comment = self._qzone_comment_is_self(state, post, comment, own_uin=own_uin, now=now) - author_recently_replied = self._qzone_author_post_recently_replied(state, post, comment, now=now) - observed.append( - ( - post, - comment, - comment_id or comment_key, - comment_key or comment_id, - id_candidates, - is_self_comment, - author_recently_replied, - ) - ) - seen_ids = self._qzone_trim_id_list(state.get("comment_inbox_seen_ids"), limit=500) - replied_ids = self._qzone_trim_id_list(state.get("comment_inbox_replied_ids"), limit=300) - seen_keys = self._qzone_trim_id_list(state.get("comment_inbox_seen_keys"), limit=500) - replied_keys = self._qzone_trim_id_list(state.get("comment_inbox_replied_keys"), limit=300) - seen_set = set(seen_ids) - replied_set = set(replied_ids) - seen_key_set = set(seen_keys) - replied_key_set = set(replied_keys) - observed_ids = [candidate_id for _, _, _, _, id_candidates, _, _ in observed for candidate_id in id_candidates if candidate_id] - observed_keys = [comment_key for _, _, _, comment_key, _, _, _ in observed if comment_key] - first_run = not state.get("comment_inbox_initialized_at") - if first_run: - state["comment_inbox_seen_ids"] = self._qzone_trim_id_list(seen_ids + observed_ids, limit=500) - state["comment_inbox_seen_keys"] = self._qzone_trim_id_list(seen_keys + observed_keys, limit=500) - state["comment_inbox_initialized_at"] = now - state["last_comment_inbox_checked_at"] = now - state["last_comment_inbox_status"] = f"seeded:{len(observed_ids)}" - self._save_data_sync() - logger.info("[PrivateCompanion] QQ 空间评论收件箱首次启用,已记录现有评论: count=%s", len(observed_ids)) - return - history_lost_after_init = bool( - state.get("comment_inbox_initialized_at") - and observed_ids - and not seen_ids - and not seen_keys - and not replied_ids - and not replied_keys - ) - if history_lost_after_init: - state["comment_inbox_seen_ids"] = self._qzone_trim_id_list(observed_ids, limit=500) - state["comment_inbox_seen_keys"] = self._qzone_trim_id_list(observed_keys, limit=500) - state["last_comment_inbox_checked_at"] = now - state["last_comment_inbox_status"] = f"reseeded:history_lost:{len(observed_ids)}" - self._save_data_sync() - logger.warning( - "[PrivateCompanion] QQ 空间评论收件箱历史 key 为空,已重新播种当前可见评论并跳过本轮回复: count=%s", - len(observed_ids), - ) - return - - candidates = [ - (post, comment, comment_id, comment_key, id_candidates) - for post, comment, comment_id, comment_key, id_candidates, is_self_comment, author_recently_replied in observed - if not any(candidate_id in seen_set or candidate_id in replied_set for candidate_id in id_candidates) - and comment_key not in seen_key_set - and comment_key not in replied_key_set - and not is_self_comment - and not author_recently_replied - ] - if observed_ids or observed_keys: - state["comment_inbox_seen_ids"] = self._qzone_trim_id_list(seen_ids + observed_ids, limit=500) - state["comment_inbox_seen_keys"] = self._qzone_trim_id_list(seen_keys + observed_keys, limit=500) - state["last_comment_inbox_checked_at"] = now - state["last_comment_inbox_status"] = f"checking:new={len(candidates)}" - self._save_data_sync() - candidates.sort(key=lambda item: _safe_float(getattr(item[1], "create_time", 0), 0)) - replies = 0 - skipped = 0 - last_reason = "" - sent_text = "" - for post, comment, comment_id, comment_key, id_candidates in candidates: - if replies >= max_replies: - break - decision = await self._qzone_decide_comment_reply(post, comment, own_uin=own_uin) - if decision.get("decision") != "reply": - skipped += 1 - last_reason = _single_line(decision.get("reason"), 60) - continue - for candidate_id in id_candidates: - if candidate_id: - replied_set.add(candidate_id) - if comment_id: - replied_set.add(comment_id) - if comment_key: - replied_key_set.add(comment_key) - state["comment_inbox_replied_ids"] = self._qzone_trim_id_list(list(replied_set), limit=300) - state["comment_inbox_replied_keys"] = self._qzone_trim_id_list(list(replied_key_set), limit=300) - state["last_comment_inbox_checked_at"] = now - state["last_comment_inbox_status"] = f"replying:guarded:{_single_line(comment_id or comment_key, 80)}" - state["last_comment_inbox_reply_comment_id"] = comment_id - state["last_comment_inbox_reply_comment_key"] = comment_key - state["last_comment_inbox_reply_author"] = _single_line(getattr(comment, "name", ""), 40) or _single_line(getattr(comment, "uin", ""), 40) - self._save_data_sync() - sent_text = await self._qzone_reply_to_comment(None, post, comment, str(decision.get("reply") or "")) - self._qzone_note_comment_inbox_sent(state, post, comment, sent_text, now=now) - replies += 1 - last_reason = _single_line(decision.get("reason"), 60) or "已回复" - state["comment_inbox_replied_ids"] = self._qzone_trim_id_list(list(replied_set), limit=300) - state["comment_inbox_replied_keys"] = self._qzone_trim_id_list(list(replied_key_set), limit=300) - state["last_comment_inbox_reply_at"] = now - post_images = getattr(post, "images", []) or [] - post_image_count = len(post_images) if isinstance(post_images, list) else 0 - post_rt_text = _single_line(getattr(post, "rt_con", ""), 160) - post_type = "转发" if post_rt_text else ("图文" if post_image_count else "文字") - state["last_comment_inbox_reply_post_tid"] = _single_line(getattr(post, "tid", ""), 80) - state["last_comment_inbox_reply_post_type"] = post_type - state["last_comment_inbox_reply_post_time"] = self._qzone_post_time_text(getattr(post, "create_time", 0)) - state["last_comment_inbox_reply_post_text"] = _single_line( - getattr(post, "text", "") or getattr(post, "rt_con", ""), - 120, - ) - state["last_comment_inbox_reply_post_image_count"] = post_image_count - state["last_comment_inbox_reply_comment_id"] = comment_id - state["last_comment_inbox_reply_comment_key"] = comment_key - state["last_comment_inbox_reply_author"] = _single_line(getattr(comment, "name", ""), 40) or _single_line(getattr(comment, "uin", ""), 40) - state["last_comment_inbox_reason"] = last_reason - state["last_comment_inbox_reply_text"] = _single_line(sent_text, 120) - self._save_data_sync() - logger.info( - "[PrivateCompanion] QQ 空间评论收件箱已追加评论回复: post=%s type=%s comment=%s key=%s author=%s text=%s", - state["last_comment_inbox_reply_post_tid"] or "-", - post_type, - comment_id, - comment_key, - state["last_comment_inbox_reply_author"], - _single_line(sent_text, 100), - ) - state["comment_inbox_seen_ids"] = self._qzone_trim_id_list(seen_ids + observed_ids, limit=500) - state["comment_inbox_seen_keys"] = self._qzone_trim_id_list(seen_keys + observed_keys, limit=500) - state["comment_inbox_replied_ids"] = self._qzone_trim_id_list(list(replied_set), limit=300) - state["comment_inbox_replied_keys"] = self._qzone_trim_id_list(list(replied_key_set), limit=300) - state["last_comment_inbox_checked_at"] = now - state["last_comment_inbox_status"] = f"checked:new={len(candidates)},replied={replies},skipped={skipped}" - state["last_comment_inbox_reason"] = last_reason - state["last_comment_inbox_reply_text"] = _single_line(sent_text, 120) - if replies: - state["last_comment_inbox_reply_at"] = now - state.pop("last_comment_inbox_failed_at", None) - self._save_data_sync() - except Exception as exc: - reason = _single_line(exc, 160) - if self._qzone_auth_failure_message(reason): - self._qzone_mark_auth_failure(reason, source="comment_inbox", state=state, save=False) - if replied_set or replied_key_set: - state["comment_inbox_replied_ids"] = self._qzone_trim_id_list( - replied_ids + list(replied_set), - limit=300, - ) - state["comment_inbox_replied_keys"] = self._qzone_trim_id_list( - replied_keys + list(replied_key_set), - limit=300, - ) - if seen_ids or seen_keys: - state["comment_inbox_seen_ids"] = self._qzone_trim_id_list( - self._qzone_trim_id_list(state.get("comment_inbox_seen_ids"), limit=500) + seen_ids, - limit=500, - ) - state["comment_inbox_seen_keys"] = self._qzone_trim_id_list( - self._qzone_trim_id_list(state.get("comment_inbox_seen_keys"), limit=500) + seen_keys, - limit=500, - ) - state["last_comment_inbox_failed_at"] = now - state["last_comment_inbox_checked_at"] = now - state["last_comment_inbox_status"] = f"failed:{_single_line(reason, 80)}" - self._save_data_sync() - if any(token in reason for token in ("没有可用的 OneBot 连接", "获取 QQ 空间 Cookie 失败", "Cookie")): - logger.warning("[PrivateCompanion] QQ 空间评论收件箱处理失败: %s", reason) - else: - logger.warning("[PrivateCompanion] QQ 空间评论收件箱处理失败: %s", reason, exc_info=True) - - def _qzone_public_state_hint(self, state: dict[str, Any]) -> str: - """Return a public-safe mood hint for Qzone posts without internal state fields.""" - if not isinstance(state, dict): - return "心情平稳,适合写一小段生活感。" - mood = _single_line(state.get("mood_bias"), 24) or "平稳" - weather = _single_line(state.get("weather"), 80) - sleep = _single_line(state.get("sleep"), 40) - hints: list[str] = [] - if mood: - hints.append(f"心情底色偏{mood}") - if weather and weather != "暂无天气信息": - hints.append(f"天气余味:{weather}") - if sleep and sleep not in {"睡眠平稳", "正常"}: - hints.append(f"节奏偏{sleep}") - if not hints: - hints.append("生活节奏平稳") - hints.append("只能写成自然感受,不要写状态标签、数值或内部变量。") - return ";".join(hints) - - @staticmethod - def _qzone_temporal_context() -> str: - now = time.localtime() - weekday_names = ("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日") - hour = now.tm_hour - if 0 <= hour < 6: - period = "凌晨" - elif hour < 9: - period = "早晨" - elif hour < 12: - period = "上午" - elif hour < 16: - period = "下午" - elif hour < 19: - period = "傍晚" - elif hour < 22: - period = "晚上" - else: - period = "深夜" - if now.tm_mon in (12, 1, 2): - season = "冬天" - elif now.tm_mon in (3, 4, 5): - season = "春天" - elif now.tm_mon in (6, 7, 8, 9): - season = "夏天" - else: - season = "秋天" - weekday = weekday_names[min(6, max(0, now.tm_wday))] - day_type = "周末" if now.tm_wday >= 5 else "工作日" - return f"{time.strftime('%Y年%m月%d日 %H:%M', now)},{weekday},{day_type},{season},{period}。" - - @staticmethod - def _qzone_publish_theme_hint() -> str: - themes = ( - "记录当前时段里一件具体的小事", - "写一个自然冒出来的心情余味", - "轻轻吐槽一个生活里的小麻烦", - "记录眼前看到、听到或碰到的具体画面", - "写一段短短的碎碎念,不要总结成道理", - "记录一个让人稍微开心或安心的小瞬间", - "写写天气、光线、食物、衣物、路上或桌边的生活细节", - "从当前日程里挑一个最不像任务汇报的切面", - ) - return random.choice(themes) - - def _qzone_relationship_safe_source(self, value: Any, *, source: str) -> str: - sanitizer = getattr(self, "_sanitize_generation_relationship_context", None) - if callable(sanitizer): - try: - return sanitizer(value, source=source) - except Exception: - pass - return str(value or "").strip() - - def _qzone_relationship_authority_guard(self) -> str: - formatter = getattr(self, "_format_generation_relationship_authority_guard", None) - if callable(formatter): - try: - return str(formatter() or "").strip() - except Exception: - pass - return "" - - def _qzone_recent_publish_context(self, state: dict[str, Any], *, limit: int = 5) -> str: - items = state.get("recent_life_publish_texts") if isinstance(state, dict) else [] - if not isinstance(items, list): - return "" - lines: list[str] = [] - for item in items[-max(1, int(limit or 5)) :]: - text = _single_line( - self._qzone_relationship_safe_source( - item.get("text") if isinstance(item, dict) else item, - source="qzone.recent_publish", - ), - 120, - ) - if text: - lines.append(f"- {text}") - if not lines: - return "" - return "最近已发说说:\n" + "\n".join(lines) + "\n本次请换一个场景、情绪或观察角度,不要重复同一类表达。" - - def _qzone_recent_self_publish_chat_context(self, *, limit: int = 3) -> str: - """Expose recent successful Bot posts to Qzone-related chat turns.""" - state = self.data.get("qzone_integration") if isinstance(getattr(self, "data", None), dict) else {} - items = state.get("recent_life_publish_texts") if isinstance(state, dict) else [] - if not isinstance(items, list): - return "" - records: list[str] = [] - labels = ("最新一条", "上一条", "更早一条") - for item in reversed(items): - if len(records) >= max(1, min(3, int(limit or 3))): - break - text = _single_line( - self._qzone_relationship_safe_source( - item.get("text") if isinstance(item, dict) else item, - source="qzone.recent_self_publish_chat", - ), - 180, - ) - if not text: - continue - image_count = _safe_int(item.get("image_count"), 0, 0, 99) if isinstance(item, dict) else 0 - image_note = f";配图 {image_count} 张" if image_count else "" - label = labels[len(records)] if len(records) < len(labels) else f"较早第 {len(records) + 1} 条" - records.append(f"- {label}:{text}{image_note}") - if not records: - return "" - return ( - "【Bot 自己最近成功发布的 QQ 空间记录】\n" - + "\n".join(records) - + "\n这些正文是 Bot 自己发出的公开动态,不是当前用户发的内容。" - ) - - def _qzone_note_recent_publish( - self, - state: dict[str, Any], - text: Any, - *, - reason: str, - now: float | None = None, - tid: str = "", - image_count: int = 0, - verified: bool | None = None, - source: str = "", - ) -> None: - if not isinstance(state, dict): - return - clean = _single_line(text, 180) - if not clean: - return - current = _now_ts() if now is None else float(now) - items = state.get("recent_life_publish_texts") - if not isinstance(items, list): - items = [] - deduped: list[dict[str, Any]] = [] - seen: set[str] = set() - for item in items: - raw = item.get("text") if isinstance(item, dict) else item - item_text = _single_line(raw, 180) - key = re.sub(r"\s+", "", item_text) - if not item_text or key in seen or key == re.sub(r"\s+", "", clean): - continue - seen.add(key) - if isinstance(item, dict): - deduped.append(dict(item)) - else: - deduped.append({"text": item_text, "at": 0, "reason": ""}) - entry = { - "text": clean, - "at": current, - "reason": _single_line(reason, 40), - "tid": _single_line(tid, 80), - "image_count": _safe_int(image_count, 0, 0, 99), - "source": _single_line(source, 40), - } - if verified is not None: - entry["verified"] = bool(verified) - deduped.append(entry) - state["recent_life_publish_texts"] = deduped[-8:] - - async def _qzone_record_published_post( - self, - text: Any, - *, - reason: str = "manual_publish", - tid: str = "", - image_count: int = 0, - verified: bool | None = None, - event: AstrMessageEvent | None = None, - ) -> None: - state = self._qzone_state_dict() - now = _now_ts() - clean = _single_line(text, 300) - if not clean: - return - self._qzone_note_recent_publish( - state, - clean, - reason=reason, - now=now, - tid=tid, - image_count=image_count, - verified=verified, - source="publish_success", - ) - state["last_publish_recorded_at"] = now - state["last_publish_recorded_text"] = _single_line(clean, 180) - state["last_publish_recorded_reason"] = _single_line(reason, 40) - state["last_publish_recorded_tid"] = _single_line(tid, 80) - state["last_publish_recorded_images"] = _safe_int(image_count, 0, 0, 99) - recorder = getattr(self, "_memory_companion_record_qzone_publish", None) - if callable(recorder): - await recorder( - text=clean, - reason=reason, - tid=tid, - image_count=image_count, - verified=verified, - event=event, - ) - self._qzone_append_publish_to_current_detail( - clean, - reason=reason, - tid=tid, - image_count=image_count, - verified=verified, - ) - invalidator = getattr(self, "_invalidate_detail_after_interaction", None) - if callable(invalidator): - try: - invalidator(now=now) - except Exception: - pass - try: - self._save_data_sync() - except Exception as exc: - logger.debug("[PrivateCompanion] QQ 空间发布记录保存失败: %s", _single_line(exc, 120)) - - def _qzone_append_publish_to_current_detail( - self, - text: Any, - *, - reason: str = "", - tid: str = "", - image_count: int = 0, - verified: bool | None = None, - ) -> bool: - segment_getter = getattr(self, "_current_detail_segment_for_update", None) - if not callable(segment_getter): - return False - try: - segment = segment_getter() - except Exception: - return False - if not isinstance(segment, dict): - return False - enhanced = self.data.get("detail_enhanced_segments", {}) - if not isinstance(enhanced, dict): - return False - key = str(segment.get("key") or "") - snapshot = enhanced.get(key) - if not isinstance(snapshot, dict): - return False - clean = _single_line(text, 180) - if not clean: - return False - safe_image_count = _safe_int(image_count, 0, 0, 99) - image_part = f";配图 {safe_image_count} 张" if safe_image_count > 0 else "" - verify_part = ";已反查确认" if verified else "" - event_text = _single_line(f"刚发布了一条 QQ 空间说说:{clean}{image_part}{verify_part}。", 220) - events = snapshot.setdefault("today_events", []) - if not isinstance(events, list): - events = [] - snapshot["today_events"] = events - tid_text = _single_line(tid, 80) - for item in events: - if not isinstance(item, dict): - continue - if tid_text and _single_line(item.get("tid"), 80) == tid_text: - return False - if clean and clean in _single_line(item.get("event") or item.get("text"), 260): - return False - try: - at = self._environment_now().strftime("%H:%M") - except Exception: - at = "" - events.append( - { - "window": at, - "event": event_text, - "mood": "公开动态已发布", - "source": "qzone_publish", - "reason": _single_line(reason, 40), - "tid": tid_text, - } - ) - del events[:-8] - summary = _single_line(snapshot.get("summary"), 140) - summary_tail = _single_line(f"刚发了一条 QQ 空间说说:{clean}", 80) - if summary_tail and summary_tail not in summary: - snapshot["summary"] = _single_line(f"{summary};{summary_tail}" if summary else summary_tail, 160) - snapshot["updated_at"] = at or _single_line(snapshot.get("updated_at"), 20) - return True - - def _qzone_text_leaks_internal_state(self, text: str) -> bool: - compact = str(text or "") - if not compact.strip(): - return False - patterns = ( - r"能量\s*[::=]?\s*\d{1,3}\s*/\s*100", - r"心理能量", - r"\d{1,3}\s*/\s*100", - r"状态变量", - r"当前状态", - r"拟人状态", - r"内部状态", - r"插件", - r"模型", - r"系统提示", - ) - return any(re.search(pattern, compact, flags=re.IGNORECASE) for pattern in patterns) - - def _strip_qzone_internal_state_fragments(self, text: str) -> str: - cleaned = _single_line(text, 180) - if not cleaned: - return "" - cleaned = re.sub(r"(?:心理)?能量\s*[::=]?\s*\d{1,3}\s*/\s*100[,,。;;\s]*", "", cleaned) - cleaned = re.sub(r"\d{1,3}\s*/\s*100[,,。;;\s]*", "", cleaned) - cleaned = re.sub(r"(?:当前状态|拟人状态|状态变量|内部状态)[::,,。;;\s]*", "", cleaned) - cleaned = re.sub(r"(?:插件|模型|系统提示)[^。!?!?;;]{0,40}[。!?!?;;]?", "", cleaned) - cleaned = re.sub(r"\s{2,}", " ", cleaned).strip(" ,,。;;") - return _single_line(cleaned, 180) - - def _qzone_publish_style_prompt(self, *, mood: str = "life") -> str: - base = ( - "默认风格:像随手发的一条 QQ 空间生活碎片,贴着眼前具体事物、动作或天气写;" - "口语、轻一点、短一点,可以有小情绪但不要上价值。" - "避免哲理总结、人生感悟、诗化独白、宏大比喻、老成说教、文案腔和谜语感。" - ) - if mood == "emotional_vent": - base += " 心情动态也要克制,只写公开可见的余味,不要写成控诉或伤感散文。" - voice = "" - voice_formatter = getattr(self, "_format_persona_voice_channel_prompt", None) - if callable(voice_formatter): - voice = voice_formatter("creative") - expression_voice = "" - expression_formatter = getattr(self, "_format_expression_voice_for_prompt", None) - if callable(expression_formatter): - expression_voice = expression_formatter( - scope="qzone", - inbound_text="低落情绪" if mood == "emotional_vent" else "生活闲聊", - ) - custom = _single_line(getattr(self, "qzone_publish_style_prompt", ""), 500) - parts = [base] - if voice: - parts.append(voice) - if expression_voice: - parts.append(expression_voice) - if custom: - parts.append(f"自定义风格:{custom}") - return "\n".join(parts) - - def _qzone_publish_image_style_prompt(self) -> str: - base = ( - "默认配图策略:像 QQ 空间随手生活图,先贴合说说正文和当前日程选择画面。" - "人物可以自然入镜,但不要每次都做自拍;在生活物件、食物饮品、路上光影、桌面一角、窗边、背影、侧脸、第一视角手部之间轮换。" - "避免过度使用镜前自拍、手机挡脸自拍、固定半身自拍模板;只有正文或日程明确在整理穿搭、出门前照镜子、换衣服时才考虑镜前/镜中构图。" - ) - custom = _single_line(getattr(self, "qzone_publish_image_style_prompt", ""), 600) - if custom: - return f"{base}\n自定义配图提示:{custom}" - return base - - async def _sanitize_qzone_life_post_text(self, text: str, *, prompt: str = "") -> str: - cleaned = _single_line(text, 180) - relationship_cleaned = _single_line( - self._qzone_relationship_safe_source( - cleaned, - source="qzone.generated_post", - ), - 180, - ) - if relationship_cleaned != cleaned: - logger.warning( - "[PrivateCompanion] QQ 空间说说草稿含未声明关系,已移除污染片段: %s", - _single_line(cleaned, 160), - ) - cleaned = relationship_cleaned - if len(cleaned) < 12: - return "" - if not self._qzone_text_leaks_internal_state(cleaned): - return cleaned - stripped = self._strip_qzone_internal_state_fragments(cleaned) - if stripped and not self._qzone_text_leaks_internal_state(stripped) and len(stripped) >= 12: - logger.warning("[PrivateCompanion] QQ 空间说说草稿含内部状态,已净化: %s", _single_line(cleaned, 160)) - return stripped - rewrite_prompt = f""" -下面是一条 QQ 空间说说草稿,里面泄露了内部状态/数值。请重写成自然生活动态。 -只输出正文,30 到 120 字,不要解释。 -禁止出现:能量、心理能量、/100、当前状态、状态变量、插件、模型、系统提示。 - -【原草稿】 -{cleaned} - -【原任务背景】 -{_single_line(prompt, 600)} -""".strip() - try: - rewritten = await self._llm_call( - rewrite_prompt, - max_tokens=160, - provider_id=self._task_provider(self.mai_style_provider_id, self.llm_provider_id), - task="qzone_publish_sanitize", - ) - rewritten = _single_line( - self._qzone_relationship_safe_source( - rewritten, - source="qzone.sanitizer_rewrite", - ), - 180, - ) - if rewritten and not self._qzone_text_leaks_internal_state(rewritten): - logger.warning("[PrivateCompanion] QQ 空间说说草稿含内部状态,已重写: %s", _single_line(cleaned, 160)) - return rewritten - except Exception as exc: - logger.warning("[PrivateCompanion] QQ 空间说说内部状态重写失败: %s", _single_line(exc, 120)) - logger.warning("[PrivateCompanion] QQ 空间说说草稿含内部状态且重写失败,已取消本次发布") - return "" - - async def _test_qzone_publish_tool_chain(self, event: AstrMessageEvent | None = None) -> str: - lines = ["QQ 空间发布链路模拟:"] - lines.append(f"- 整合开关:{'开启' if self.enable_qzone_integration else '关闭'}") - lines.append("- 真实发布:否,本指令只模拟工具链路") - if not self._qzone_platform_supported(event): - lines.append(f"结果:{self._qzone_platform_unavailable_message()}") - return "\n".join(lines) - - try: - empty_result_raw = await self._pc_qzone_publish_feed_impl(event, "") - empty_result = json.loads(empty_result_raw) - except Exception as exc: - empty_result = {"status": "exception", "message": _single_line(exc, 160)} - lines.append( - "- 空参数工具调用:" - + ( - "通过,返回 need_text" - if empty_result.get("status") == "need_text" - else f"异常,返回 {empty_result.get('status') or empty_result.get('message') or empty_result}" - ) - ) - - qzone_state = self._qzone_state_dict() - daily_state = self.data.get("daily_state", {}) - current_item = self._get_current_plan_item(self.data.get("daily_plan", {})) - diary_context = self._recent_diary_context(count=2) - theme_hint = self._qzone_publish_theme_hint() - temporal_context = self._qzone_temporal_context() - recent_publish_context = self._qzone_recent_publish_context(qzone_state) - memory_context = await self._qzone_memory_companion_context( - purpose="publish_test", - query="QQ空间生活说说 今日公开可写生活 当前日程 今日穿搭 最近吃饭 日记余味 自我时间线", - ) - public_state_hint = self._qzone_relationship_safe_source( - self._qzone_public_state_hint(daily_state if isinstance(daily_state, dict) else {}), - source="qzone.publish_test.current_state", - ) - current_schedule_hint = self._qzone_relationship_safe_source( - self._format_plan_item_for_prompt(current_item), - source="qzone.publish_test.current_schedule", - ) - diary_context = self._qzone_relationship_safe_source( - diary_context, - source="qzone.publish_test.recent_diary", - ) - memory_context = self._qzone_relationship_safe_source( - memory_context, - source="qzone.publish_test.memory", - ) - relationship_authority_guard = self._qzone_relationship_authority_guard() - prompt = f""" -请以当前 Bot 人格写一条 QQ 空间说说。 -只输出说说正文,不要解释,不要加标题。 - -要求: -- 30 到 120 字。 -- 像自然生活动态,不是公告、不是任务汇报。 -- 可以带一点公开可见的心情、天气或日记余味,但不要暴露插件、模型、内部状态数值。 -- 禁止出现“能量”“心理能量”“/100”“状态变量”“当前状态”等内部汇报词。 -- 不要 @ 用户,不要泄露私聊内容,不要写得像营销文。 -- 写作角度:{theme_hint} - -【说说风格提示】 -{self._qzone_publish_style_prompt()} - -【当前时间与季节】 -{temporal_context} - -【公开可写的状态余味】 -{public_state_hint} - -【当前/附近日程】 -{current_schedule_hint or "无明确日程"} - -【近日私密日记余味】 -{diary_context or "暂无"} - -【我会牢牢记住你 公开可写生活参考】 -{memory_context or "暂无"} -使用方式:只选公开可写、不会泄露私聊或内部记忆来源的生活连续性。 - -【最近说说去重】 -{recent_publish_context or "暂无最近记录。"} - -{relationship_authority_guard} - -{self._format_worldview_adaptation_prompt()} -""".strip() - try: - draft = await self._llm_call( - prompt, - max_tokens=180, - provider_id=self._task_provider(self.mai_style_provider_id, self.llm_provider_id), - task="qzone_publish_test", - ) - draft = await self._sanitize_qzone_life_post_text(draft, prompt=prompt) - except Exception as exc: - draft = "" - lines.append(f"- 草稿生成:失败,{_single_line(exc, 160)}") - if draft: - lines.append("- 草稿生成:成功") - lines.append(f"- 将传入工具参数:{{\"text\":\"{draft}\"}}") - lines.append(f"- 草稿正文:{draft}") - else: - lines.append("- 草稿生成:失败或为空") - image_enabled = bool(getattr(self, "enable_qzone_generated_image_publish", False)) - image_probability = max(0.0, min(1.0, _safe_float(getattr(self, "qzone_generated_image_probability", 0.25), 0.25))) - generator_available = callable(getattr(self, "_generate_photo_image", None)) - backend_summary = "" - summary_getter = getattr(self, "_photo_generation_backend_config_summary", None) - if callable(summary_getter): - try: - backend_summary = _single_line(summary_getter(), 180) - except Exception: - backend_summary = "" - prefix = self._qzone_reason_prefix("life_publish") - last_image_status = _single_line(qzone_state.get(f"last_{prefix}_generated_image_status"), 80) - last_image_note = _single_line(qzone_state.get(f"last_{prefix}_generated_image_note"), 160) - lines.append( - "- 配图预检:" - f"开关={'开启' if image_enabled else '关闭'}," - f"概率={image_probability:.0%}," - f"生图入口={'可用' if generator_available else '不可用'}" - ) - if backend_summary: - lines.append(f"- 生图后端:{backend_summary}") - if last_image_status or last_image_note: - lines.append(f"- 上次配图状态:{last_image_status or '-'} {last_image_note or ''}".rstrip()) - if image_enabled and image_probability <= 0: - lines.append("- 配图结论:概率为 0,不会自动带图。") - elif not image_enabled: - lines.append("- 配图结论:说说配图开关未开启,不会自动带图。") - elif not generator_available: - lines.append("- 配图结论:缺少生图入口,不会自动带图。") - else: - lines.append("- 配图结论:满足发布条件时会按概率尝试生成 1 张配图;生成失败会回退纯文字。") - lines.append("结果:模拟完成。若要真实发布,请使用 `陪伴 发说说 <正文>` 或让模型调用带 text 的 `pc_qzone_publish_feed`。") - return "\n".join(lines) - - async def _test_qzone_publish_image_chain(self, event: AstrMessageEvent | None = None) -> str: - lines = ["QQ 空间配图链路测试:"] - lines.append("- 真实发布:否,本指令只生成草稿和配图,不发 QQ 空间") - image_enabled = bool(getattr(self, "enable_qzone_generated_image_publish", False)) - image_probability = max(0.0, min(1.0, _safe_float(getattr(self, "qzone_generated_image_probability", 0.25), 0.25))) - generator_available = callable(getattr(self, "_generate_photo_image", None)) - lines.append(f"- 配图开关:{'开启' if image_enabled else '关闭'}") - lines.append(f"- 自动配图概率:{image_probability:.0%}(本测试会绕过概率,只检查生图链路)") - lines.append(f"- 生图入口:{'可用' if generator_available else '不可用'}") - if not self._qzone_platform_supported(event): - lines.append(f"结果:{self._qzone_platform_unavailable_message()}") - return "\n".join(lines) - summary_getter = getattr(self, "_photo_generation_backend_config_summary", None) - if callable(summary_getter): - try: - backend_summary = _single_line(summary_getter(), 180) - except Exception: - backend_summary = "" - if backend_summary: - lines.append(f"- 生图后端:{backend_summary}") - if not self.enable_qzone_integration: - lines.append("结果:QQ 空间动态层未启用,配图测试取消。") - return "\n".join(lines) - if not image_enabled: - lines.append("结果:说说配图开关未开启,配图测试取消。") - return "\n".join(lines) - if not generator_available: - lines.append("结果:缺少主动生图入口,配图测试取消。") - return "\n".join(lines) - - state = self._qzone_state_dict() - daily_state = self.data.get("daily_state", {}) - current_item = self._get_current_plan_item(self.data.get("daily_plan", {})) - diary_context = self._recent_diary_context(count=2) - public_state_hint = self._qzone_relationship_safe_source( - self._qzone_public_state_hint(daily_state if isinstance(daily_state, dict) else {}), - source="qzone.publish_image_test.current_state", - ) - current_schedule_hint = self._qzone_relationship_safe_source( - self._format_plan_item_for_prompt(current_item), - source="qzone.publish_image_test.current_schedule", - ) - diary_context = self._qzone_relationship_safe_source( - diary_context, - source="qzone.publish_image_test.recent_diary", - ) - relationship_authority_guard = self._qzone_relationship_authority_guard() - prompt = f""" -请以当前 Bot 人格写一条 QQ 空间说说,用来测试配图生成。 -只输出说说正文,不要解释,不要加标题。 - -要求: -- 30 到 100 字。 -- 像自然生活动态,最好包含一个能被画出来的具体场景或物件。 -- 不要 @ 用户,不要泄露私聊内容,不要出现插件、模型、系统提示、内部状态数值。 -- 写作角度:{self._qzone_publish_theme_hint()} - -【说说风格提示】 -{self._qzone_publish_style_prompt()} - -【当前时间与季节】 -{self._qzone_temporal_context()} - -【公开可写的状态余味】 -{public_state_hint} - -【当前/附近日程】 -{current_schedule_hint or "无明确日程"} - -【近日私密日记余味】 -{diary_context or "暂无"} - -【最近说说去重】 -{self._qzone_recent_publish_context(state) or "暂无最近记录。"} - -{relationship_authority_guard} - -{self._format_worldview_adaptation_prompt()} -""".strip() - try: - draft = await self._llm_call( - prompt, - max_tokens=160, - provider_id=self._task_provider(self.mai_style_provider_id, self.llm_provider_id), - task="qzone_publish_image_test_draft", - ) - draft = await self._sanitize_qzone_life_post_text(draft, prompt=prompt) - except Exception as exc: - lines.append(f"结果:草稿生成失败,{_single_line(exc, 160)}") - return "\n".join(lines) - if not draft: - lines.append("结果:草稿为空或不安全,配图测试取消。") - return "\n".join(lines) - lines.append(f"- 草稿正文:{draft}") - images = await self._maybe_generate_qzone_publish_image( - post_text=draft, - reason="life_publish", - daily_state=daily_state if isinstance(daily_state, dict) else {}, - current_item=current_item, - diary_context=diary_context, - state=state, - force=True, - ) - prefix = self._qzone_reason_prefix("life_publish") - status = _single_line(state.get(f"last_{prefix}_generated_image_status"), 80) - note = _single_line(state.get(f"last_{prefix}_generated_image_note"), 160) - backend = _single_line(state.get(f"last_{prefix}_generated_image_backend"), 60) - caption = _single_line(state.get(f"last_{prefix}_generated_image_caption"), 160) - visual_anchor = _single_line(state.get(f"last_{prefix}_generated_image_anchor"), 120) - composition = _single_line(state.get(f"last_{prefix}_generated_image_composition"), 120) - reference_image = _single_line(state.get(f"last_{prefix}_generated_image_reference"), 220) - reference_exists = bool(state.get(f"last_{prefix}_generated_image_reference_exists", False)) - if callable(getattr(self, "_save_data_sync", None)): - try: - self._save_data_sync() - except Exception: - pass - if images: - lines.append("- 生图结果:成功") - if backend: - lines.append(f"- 后端:{backend}") - if caption: - lines.append(f"- 画面说明:{caption}") - if visual_anchor: - lines.append(f"- 视觉锚点:{visual_anchor}") - if composition: - lines.append(f"- 构图:{composition}") - if reference_image: - lines.append(f"- 自拍参考图:{'可用' if reference_exists else '不可用'} {_single_line(reference_image, 160)}") - lines.append(f"- 图片路径:{_single_line(images[0], 220)}") - lines.append("结果:配图生成链路可用。下一步可用 `陪伴 发说说 <正文>` 或等待自动说说验证上传。") - else: - lines.append(f"- 生图结果:{status or '失败'}") - if note: - lines.append(f"- 原因:{note}") - if visual_anchor: - lines.append(f"- 视觉锚点:{visual_anchor}") - if composition: - lines.append(f"- 构图:{composition}") - if reference_image: - lines.append(f"- 自拍参考图:{'可用' if reference_exists else '不可用'} {_single_line(reference_image, 160)}") - lines.append("结果:没有生成可用于说说的图片。") - return "\n".join(lines) - - async def _test_qzone_integration(self, event: AstrMessageEvent | None, target_id: str = "") -> str: - lines = ["QQ 空间测试:"] - - lines.append(f"- 整合开关:{'开启' if self.enable_qzone_integration else '关闭'}") - lines.append("- 内置服务:可用") - lines.append("- 外部插件依赖:无") - - if not self._qzone_platform_supported(event): - lines.append(f"结果:{self._qzone_platform_unavailable_message()}") - return "\n".join(lines) - - if not self.enable_qzone_integration: - lines.append("结果:整合开关关闭。") - return "\n".join(lines) - - target = _single_line(target_id, 40) - try: - cookie_header = await self._qzone_get_cookies(event) - ctx = self._qzone_context_from_cookies(cookie_header) - target = target or str(ctx.get("uin") or "") - lines.append(f"- Cookie:已获取,登录 QQ {ctx.get('uin')}") - lines.append("- 读取动态:可用") - lines.append("- 发布说说:可用") - lines.append("- 点赞/评论:可用") - posts = await self._qzone_query_feeds( - event, - target_id=target or None, - pos=0, - num=1, - with_detail=True, - cookie_header=cookie_header, - ) - if not posts: - lines.append(f"- 查询目标:{target or '默认'}") - lines.append("- 查询结果:空") - lines.append("结果:读取链路可调用,但没有拿到动态。") - return "\n".join(lines) - post = posts[0] - text = _single_line(getattr(post, "text", "") or getattr(post, "rt_con", ""), 120) - images = list(getattr(post, "images", []) or []) - lines.append(f"- 查询目标:{target or '默认'}") - lines.append("- 查询结果:成功") - lines.append(f"- 作者:{_single_line(getattr(post, 'name', ''), 40) or '未知'}") - lines.append(f"- QQ:{str(getattr(post, 'uin', '') or '') or '未知'}") - lines.append(f"- 内容:{text or '无文本'}") - lines.append(f"- 图片数:{len(images)}") - lines.append("结果:QQ 空间读取链路正常。") - return "\n".join(lines) - except Exception as exc: - lines.append(f"- 查询目标:{target or '默认'}") - error_text = _single_line(exc, 160) - if "空响应" in error_text: - error_text = "接口返回空响应,通常表示目标空间不可见、无权限访问,或当前 Cookie 对该目标无访问权" - lines.append(f"- 查询结果:失败:{error_text}") - lines.append("结果:内置服务已加载,但 QQ 空间访问失败。") - return "\n".join(lines) - - @staticmethod - def _qzone_reason_prefix(reason: str) -> str: - if reason == "emotional_vent": - return "emotional_vent" - if reason == "manual_publish": - return "manual_publish" - return "life_publish" - - def _qzone_reusable_draft(self, state: dict[str, Any], reason: str, *, now: float | None = None, max_age_hours: float = 72.0) -> str: - if not isinstance(state, dict): - return "" - prefix = self._qzone_reason_prefix(reason) - status = str(state.get(f"last_{prefix}_status") or "").strip() - if not (status.startswith("failed:") or status.startswith("paused:") or status.startswith("retrying:")): - return "" - current = _now_ts() if now is None else float(now) - draft_at = _safe_float(state.get(f"last_{prefix}_draft_at"), 0) - if not draft_at or current - draft_at > max(1.0, float(max_age_hours)) * 3600: - return "" - draft_key = f"last_{prefix}_draft" - draft = _single_line(state.get(draft_key), 300) - cleaned = _single_line( - self._qzone_relationship_safe_source( - draft, - source=f"qzone.reusable_draft.{prefix}", - ), - 300, - ) - if cleaned != draft: - state[draft_key] = cleaned - if len(cleaned) < 12: - state.pop(draft_key, None) - state.pop(f"last_{prefix}_draft_at", None) - return "" - return cleaned - - def _qzone_reusable_generated_image(self, state: dict[str, Any], reason: str, post_text: str, *, now: float | None = None) -> list[str]: - if not isinstance(state, dict): - return [] - prefix = self._qzone_reason_prefix(reason) - current = _now_ts() if now is None else float(now) - image_at = _safe_float(state.get(f"last_{prefix}_generated_image_at"), 0) - if not image_at or current - image_at > 72 * 3600: - return [] - stored_text = _single_line(state.get(f"last_{prefix}_generated_image_text"), 300) - if stored_text and stored_text != _single_line(post_text, 300): - return [] - image_path = str(state.get(f"last_{prefix}_generated_image_path") or "").strip() - if not image_path: - return [] - if not re.match(r"^(?:https?://|file://|data:)", image_path, flags=re.I) and not Path(image_path).exists(): - return [] - logger.info("[PrivateCompanion] QQ 空间复用待发布配图: reason=%s path=%s", reason, _single_line(image_path, 160)) - return [image_path] - - def _qzone_note_publish_image_status( - self, - state: dict[str, Any] | None, - reason: str, - status: str, - note: Any = "", - *, - path: Any = "", - backend: Any = "", - caption: Any = "", - reference_image: Any = "", - reference_exists: bool | None = None, - visual_anchor: Any = "", - composition: Any = "", - ) -> None: - if not isinstance(state, dict): - return - prefix = self._qzone_reason_prefix(reason) - state[f"last_{prefix}_generated_image_status"] = _single_line(status, 60) - state[f"last_{prefix}_generated_image_note"] = _single_line(note, 180) - state[f"last_{prefix}_generated_image_checked_at"] = _now_ts() - if path: - state[f"last_{prefix}_generated_image_path"] = _single_line(path, 260) - if backend: - state[f"last_{prefix}_generated_image_backend"] = _single_line(backend, 40) - if caption: - state[f"last_{prefix}_generated_image_caption"] = _single_line(caption, 180) - if reference_image: - state[f"last_{prefix}_generated_image_reference"] = _single_line(reference_image, 260) - if reference_exists is not None: - state[f"last_{prefix}_generated_image_reference_exists"] = bool(reference_exists) - if visual_anchor: - state[f"last_{prefix}_generated_image_anchor"] = _single_line(visual_anchor, 120) - if composition: - state[f"last_{prefix}_generated_image_composition"] = _single_line(composition, 120) - - def _qzone_clear_pending_publish_assets(self, state: dict[str, Any], reason: str) -> None: - if not isinstance(state, dict): - return - prefix = self._qzone_reason_prefix(reason) - for key in ( - f"last_{prefix}_draft", - f"last_{prefix}_draft_at", - f"last_{prefix}_generated_image_path", - f"last_{prefix}_generated_image_at", - f"last_{prefix}_generated_image_text", - f"last_{prefix}_generated_image_reference", - f"last_{prefix}_generated_image_reference_exists", - f"last_{prefix}_generated_image_anchor", - f"last_{prefix}_generated_image_composition", - ): - state.pop(key, None) - - async def _maybe_generate_qzone_publish_image( - self, - *, - post_text: str, - reason: str, - daily_state: dict[str, Any] | None = None, - current_item: Any = None, - diary_context: str = "", - state: dict[str, Any] | None = None, - force: bool = False, - ) -> list[str]: - reusable = [] if force else self._qzone_reusable_generated_image(state if isinstance(state, dict) else {}, reason, post_text) - if reusable: - self._qzone_note_publish_image_status(state, reason, "reused", "复用上次待发布配图", path=reusable[0]) - return reusable - if not ( - getattr(self, "enable_qzone_generated_image_publish", False) - and getattr(self, "enable_qzone_integration", False) - ): - self._qzone_note_publish_image_status(state, reason, "skipped:disabled", "QQ 空间配图开关未开启") - return [] - probability = max(0.0, min(1.0, _safe_float(getattr(self, "qzone_generated_image_probability", 0.25), 0.25))) - if not force and (probability <= 0 or random.random() > probability): - self._qzone_note_publish_image_status(state, reason, "skipped:probability", f"未命中配图概率 {probability:.0%}") - return [] - if callable(getattr(self, "_daily_token_soft_limit_should_defer", None)) and self._daily_token_soft_limit_should_defer("photo_prompt"): - logger.info("[PrivateCompanion] QQ 空间主动配图跳过: token_soft_limit") - self._qzone_note_publish_image_status(state, reason, "skipped:token_budget", "token 软上限保护") - return [] - generator = getattr(self, "_generate_photo_image", None) - if not callable(generator): - logger.info("[PrivateCompanion] QQ 空间主动配图跳过: image_generator_unavailable") - self._qzone_note_publish_image_status(state, reason, "skipped:no_generator", "缺少 _generate_photo_image 生图入口") - return [] - - style_name, style_instruction = self._get_photo_style_instruction() - post_text = self._qzone_relationship_safe_source(post_text, source="qzone.image.post_text") - current_desc = self._qzone_relationship_safe_source( - self._format_plan_item_for_prompt(current_item), - source="qzone.image.current_schedule", - ) or "无明确日程" - state_desc = self._qzone_relationship_safe_source( - self._qzone_public_state_hint(daily_state if isinstance(daily_state, dict) else {}), - source="qzone.image.current_state", - ) - diary_context = self._qzone_relationship_safe_source( - diary_context, - source="qzone.image.recent_diary", - ) - content_options = "" - try: - content_options = self._format_content_choice_options_for_prompt() - except Exception: - content_options = "生活小物、窗边光影、路上风景、桌面一角、随手自拍、偶遇小动物。" - content_options = self._qzone_relationship_safe_source( - content_options, - source="qzone.image.content_options", - ) - relationship_authority_guard = self._qzone_relationship_authority_guard() - qzone_selfie_reference_path = "" - qzone_selfie_reference_exists = False - reference_getter = getattr(self, "_photo_persona_reference_image_for_kind_async", None) - if callable(reference_getter): - try: - qzone_selfie_reference_path = await reference_getter( - "selfie", - allow_daily_outfit=True, - selection_context=f"说说:{post_text}\n当前日程:{current_desc}\n当前状态:{state_desc}", - ) - except Exception as ref_exc: - logger.info( - "[PrivateCompanion] QQ 空间自拍参考图预检失败: reason=%s error=%s", - _single_line(reason, 40), - _single_line(ref_exc, 120), - ) - qzone_selfie_reference_path = "" - try: - qzone_selfie_reference_exists = bool( - qzone_selfie_reference_path and Path(str(qzone_selfie_reference_path)).exists() - ) - except (OSError, ValueError): - qzone_selfie_reference_exists = False - reference_text = ( - "有可用参考图。可以选择 selfie 让人物自然入镜,但不要默认镜前自拍;只有正文或日程明确需要穿搭/照镜子时才用镜前构图。选择 selfie 时 prompt 必须写明保持参考图中的人物身份、脸部、发色、瞳色、穿搭连续性。" - if qzone_selfie_reference_path - else "当前没有可用自拍参考图。可以让人物自然入镜,人物外貌参考人格描述和公开状态;优先使用第一视角手部、侧脸、背影、肩颈半身、影子、随身小物等不强依赖精确脸部的方式,避免凭空追加人格里没有的脸部细节,也不要默认镜前自拍。" - ) - prompt = f""" -请为一条即将公开发布到 QQ 空间的说说生成一张配图提示词。 -只输出 JSON,不要解释。 - -【说说正文】 -{_single_line(post_text, 300)} - -【人格】 -{self._get_default_persona_prompt()} - -【公开可写的状态余味】 -{state_desc} - -【当前/附近日程】 -{current_desc} - -【近日日记余味】 -{_single_line(diary_context, 500) or "暂无"} - -{self._format_worldview_adaptation_prompt()} - -{relationship_authority_guard} - -【可选画面方向】 -{content_options} - -【自拍参考图状态】 -{reference_text} - -【空间配图风格提示】 -{self._qzone_publish_image_style_prompt()} - -【生图风格】 -{style_name} -风格要求:{style_instruction} - -输出 JSON: -{{ - "kind": "selfie 或 text2img;按说说正文选择,不要固定优先镜前自拍", - "visual_anchor": "本图唯一视觉锚点,例如第一视角手部与饮品/桌面小物/路上夕光/侧脸看窗边光影/背影走在路上/餐盘与衣袖;必须具体", - "composition": "构图一句话,例如第一视角手部近景/桌面俯拍/侧脸三分构图/背影环境中景/路边半身随拍/窗边剪影;镜前自拍只能偶尔使用", - "prompt": "给生图后端的中文提示词,包含唯一主体、场景、光线、构图、情绪和风格;不要写聊天口吻", - "caption": "一句画面说明" -}} - -要求: -1. 图片必须像公开动态配图,不要包含私聊、系统、插件、模型、内部状态数值。 -2. 先确定一个“唯一视觉锚点”,不要把多个主体拼在一张图里;画面要贴合说说正文和当前日程,不要为了配图硬画无关内容。 -3. 人物可以入镜,但不要每次都自拍;在第一视角手部、桌面小物、食物饮品、路上光影、窗边侧脸、背影、影子、随身小物和半身随拍之间轮换。 -4. 镜前自拍、镜中自拍、手机挡脸自拍不是默认模板;只有正文/日程明确涉及穿搭、整理仪容、出门前照镜子或房间镜子时才使用,且不要连续复用。 -5. 如果有自拍参考图,选择 selfie 时必须写清“保留参考图人物身份和外观”“脸部完整清晰”“不要裁脸/遮脸/只拍身体局部”,并让场景来自当前日程;但仍要优先考虑非镜前构图。 -6. 如果没有自拍参考图,仍可选择人物入镜;人物外貌以人格描述、公开状态和风格设定为准,不要追加人格里没有的脸部细节。优先使用不强依赖精确脸部的自然入镜方式,比如侧脸、背影、第一视角手部、肩颈半身、窗边剪影。 -7. 如果选择 text2img:也可以保留人的存在感,如手边物件、脚步、背影、影子或随身小物;只有画面确实不适合人物入镜时才纯物件/纯风景。 -8. 不要包含 NSFW、真实用户隐私、聊天截图或电脑屏幕内容;避免文字、水印、UI、二维码、聊天气泡。 -9. prompt 必须体现上面的生图风格要求,且不能是泛泛的“好看的照片/生活记录/天气图”。 -""".strip() - try: - text = await self._llm_call( - prompt, - max_tokens=360, - provider_id=self._task_provider(self.photo_prompt_provider_id, self.mai_style_provider_id), - task=f"qzone_{reason}_photo_prompt", - ) - payload = self._extract_json_payload(text or "") - if isinstance(payload, dict): - workflow_kind = _single_line(payload.get("kind"), 60).lower() - visual_anchor = _single_line(payload.get("visual_anchor"), 120) - composition = _single_line(payload.get("composition"), 120) - image_prompt = _single_line(payload.get("prompt"), 600) - caption = _single_line(payload.get("caption"), 180) - else: - workflow_kind = "text2img" - visual_anchor = "" - composition = "" - image_prompt = _single_line(text, 600) - caption = image_prompt - if any(token in workflow_kind for token in ("selfie", "portrait", "自拍", "人像", "人物", "出镜")): - workflow_kind = "selfie" - elif any(token in workflow_kind for token in ("text2img", "scene", "photo", "风景", "静物", "物件")): - workflow_kind = "text2img" - else: - workflow_kind = "text2img" - if not image_prompt: - image_prompt = f"QQ 空间公开动态配图,{_single_line(post_text, 160)},{style_instruction}" - if visual_anchor and visual_anchor not in image_prompt: - image_prompt = f"唯一视觉锚点:{visual_anchor}。{image_prompt}" - if composition and composition not in image_prompt: - image_prompt = f"{image_prompt}。构图:{composition}" - if workflow_kind == "selfie": - if qzone_selfie_reference_path: - image_prompt = ( - f"{image_prompt}。保留参考图中的人物身份、脸部、发色、瞳色和穿搭连续性;" - "脸部完整清晰,头发、肩颈和上半身自然入镜;不要裁脸、遮脸、背影、只拍身体局部。" - ) - else: - image_prompt = ( - f"{image_prompt}。人物是画面主角,外貌参考人格描述、公开状态和风格设定;没有可用自拍参考图时不要追加人格里没有的脸部细节;" - "优先使用第一视角手部、侧脸、背影、肩颈半身、窗边剪影、随身小物等自然入镜方式;不要默认镜前自拍或手机挡脸自拍,保持公开动态随手拍质感。" - ) - else: - image_prompt = ( - f"{image_prompt}。画面像 QQ 空间公开生活配图,单一主体清楚,不出现聊天截图、UI、二维码、水印或虚构人物脸部。" - ) - reference_image_path = qzone_selfie_reference_path if workflow_kind == "selfie" else "" - reference_exists = qzone_selfie_reference_exists if workflow_kind == "selfie" else False - logger.info( - "[PrivateCompanion] QQ 空间配图生图开始: reason=%s kind=%s anchor=%s composition=%s reference=%s reference_exists=%s post=%s prompt=%s", - _single_line(reason, 40), - _single_line(workflow_kind, 30), - _single_line(visual_anchor, 80) or "-", - _single_line(composition, 80) or "-", - bool(reference_image_path), - reference_exists, - _single_line(post_text, 120), - _single_line(image_prompt, 180), - ) - backend_name, image_path, workflow_note = await generator( - workflow_kind=workflow_kind, - prompt_text=image_prompt, - session_key=f"qzone_{reason}", - reference_image_path=reference_image_path, - ) - except Exception as exc: - logger.info("[PrivateCompanion] QQ 空间主动配图失败: %s", _single_line(exc, 120)) - self._qzone_note_publish_image_status( - state, - reason, - "failed:prompt_or_generate", - exc, - reference_image=qzone_selfie_reference_path, - reference_exists=qzone_selfie_reference_exists, - ) - return [] - if not image_path: - logger.info("[PrivateCompanion] QQ 空间主动配图跳过: %s", _single_line(workflow_note, 160)) - self._qzone_note_publish_image_status( - state, - reason, - "failed:no_image", - workflow_note, - backend=backend_name, - reference_image=reference_image_path, - reference_exists=reference_exists, - visual_anchor=visual_anchor, - composition=composition, - ) - return [] - if not re.match(r"^(?:https?://|file://|data:)", str(image_path), flags=re.I) and not Path(str(image_path)).exists(): - logger.info("[PrivateCompanion] QQ 空间主动配图跳过: image_path_missing path=%s", _single_line(image_path, 160)) - self._qzone_note_publish_image_status( - state, - reason, - "failed:path_missing", - "生图返回路径不存在", - path=image_path, - backend=backend_name, - reference_image=reference_image_path, - reference_exists=reference_exists, - visual_anchor=visual_anchor, - composition=composition, - ) - return [] - if isinstance(state, dict): - prefix = self._qzone_reason_prefix(reason) - state["last_generated_image_path"] = _single_line(image_path, 260) - state["last_generated_image_at"] = _now_ts() - state["last_generated_image_reason"] = reason - state["last_generated_image_caption"] = _single_line(caption, 180) - state["last_generated_image_backend"] = _single_line(backend_name, 40) - if visual_anchor: - state["last_generated_image_anchor"] = _single_line(visual_anchor, 120) - if composition: - state["last_generated_image_composition"] = _single_line(composition, 120) - if reference_image_path: - state["last_generated_image_reference"] = _single_line(reference_image_path, 260) - state["last_generated_image_reference_exists"] = bool(reference_exists) - state[f"last_{prefix}_generated_image_path"] = _single_line(image_path, 260) - state[f"last_{prefix}_generated_image_at"] = _now_ts() - state[f"last_{prefix}_generated_image_text"] = _single_line(post_text, 300) - state[f"last_{prefix}_generated_image_caption"] = _single_line(caption, 180) - state[f"last_{prefix}_generated_image_backend"] = _single_line(backend_name, 40) - if visual_anchor: - state[f"last_{prefix}_generated_image_anchor"] = _single_line(visual_anchor, 120) - if composition: - state[f"last_{prefix}_generated_image_composition"] = _single_line(composition, 120) - self._qzone_note_publish_image_status( - state, - reason, - "generated", - workflow_note or "ok", - path=image_path, - backend=backend_name, - caption=caption, - reference_image=reference_image_path, - reference_exists=reference_exists, - visual_anchor=visual_anchor, - composition=composition, - ) - logger.info( - "[PrivateCompanion] QQ 空间主动配图完成: reason=%s backend=%s reference=%s reference_exists=%s path=%s", - reason, - _single_line(backend_name, 40), - bool(reference_image_path), - reference_exists, - _single_line(image_path, 160), - ) - return [image_path] - - async def _maybe_publish_qzone_life_post(self) -> None: - if not (self._qzone_available() and self.enable_qzone_life_publish): - return - now = _now_ts() - state = self.data.setdefault("qzone_integration", {}) - if not isinstance(state, dict): - self.data["qzone_integration"] = {} - state = self.data["qzone_integration"] - last_status = str(state.get("last_life_publish_status") or "").strip() - if ( - last_status == "published" - and now - _safe_float(state.get("last_life_publish_at"), 0) < max(4, self.qzone_life_publish_min_interval_hours) * 3600 - ): - return - block_reason = self._qzone_auto_publish_block_reason(state, now=now) - if block_reason: - state["last_life_publish_status"] = f"paused:auth:{_single_line(block_reason, 80)}" - state["last_life_publish_checked_at"] = now - self._save_data_sync() - return - if now - _safe_float(state.get("last_life_publish_failed_at"), 0) < 15 * 60: - return - reusable_text = self._qzone_reusable_draft(state, "life_publish", now=now) - if not reusable_text and random.random() > self.qzone_life_publish_probability: - state["last_life_publish_status"] = "skipped:probability_miss" - state["last_life_publish_checked_at"] = now - self._save_data_sync() - return - preflight_error = await self._qzone_preflight_auto_publish(None, state=state, source="life_publish") - if preflight_error: - state["last_life_publish_failed_at"] = now - state["last_life_publish_status"] = f"paused:auth:{_single_line(preflight_error, 80)}" - state["last_life_publish_checked_at"] = now - self._save_data_sync() - return - daily_state = self.data.get("daily_state", {}) - current_item = self._get_current_plan_item(self.data.get("daily_plan", {})) - diary_context = self._recent_diary_context(count=2) - theme_hint = self._qzone_publish_theme_hint() - temporal_context = self._qzone_temporal_context() - recent_publish_context = self._qzone_recent_publish_context(state) - memory_context = await self._qzone_memory_companion_context( - purpose="publish", - query="QQ空间生活说说 今日公开可写生活 当前日程 今日穿搭 最近吃饭 日记余味 自我时间线", - ) - public_state_hint = self._qzone_relationship_safe_source( - self._qzone_public_state_hint(daily_state if isinstance(daily_state, dict) else {}), - source="qzone.publish.current_state", - ) - current_schedule_hint = self._qzone_relationship_safe_source( - self._format_plan_item_for_prompt(current_item), - source="qzone.publish.current_schedule", - ) - diary_context = self._qzone_relationship_safe_source( - diary_context, - source="qzone.publish.recent_diary", - ) - memory_context = self._qzone_relationship_safe_source( - memory_context, - source="qzone.publish.memory", - ) - relationship_authority_guard = self._qzone_relationship_authority_guard() - if reusable_text: - text = reusable_text - logger.info( - "[PrivateCompanion] QQ 空间复用待发布生活说说草稿: age=%ds", - int(now - _safe_float(state.get("last_life_publish_draft_at"), now)), - ) - else: - prompt = f""" -请以当前 Bot 人格写一条 QQ 空间说说。 -只输出说说正文,不要解释,不要加标题。 - -要求: -- 30 到 120 字。 -- 像自然生活动态,不是公告、不是任务汇报。 -- 可以带一点公开可见的心情、天气或日记余味,但不要暴露插件、模型、内部状态数值。 -- 禁止出现“能量”“心理能量”“/100”“状态变量”“当前状态”等内部汇报词。 -- 不要 @ 用户,不要泄露私聊内容,不要写得像营销文。 -- 写作角度:{theme_hint} - -【说说风格提示】 -{self._qzone_publish_style_prompt()} - -【当前时间与季节】 -{temporal_context} - -【公开可写的状态余味】 -{public_state_hint} - -【当前/附近日程】 -{current_schedule_hint or "无明确日程"} - -【近日私密日记余味】 -{diary_context or "暂无"} - -【我会牢牢记住你 公开可写生活参考】 -{memory_context or "暂无"} -使用方式:只选公开可写、不会泄露私聊或内部记忆来源的生活连续性。 - -【最近说说去重】 -{recent_publish_context or "暂无最近记录。"} - -{relationship_authority_guard} - -{self._format_worldview_adaptation_prompt()} -""".strip() - text = await self._llm_call( - prompt, - max_tokens=180, - provider_id=self._task_provider(self.mai_style_provider_id, self.llm_provider_id), - task="qzone_publish", - ) - text = await self._sanitize_qzone_life_post_text(text, prompt=prompt) - if not text: - state["last_life_publish_failed_at"] = now - state["last_life_publish_status"] = "cancelled:empty_or_unsafe_draft" - state["last_life_publish_checked_at"] = now - self._save_data_sync() - logger.warning("[PrivateCompanion] QQ 空间生活动态草稿为空或不安全,已跳过发布") - return - state["last_life_publish_draft"] = _single_line(text, 300) - state["last_life_publish_draft_at"] = now - if reusable_text: - image_sources = self._qzone_reusable_generated_image(state, "life_publish", text, now=now) - else: - image_sources = await self._maybe_generate_qzone_publish_image( - post_text=text, - reason="life_publish", - daily_state=daily_state if isinstance(daily_state, dict) else {}, - current_item=current_item, - diary_context=diary_context, - state=state, - ) - result = await self._publish_qzone_text(text, images=image_sources, publish_reason="life_publish") - if result.get("success"): - state["last_life_publish_at"] = now - state.pop("last_life_publish_failed_at", None) - state["last_life_publish_status"] = "published" - if result.get("image_fallback"): - self._qzone_note_publish_image_status( - state, - "life_publish", - "failed:upload_fallback", - result.get("image_fallback_message") or "配图发布失败,已降级纯文字发布", - ) - state["last_life_publish_image_fallback"] = { - "stage": _single_line(result.get("image_fallback_stage"), 40), - "message": _single_line(result.get("image_fallback_message"), 180), - "at": now, - } - else: - state.pop("last_life_publish_image_fallback", None) - self._qzone_clear_pending_publish_assets(state, "life_publish") - else: - state["last_life_publish_failed_at"] = now - state["last_life_publish_status"] = f"failed:{_single_line(result.get('message'), 80)}" - state["last_life_publish_checked_at"] = now - state["last_life_publish_text"] = _single_line(result.get("text") or text, 180) - state["last_life_publish_images"] = _safe_int(result.get("image_count"), len(result.get("images") or []), 0, 99) if result.get("success") else 0 - self._save_data_sync() - - async def _maybe_publish_qzone_emotional_vent( - self, - *, - user_snapshot: dict[str, Any] | None = None, - relationship_state: dict[str, Any] | None = None, - intent: dict[str, Any] | None = None, - ) -> None: - if not ( - self._qzone_available() - and getattr(self, "enable_emotion_simulation", False) - and getattr(self, "enable_qzone_emotional_vent_publish", False) - ): - return - rel_state = relationship_state if isinstance(relationship_state, dict) else {} - mood_score = abs(_safe_int(rel_state.get("mood_score"), 0, -100, 100)) - threshold = _safe_int(getattr(self, "qzone_emotional_vent_threshold", 90), 90, 40, 100) - if mood_score < threshold: - return - if isinstance(user_snapshot, dict): - role_getter = getattr(self, "_private_user_role", None) - try: - role = role_getter(user_snapshot, str(user_snapshot.get("user_id") or "")) if callable(role_getter) else "" - except Exception: - role = "" - if role != "owner": - logger.info( - "[PrivateCompanion] 公开心情动态跳过: user_role=%s score=%s", - role or "friend", - mood_score, - ) - return - now = _now_ts() - state = self.data.setdefault("qzone_integration", {}) - if not isinstance(state, dict): - self.data["qzone_integration"] = {} - state = self.data["qzone_integration"] - cooldown = max(4, _safe_int(getattr(self, "qzone_emotional_vent_cooldown_hours", 72), 72, 4, 336)) * 3600 - if now - _safe_float(state.get("last_emotional_vent_at"), 0) < cooldown: - logger.info("[PrivateCompanion] 公开心情动态跳过: cooldown score=%s", mood_score) - return - block_reason = self._qzone_auto_publish_block_reason(state, now=now) - if block_reason: - state["last_emotional_vent_status"] = f"paused:auth:{_single_line(block_reason, 80)}" - state["last_emotional_vent_checked_at"] = now - self._save_data_sync() - return - if now - _safe_float(state.get("last_emotional_vent_failed_at"), 0) < 15 * 60: - return - reusable_text = self._qzone_reusable_draft(state, "emotional_vent", now=now) - probability = max(0.0, min(1.0, _safe_float(getattr(self, "qzone_emotional_vent_probability", 0.35), 0.35))) - if not reusable_text and random.random() > probability: - state["last_emotional_vent_status"] = "skipped:probability_miss" - state["last_emotional_vent_checked_at"] = now - self._save_data_sync() - return - preflight_error = await self._qzone_preflight_auto_publish(None, state=state, source="emotional_vent") - if preflight_error: - state["last_emotional_vent_failed_at"] = now - state["last_emotional_vent_status"] = f"paused:auth:{_single_line(preflight_error, 80)}" - state["last_emotional_vent_checked_at"] = now - self._save_data_sync() - return - daily_state = self.data.get("daily_state", {}) - current_item = self._get_current_plan_item(self.data.get("daily_plan", {})) - public_state_hint = self._qzone_relationship_safe_source( - self._qzone_public_state_hint(daily_state if isinstance(daily_state, dict) else {}), - source="qzone.emotional_vent.current_state", - ) - current_schedule_hint = self._qzone_relationship_safe_source( - self._format_plan_item_for_prompt(current_item), - source="qzone.emotional_vent.current_schedule", - ) - reason = _single_line( - self._qzone_relationship_safe_source( - (rel_state or {}).get("last_hurt_reason") or (intent or {}).get("emotion_reason"), - source="qzone.emotional_vent.reason", - ), - 80, - ) - relationship_authority_guard = self._qzone_relationship_authority_guard() - prompt = f""" -请以当前 Bot 人格写一条 QQ 空间说说,表达一种模糊的低落、委屈或想透气的心情。 -只输出说说正文,不要解释,不要加标题。 - -要求: -- 20 到 80 字。 -- 像自然生活动态,不要像控诉、公告、任务汇报。 -- 不要 @ 用户,不要提到任何具体用户、私聊内容、聊天截图或“刚才谁说了什么”。 -- 不要出现“受伤分”“情绪分”“阈值”“插件”“模型”“Bot”“机器人”“/100”等内部词。 -- 可以写天气、夜色、窗边、散步、想安静一会儿这类公开可见的余味。 - -【说说风格提示】 -{self._qzone_publish_style_prompt(mood="emotional_vent")} - -【公开可写的状态余味】 -{public_state_hint} - -【当前/附近日程】 -{current_schedule_hint or "无明确日程"} - -【内部触发原因,只能作为情绪方向,禁止复述】 -{reason or "情绪有点低落"} - -{relationship_authority_guard} - -{self._format_worldview_adaptation_prompt()} -""".strip() - try: - if reusable_text: - text = reusable_text - logger.info( - "[PrivateCompanion] QQ 空间复用待发布心情动态草稿: age=%ds", - int(now - _safe_float(state.get("last_emotional_vent_draft_at"), now)), - ) - else: - text = await self._llm_call( - prompt, - max_tokens=140, - provider_id=self._task_provider(self.mai_style_provider_id, self.llm_provider_id), - task="qzone_emotional_vent", - ) - text = await self._sanitize_qzone_life_post_text(text, prompt=prompt) - if not text: - state["last_emotional_vent_failed_at"] = now - state["last_emotional_vent_status"] = "cancelled:empty_or_unsafe_draft" - state["last_emotional_vent_checked_at"] = now - self._save_data_sync() - logger.warning("[PrivateCompanion] 公开心情动态草稿为空或不安全,已跳过发布") - return - state["last_emotional_vent_draft"] = _single_line(text, 240) - state["last_emotional_vent_draft_at"] = now - if reusable_text: - image_sources = self._qzone_reusable_generated_image(state, "emotional_vent", text, now=now) - else: - image_sources = await self._maybe_generate_qzone_publish_image( - post_text=text, - reason="emotional_vent", - daily_state=daily_state if isinstance(daily_state, dict) else {}, - current_item=current_item, - diary_context="", - state=state, - ) - result = await self._publish_qzone_text(text, images=image_sources, publish_reason="emotional_vent") - if result.get("success"): - state["last_emotional_vent_at"] = now - state.pop("last_emotional_vent_failed_at", None) - state["last_emotional_vent_status"] = "published" - if result.get("image_fallback"): - self._qzone_note_publish_image_status( - state, - "emotional_vent", - "failed:upload_fallback", - result.get("image_fallback_message") or "配图发布失败,已降级纯文字发布", - ) - state["last_emotional_vent_image_fallback"] = { - "stage": _single_line(result.get("image_fallback_stage"), 40), - "message": _single_line(result.get("image_fallback_message"), 180), - "at": now, - } - else: - state.pop("last_emotional_vent_image_fallback", None) - self._qzone_clear_pending_publish_assets(state, "emotional_vent") - logger.info("[PrivateCompanion] 公开心情动态已发布: score=%s text=%s", mood_score, _single_line(result.get("text") or text, 120)) - else: - state["last_emotional_vent_failed_at"] = now - state["last_emotional_vent_status"] = f"failed:{_single_line(result.get('message'), 80)}" - logger.warning("[PrivateCompanion] 公开心情动态发布失败: %s", _single_line(result.get("message"), 120)) - state["last_emotional_vent_checked_at"] = now - state["last_emotional_vent_text"] = _single_line(result.get("text") or text, 180) - state["last_emotional_vent_images"] = _safe_int(result.get("image_count"), len(result.get("images") or []), 0, 99) if result.get("success") else 0 - self._save_data_sync() - except Exception as exc: - state["last_emotional_vent_failed_at"] = now - state["last_emotional_vent_status"] = f"failed:{_single_line(exc, 80)}" - state["last_emotional_vent_checked_at"] = now - self._save_data_sync() - logger.warning("[PrivateCompanion] 公开心情动态异常: %s", _single_line(exc, 160), exc_info=True) - diff --git a/qzone_media.py b/qzone_media.py deleted file mode 100644 index 42f89ad..0000000 --- a/qzone_media.py +++ /dev/null @@ -1,1020 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import annotations - -import asyncio -import base64 -import hashlib -import ipaddress -import mimetypes -import re -import socket -import time -from pathlib import Path -from types import SimpleNamespace -from typing import Any -from urllib.parse import parse_qs, unquote, urljoin, urlparse - -from astrbot.api import logger -from astrbot.api.event import AstrMessageEvent - -from .helpers import _now_ts, _safe_float, _safe_int, _single_line - - -QZONE_IMAGE_UPLOAD_URL = "https://up.qzone.qq.com/cgi-bin/upload/cgi_upload_image" -QZONE_PUBLISH_URL = "https://user.qzone.qq.com/proxy/domain/taotao.qzone.qq.com/cgi-bin/emotion_cgi_publish_v6" -QZONE_REMOTE_IMAGE_MAX_BYTES = 12 * 1024 * 1024 -QZONE_UNSAFE_MEDIA_HOSTS = {"localhost", "localhost.localdomain"} - - -class QzoneIntegrationError(RuntimeError): - """User-facing Qzone error with a coarse failure stage.""" - - def __init__(self, stage: str, message: str): - self.stage = stage - super().__init__(f"{stage}:{message}") - - -class QzoneMediaMixin: - """QZone image reading, upload and publish helpers.""" - - @staticmethod - def _qzone_auth_failure_message(message: Any) -> bool: - text = str(message or "").lower() - if not text: - return False - markers = ( - "code=-3000", - "请先登录", - "未登录", - "login", - "cookie", - "p_skey", - "pskey", - "skey", - "g_tk", - "gtk", - ) - return any(marker in text for marker in markers) - - def _qzone_state_dict(self) -> dict[str, Any]: - data = getattr(self, "data", None) - if not isinstance(data, dict): - return {} - state = data.setdefault("qzone_integration", {}) - if not isinstance(state, dict): - data["qzone_integration"] = {} - state = data["qzone_integration"] - return state - - def _qzone_format_block_until(self, ts: float) -> str: - try: - return time.strftime("%m-%d %H:%M", time.localtime(float(ts))) - except Exception: - return "" - - def _qzone_auto_publish_block_reason(self, state: dict[str, Any] | None = None, *, now: float | None = None) -> str: - state = state if isinstance(state, dict) else self._qzone_state_dict() - if not isinstance(state, dict): - return "" - current = _now_ts() if now is None else float(now) - until = _safe_float(state.get("auth_block_until"), 0) - if until <= current: - return "" - reason = _single_line(state.get("last_auth_failure_reason") or "QQ 空间登录状态异常", 100) - if ( - ("没有可用的 OneBot 连接" in reason or "未配置手动 QZONE_COOKIE" in reason) - and callable(getattr(self, "_qzone_find_runtime_bot", None)) - and self._qzone_find_runtime_bot() is not None - ): - self._qzone_clear_auth_failure(state) - return "" - if "qzonetoken" in reason.lower() or "qzonetoken 未在 H5 首页中找到" in reason: - self._qzone_clear_auth_failure(state) - return "" - until_text = self._qzone_format_block_until(until) - return f"{reason},自动说说已暂停到 {until_text}" if until_text else reason - - def _qzone_mark_auth_failure( - self, - reason: str, - *, - source: str = "", - cooldown_hours: float = 12.0, - state: dict[str, Any] | None = None, - save: bool = True, - ) -> None: - state = state if isinstance(state, dict) else self._qzone_state_dict() - if not isinstance(state, dict): - return - now = _now_ts() - clean_reason = _single_line(reason or "QQ 空间登录状态异常", 160) - last_failed_at = _safe_float(state.get("last_auth_failed_at"), 0) - previous_count = _safe_int(state.get("auth_failure_count"), 0, 0, 999) - if last_failed_at and now - last_failed_at > 7 * 24 * 3600: - previous_count = 0 - failure_count = previous_count + 1 - if failure_count <= 1: - effective_hours = max(1.0, float(cooldown_hours or 12.0)) - status = "blocked" - elif failure_count == 2: - effective_hours = 24.0 - status = "blocked" - else: - effective_hours = 24.0 * 7 - status = "stopped" - cooldown_seconds = effective_hours * 3600.0 - state["last_auth_failed_at"] = now - state["last_auth_failure_reason"] = clean_reason - state["last_auth_failure_source"] = _single_line(source, 40) - state["auth_failure_count"] = failure_count - state["auth_block_until"] = now + cooldown_seconds - state["last_auth_status"] = status - if status == "stopped": - logger.warning( - "[PrivateCompanion] QQ 空间认证连续失败,自动说说进入保守等待: count=%s until=%s reason=%s", - failure_count, - self._qzone_format_block_until(state["auth_block_until"]), - clean_reason, - ) - if save: - saver = getattr(self, "_save_data_sync", None) - if callable(saver): - try: - saver() - except Exception: - pass - - def _qzone_clear_auth_failure(self, state: dict[str, Any] | None = None) -> None: - state = state if isinstance(state, dict) else self._qzone_state_dict() - if not isinstance(state, dict): - return - changed = False - for key in ( - "auth_block_until", - "last_auth_status", - "auth_failure_count", - "last_auth_failure_source", - "last_auth_failure_reason", - ): - if key in state: - state.pop(key, None) - changed = True - for key in ("last_life_publish_status", "last_emotional_vent_status"): - value = str(state.get(key) or "") - if value.startswith("paused:auth:"): - state[key] = "ready:auth_ok" - changed = True - if changed: - saver = getattr(self, "_save_data_sync", None) - if callable(saver): - try: - saver() - except Exception: - pass - - async def _qzone_preflight_auto_publish( - self, - event: AstrMessageEvent | None, - *, - state: dict[str, Any] | None = None, - source: str = "auto", - ) -> str: - state = state if isinstance(state, dict) else self._qzone_state_dict() - block_reason = self._qzone_auto_publish_block_reason(state) - if block_reason: - return block_reason - try: - cookie_header = await self._qzone_get_cookies(event) - ctx = self._qzone_context_from_cookies(cookie_header) - token = ctx.get("qzonetoken") or await self._qzone_ensure_qzonetoken(event, cookie_header=cookie_header, ctx=ctx) - if not str(token or "").strip(): - state["last_qzonetoken_status"] = "missing:h5_index" - logger.info("[PrivateCompanion] QQ 空间自动发布预检继续: qzonetoken 未找到,纯文字发布仍可使用 g_tk") - else: - state["last_qzonetoken_status"] = "ok" - except Exception as exc: - reason = _single_line(exc, 160) - self._qzone_mark_auth_failure(reason, source=source, state=state, save=False) - return reason - self._qzone_clear_auth_failure(state) - return "" - - async def _qzone_ensure_qzonetoken( - self, - event: AstrMessageEvent | None, - *, - cookie_header: str, - ctx: dict[str, Any], - ) -> str: - token = str(ctx.get("qzonetoken") or "").strip() - if token: - return token - cache = getattr(self, "_qzone_qzonetoken_cache", None) - if not isinstance(cache, dict): - cache = {} - self._qzone_qzonetoken_cache = cache - cache_key = str(ctx.get("uin") or "") - cached = cache.get(cache_key) - if isinstance(cached, dict) and _now_ts() - _safe_float(cached.get("at"), 0) < 1800: - token = str(cached.get("token") or "").strip() - if token: - return token - - import aiohttp - - url = "https://h5.qzone.qq.com/mqzone/index" - headers = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36", - "Cookie": ctx.get("cookie_header") or cookie_header, - "Referer": f"https://user.qzone.qq.com/{ctx['uin']}", - "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", - } - try: - timeout = aiohttp.ClientTimeout(total=12) - async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session: - async with session.get(url) as response: - text = await response.text() - if response.status >= 400: - logger.info("[PrivateCompanion] QQ 空间 qzonetoken 获取失败: HTTP %s", response.status) - return "" - except Exception as exc: - logger.info("[PrivateCompanion] QQ 空间 qzonetoken 获取失败: %s", _single_line(exc, 120)) - return "" - match = re.search(r'window\.shine0callback.*?return\s+"([0-9a-f]+?)";', text, flags=re.S) - if not match: - logger.info("[PrivateCompanion] QQ 空间 qzonetoken 未在 H5 首页中找到") - return "" - token = match.group(1).strip() - if token: - cache[cache_key] = {"token": token, "at": _now_ts()} - logger.info("[PrivateCompanion] QQ 空间 qzonetoken 已自动获取: uin=%s", ctx.get("uin")) - return token - - @staticmethod - def _qzone_find_first(payload: Any, keys: tuple[str, ...], *, _depth: int = 0, _seen: set[int] | None = None) -> Any: - if payload is None or _depth > 8: - return None - if _seen is None: - _seen = set() - if isinstance(payload, dict): - obj_id = id(payload) - if obj_id in _seen: - return None - _seen.add(obj_id) - normalized = {str(key).lower().replace("-", "_"): value for key, value in payload.items()} - for key in keys: - value = normalized.get(str(key).lower().replace("-", "_")) - if value not in (None, ""): - return value - for value in payload.values(): - found = QzoneMediaMixin._qzone_find_first(value, keys, _depth=_depth + 1, _seen=_seen) - if found not in (None, ""): - return found - elif isinstance(payload, (list, tuple)): - for item in payload: - found = QzoneMediaMixin._qzone_find_first(item, keys, _depth=_depth + 1, _seen=_seen) - if found not in (None, ""): - return found - return None - - async def _qzone_call_platform_action(self, event: AstrMessageEvent | None, action: str, **kwargs: Any) -> Any: - if event is None: - return None - caller = getattr(self, "_call_platform_action", None) - if callable(caller): - try: - return await caller(event, action, **kwargs) - except Exception: - pass - bot = getattr(event, "bot", None) - direct = getattr(bot, action, None) - if callable(direct): - try: - maybe = direct(**kwargs) - return await maybe if hasattr(maybe, "__await__") else maybe - except Exception: - pass - api = getattr(bot, "api", None) - call_action = getattr(api, "call_action", None) - if callable(call_action): - try: - maybe = call_action(action, **kwargs) - return await maybe if hasattr(maybe, "__await__") else maybe - except Exception: - return None - return None - - async def _qzone_resolve_onebot_image_source(self, event: AstrMessageEvent | None, source: str) -> str: - text = str(source or "").strip() - if not text or event is None: - return "" - if Path(text).exists() or re.match(r"^(?:https?://|file://|data:|base64://)", text, flags=re.I): - return "" - attempts = ( - ("get_image", {"file": text}), - ("get_image", {"file_id": text}), - ("get_file", {"file": text}), - ("get_file", {"file_id": text}), - ) - for action, kwargs in attempts: - result = await self._qzone_call_platform_action(event, action, **kwargs) - if not result: - continue - for key_group in ( - ("path", "file_path", "local_path", "local_file", "file"), - ("url", "origin_url", "source_url"), - ): - found = self._qzone_find_first(result, key_group) - candidate = str(found or "").strip() - if candidate and candidate != text: - return candidate - return "" - - @staticmethod - def _qzone_guess_image_type(source: str, image_bytes: bytes, content_type: str = "") -> tuple[str, str]: - probe = (content_type or mimetypes.guess_type(str(source or ""))[0] or "").lower() - head = image_bytes[:16] - if head.startswith(b"\x89PNG\r\n\x1a\n") or "png" in probe: - return "png", "image/png" - if head.startswith(b"GIF8") or "gif" in probe: - return "gif", "image/gif" - if (head.startswith(b"RIFF") and b"WEBP" in image_bytes[:32]) or "webp" in probe: - return "webp", "image/webp" - return "jpg", "image/jpeg" - - @staticmethod - def _qzone_supported_image_header(image_bytes: bytes) -> bool: - head = image_bytes[:16] - return bool( - head.startswith(b"\xff\xd8\xff") - or head.startswith(b"\x89PNG\r\n\x1a\n") - or head.startswith(b"GIF8") - or head.startswith(b"BM") - or (head.startswith(b"RIFF") and b"WEBP" in image_bytes[:32]) - ) - - def _qzone_validate_image_bytes(self, image_bytes: bytes, *, filename: str = "") -> None: - size = len(image_bytes or b"") - if size <= 0: - raise QzoneIntegrationError("图片校验失败", "图片内容为空") - max_bytes = QZONE_REMOTE_IMAGE_MAX_BYTES - if size > max_bytes: - raise QzoneIntegrationError("图片校验失败", f"图片过大,超过 {max_bytes // 1024 // 1024}MB") - if not self._qzone_supported_image_header(image_bytes): - raise QzoneIntegrationError("图片校验失败", f"不是 QQ 空间支持的图片文件:{_single_line(filename, 80) or 'unknown'}") - try: - from PIL import Image as PILImage - import io - - with PILImage.open(io.BytesIO(image_bytes)) as image: - width, height = image.size - if min(width, height) < 16: - raise QzoneIntegrationError("图片校验失败", f"图片尺寸过小:{width}x{height}") - except QzoneIntegrationError: - raise - except Exception: - # PIL may be unavailable in some AstrBot environments; magic header validation still protects the upload. - return - - @staticmethod - def _qzone_is_unsafe_media_host(host: str) -> bool: - normalized = str(host or "").strip().lower().rstrip(".") - if not normalized or normalized in QZONE_UNSAFE_MEDIA_HOSTS or normalized.endswith(".localhost"): - return True - try: - address = ipaddress.ip_address(normalized.strip("[]")) - except ValueError: - return False - return bool( - address.is_private - or address.is_loopback - or address.is_link_local - or address.is_multicast - or address.is_reserved - or address.is_unspecified - ) - - @classmethod - def _qzone_remote_media_url_allowed(cls, source: str) -> bool: - parsed = urlparse(str(source or "").strip()) - if parsed.scheme.lower() not in {"http", "https"} or not parsed.netloc: - return False - host = parsed.hostname - if not host or cls._qzone_is_unsafe_media_host(host): - return False - try: - ipaddress.ip_address(host.strip("[]")) - return True - except ValueError: - pass - try: - infos = socket.getaddrinfo(host.rstrip("."), None, type=socket.SOCK_STREAM) - except OSError: - return False - addresses = {item[4][0] for item in infos if item and item[4]} - return bool(addresses) and not any(cls._qzone_is_unsafe_media_host(address) for address in addresses) - - @classmethod - def _qzone_safe_redirect_url(cls, current_url: str, location: str) -> str: - if not location: - return "" - target = urljoin(current_url, location) - return target if cls._qzone_remote_media_url_allowed(target) else "" - - async def _qzone_load_image_bytes( - self, - event: AstrMessageEvent | None, - source: Any, - *, - cookie_header: str, - ) -> tuple[bytes, str, str]: - import aiohttp - - if isinstance(source, bytes): - return source, "image.jpg", "image/jpeg" - text = str(source or "").strip().strip('"') - if not text: - raise QzoneIntegrationError("图片读取失败", "图片路径为空") - if text.startswith("data:") and "," in text: - meta, encoded = text.split(",", 1) - content_type = meta[5:].split(";", 1)[0] or "image/jpeg" - estimated_size = (len(encoded) * 3) // 4 - if estimated_size > QZONE_REMOTE_IMAGE_MAX_BYTES + 3: - raise QzoneIntegrationError("图片校验失败", "图片过大,已跳过上传") - try: - return base64.b64decode(encoded), f"image.{content_type.rsplit('/', 1)[-1]}", content_type - except Exception as exc: - raise QzoneIntegrationError("图片读取失败", f"图片 data URL 解析失败:{_single_line(exc, 80)}") from exc - if text.startswith("file://"): - text = unquote(urlparse(text).path or "") - if re.match(r"^/[A-Za-z]:/", text): - text = text[1:] - path = Path(text) - if path.exists() and path.is_file(): - data = path.read_bytes() - image_type, content_type = self._qzone_guess_image_type(str(path), data) - return data, path.name or f"image.{image_type}", content_type - if re.match(r"^https?://", text, flags=re.I): - if not self._qzone_remote_media_url_allowed(text): - raise QzoneIntegrationError("图片读取失败", "图片 URL 指向本机、内网或不可安全解析的地址") - timeout = aiohttp.ClientTimeout(total=30) - headers = { - "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0.0.0 Safari/537.36", - "Accept": "image/avif,image/webp,image/apng,image/svg+xml,image/*,*/*;q=0.8", - "Referer": f"https://user.qzone.qq.com/{self._qzone_context_from_cookies(cookie_header)['uin']}", - } - async with aiohttp.ClientSession(timeout=timeout, headers=headers) as session: - current_url = text - for _redirect in range(4): - async with session.get(current_url, allow_redirects=False) as response: - if response.status in {301, 302, 303, 307, 308}: - location = response.headers.get("Location") or response.headers.get("location") or "" - redirected = self._qzone_safe_redirect_url(current_url, location) - if not redirected: - raise QzoneIntegrationError("图片读取失败", "图片重定向目标不安全,已拒绝下载") - current_url = redirected - continue - if response.status >= 400: - raise QzoneIntegrationError("图片读取失败", f"图片下载失败 HTTP {response.status}") - content_type = str(response.headers.get("Content-Type") or "").split(";", 1)[0].strip().lower() - length = _safe_int(response.headers.get("Content-Length"), 0, 0) - if length and length > QZONE_REMOTE_IMAGE_MAX_BYTES: - raise QzoneIntegrationError("图片校验失败", "图片过大,已跳过上传") - data = await response.read() - if len(data) > QZONE_REMOTE_IMAGE_MAX_BYTES: - raise QzoneIntegrationError("图片校验失败", "图片过大,已跳过上传") - image_type, guessed_type = self._qzone_guess_image_type(current_url, data, content_type) - name = Path(urlparse(current_url).path).name or f"image.{image_type}" - return data, name, content_type or guessed_type - raise QzoneIntegrationError("图片读取失败", "图片重定向次数过多,已停止下载") - resolved = await self._qzone_resolve_onebot_image_source(event, text) - if resolved and resolved != text: - return await self._qzone_load_image_bytes(event, resolved, cookie_header=cookie_header) - raise QzoneIntegrationError("图片读取失败", f"无法读取图片:{_single_line(text, 120)}") - - @staticmethod - def _qzone_extract_pic_bo(value: Any) -> str: - text = str(value or "").strip() - if not text: - return "" - parsed = urlparse(text) - query = parse_qs(parsed.query) - for key in ("bo", "pic_bo", "picbo"): - values = query.get(key) - if values and values[0]: - return str(values[0]).strip() - match = re.search(r"(?:^|[?&])(?:bo|pic_bo|picbo)=([^&\s]+)", text) - return match.group(1).strip() if match else "" - - @staticmethod - def _qzone_build_richval(upload_payload: dict[str, Any]) -> str: - albumid = str(QzoneMediaMixin._qzone_find_first(upload_payload, ("albumid", "album_id")) or "").strip() - lloc = str(QzoneMediaMixin._qzone_find_first(upload_payload, ("lloc",)) or "").strip() - sloc = str(QzoneMediaMixin._qzone_find_first(upload_payload, ("sloc",)) or "").strip() - image_type = str(QzoneMediaMixin._qzone_find_first(upload_payload, ("type", "phototype", "image_type")) or "").strip() or "1" - height = str(QzoneMediaMixin._qzone_find_first(upload_payload, ("height", "h")) or "").strip() or "0" - width = str(QzoneMediaMixin._qzone_find_first(upload_payload, ("width", "w")) or "").strip() or "0" - if albumid and lloc and sloc: - return ",".join(["", albumid, lloc, sloc, image_type, height, width, "", height, width]) - return "" - - async def _qzone_upload_image( - self, - event: AstrMessageEvent | None, - source: Any, - *, - cookie_header: str, - ctx: dict[str, Any], - ) -> dict[str, str]: - image_bytes, filename, content_type = await self._qzone_load_image_bytes(event, source, cookie_header=cookie_header) - return await self._qzone_upload_image_bytes( - event, - image_bytes, - filename=filename, - content_type=content_type, - source=source, - cookie_header=cookie_header, - ctx=ctx, - ) - - async def _qzone_upload_image_bytes( - self, - event: AstrMessageEvent | None, - image_bytes: bytes, - *, - filename: str, - content_type: str, - source: Any, - cookie_header: str, - ctx: dict[str, Any], - ) -> dict[str, str]: - if not image_bytes: - raise QzoneIntegrationError("图片读取失败", "图片内容为空") - self._qzone_validate_image_bytes(image_bytes, filename=filename) - image_type, _ = self._qzone_guess_image_type(filename, image_bytes, content_type) - encoded = base64.b64encode(image_bytes).decode("ascii") - referrer = f"https://user.qzone.qq.com/{ctx['uin']}" - payload = await self._qzone_request( - event, - "POST", - QZONE_IMAGE_UPLOAD_URL, - params={"g_tk": ctx["gtk"]}, - data={ - "filename": filename, - "uin": ctx["uin"], - "skey": ctx.get("skey") or ctx.get("p_skey") or "", - "p_skey": ctx.get("p_skey") or ctx.get("skey") or "", - "zzpaneluin": ctx["uin"], - "p_uin": ctx["uin"], - "qzonetoken": ctx.get("qzonetoken") or "", - "zzpanelkey": "", - "uploadtype": "1", - "albumtype": "7", - "exttype": "0", - "refer": "shuoshuo", - "output_type": "json", - "charset": "utf-8", - "output_charset": "utf-8", - "upload_hd": "1", - "hd_width": "2048", - "hd_height": "10000", - "hd_quality": "96", - "backUrls": "http://upbak.photo.qzone.qq.com/cgi-bin/upload/cgi_upload_image,http://119.147.64.75/cgi-bin/upload/cgi_upload_image", - "url": f"{QZONE_IMAGE_UPLOAD_URL}?g_tk={ctx['gtk']}", - "base64": "1", - "picfile": encoded, - "qzreferrer": referrer, - }, - headers={ - "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", - "Accept": "application/json, text/javascript, */*; q=0.01", - "Origin": "https://user.qzone.qq.com", - "Referer": referrer, - "X-Requested-With": "XMLHttpRequest", - }, - timeout_seconds=60.0, - cookie_header=cookie_header, - ) - code = payload.get("code", payload.get("ret", payload.get("_raw_code", 0))) - if code not in {0, "0", None, ""}: - raise QzoneIntegrationError("图片上传失败", _single_line(payload.get("message") or payload.get("msg") or payload.get("_raw_message") or f"code={code}", 160)) - richval = self._qzone_build_richval(payload) - pic_bo = str(self._qzone_find_first(payload, ("pic_bo", "picbo", "bo")) or "").strip() - if not pic_bo: - pic_bo = self._qzone_extract_pic_bo(self._qzone_find_first(payload, ("url", "origin_url", "pre", "raw_url"))) - if not richval: - raise QzoneIntegrationError("图片上传失败", "图片上传成功但未返回 richval 所需字段") - if not pic_bo: - raise QzoneIntegrationError("图片上传失败", "图片上传成功但未返回 pic_bo") - return { - "source": _single_line(source, 160), - "filename": filename, - "type": image_type, - "richval": richval, - "pic_bo": pic_bo, - } - - async def _qzone_image_sources_from_event(self, event: AstrMessageEvent | None) -> list[str]: - if event is None: - return [] - sources: list[str] = [] - - def add(value: Any) -> None: - text = str(value or "").strip() - if text and text not in sources: - sources.append(text) - - extractor = getattr(self, "_extract_image_sources_from_message_obj", None) - message_obj = getattr(event, "message_obj", None) - if callable(extractor): - try: - for source in extractor(message_obj): - add(source) - except Exception: - pass - try: - for source in extractor(getattr(message_obj, "message", None) if message_obj is not None else None): - add(source) - except Exception: - pass - components_getter = getattr(self, "_event_components", None) - components: list[Any] = [] - if callable(components_getter): - try: - components = list(components_getter(event) or []) - except Exception: - components = [] - image_component_count = 0 - image_source_getter = getattr(self, "_image_component_source", None) - for comp in components: - class_name = comp.__class__.__name__.lower() - if isinstance(comp, dict): - class_name = str(comp.get("type") or "").lower() - if class_name != "image": - continue - image_component_count += 1 - if callable(image_source_getter): - try: - add(image_source_getter(comp)) - except Exception: - pass - converter = getattr(comp, "convert_to_file_path", None) - if callable(converter): - try: - maybe = converter() - add(await maybe if hasattr(maybe, "__await__") else maybe) - except Exception: - pass - data = getattr(comp, "data", None) - if not isinstance(data, dict) and isinstance(comp, dict): - data = comp.get("data") if isinstance(comp.get("data"), dict) else {} - for key in ("url", "origin_url", "source_url", "src", "path", "file", "image_path", "file_path", "local_path"): - if isinstance(data, dict): - add(data.get(key)) - if isinstance(comp, dict): - add(comp.get(key)) - else: - add(getattr(comp, key, None)) - reply_image_getter = getattr(self, "_find_reply_image_sources_for_event", None) - if callable(reply_image_getter): - try: - for source in await reply_image_getter(event): - add(source) - except Exception as exc: - logger.info("[PrivateCompanion] QQ 空间引用图片读取失败: %s", _single_line(exc, 120)) - normalized: list[str] = [] - for source in sources: - resolved = await self._qzone_resolve_onebot_image_source(event, source) - candidate = resolved or source - if candidate and candidate not in normalized: - normalized.append(candidate) - if image_component_count <= 1 and len(normalized) > 1: - def rank(source: str) -> tuple[int, int]: - text = str(source or "").strip() - path_text = text[len("file://"):] if text.startswith("file://") else text - path = Path(path_text) - if path.exists() and path.is_file(): - suffix_score = 3 if path.suffix.lower() in {".jpg", ".jpeg", ".png", ".webp", ".gif"} else 2 - return (suffix_score, len(str(path))) - if re.match(r"^https?://", text, flags=re.I): - return (1, len(text)) - return (0, len(text)) - - best = sorted(normalized, key=rank, reverse=True)[0] - logger.info("[PrivateCompanion] QQ 空间单图消息解析到多个来源,已选择一个: candidates=%s chosen=%s", len(normalized), _single_line(best, 120)) - return [best] - return normalized[:9] - - @staticmethod - def _qzone_select_image_sources(command_text: str, image_sources: list[str]) -> tuple[list[str], str]: - sources = [str(item).strip() for item in list(image_sources or []) if str(item or "").strip()] - if len(sources) <= 1: - return sources, "" - text = _single_line(command_text, 120) - if re.search(r"(全部|所有|都发|全发|多图|这几张|这些图)", text): - return sources[:9], "" - cn_digits = {"一": 1, "二": 2, "两": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9} - match = re.search(r"(?:第)?([1-9]\d*)\s*张", text) - if not match: - match = re.search(r"第([一二两三四五六七八九])张", text) - if match: - raw = match.group(1) - index = int(raw) if raw.isdigit() else cn_digits.get(raw, 0) - if 1 <= index <= len(sources): - return [sources[index - 1]], "" - return [], f"检测到 {len(sources)} 张图片,但你指定的第 {index} 张不存在。" - return [], ( - f"检测到 {len(sources)} 张图片。为避免误发公开说说,请补充:" - f"“陪伴 发说说 全部 <正文>” 或 “陪伴 发说说 第1张 <正文>”。" - ) - - @staticmethod - def _qzone_clean_publish_text(command_text: str) -> str: - text = _single_line(command_text, 300) - text = re.sub(r"^(?:全部|所有|都发|全发|多图|这几张|这些图)\s*", "", text) - text = re.sub(r"^(?:第)?[1-9]\d*\s*张\s*", "", text) - text = re.sub(r"^第[一二两三四五六七八九]张\s*", "", text) - return _single_line(text, 300) - - async def _qzone_publish_post( - self, - event: AstrMessageEvent | None = None, - *, - text: str = "", - images: list[str] | None = None, - ) -> Any: - cookie_header = await self._qzone_get_cookies(event) - ctx = self._qzone_context_from_cookies(cookie_header) - ctx["qzonetoken"] = ctx.get("qzonetoken") or await self._qzone_ensure_qzonetoken(event, cookie_header=cookie_header, ctx=ctx) - content = _single_line(text, 300) - if not content and not images: - raise RuntimeError("说说内容为空") - publish_content = content or (" " if images else "") - referrer = f"https://user.qzone.qq.com/{ctx['uin']}" - prepared_images: list[dict[str, Any]] = [] - seen_hashes: set[str] = set() - for image in list(images or [])[:12]: - image_bytes, filename, content_type = await self._qzone_load_image_bytes(event, image, cookie_header=cookie_header) - self._qzone_validate_image_bytes(image_bytes, filename=filename) - digest = hashlib.sha256(image_bytes).hexdigest() - if digest in seen_hashes: - continue - seen_hashes.add(digest) - prepared_images.append( - { - "source": image, - "bytes": image_bytes, - "filename": filename, - "content_type": content_type, - "sha256": digest, - } - ) - if len(prepared_images) >= 9: - break - uploaded_images: list[dict[str, str]] = [] - seen_pic_bos: set[str] = set() - for image in prepared_images: - uploaded = await self._qzone_upload_image_bytes( - event, - image["bytes"], - filename=str(image.get("filename") or "image.jpg"), - content_type=str(image.get("content_type") or "image/jpeg"), - source=image.get("source"), - cookie_header=cookie_header, - ctx=ctx, - ) - pic_bo = str(uploaded.get("pic_bo") or "") - if pic_bo and pic_bo in seen_pic_bos: - continue - if pic_bo: - seen_pic_bos.add(pic_bo) - uploaded_images.append(uploaded) - pic_bos = [item.get("pic_bo", "") for item in uploaded_images if item.get("pic_bo")] - richvals = [item.get("richval", "") for item in uploaded_images if item.get("richval")] - base_data = { - "syn_tweet_verson": "1", - "paramstr": "1", - "who": "1", - "con": publish_content, - "feedversion": "1", - "ver": "1", - "ugc_right": 1, - "to_sign": 0, - "hostuin": ctx["uin"], - "code_version": "1", - "issyncweibo": 0, - "format": "json", - "qzreferrer": referrer, - } - if uploaded_images: - base_data.update( - { - "richtype": "1", - "subrichtype": "1", - "richval": "\t".join(richvals), - "pic_bo": ",".join(pic_bos), - "pic_template": "", - } - ) - headers = { - "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8", - "Referer": referrer, - "Accept": "application/json, text/javascript, */*; q=0.01", - "X-Requested-With": "XMLHttpRequest", - } - endpoint = QZONE_PUBLISH_URL - payload: dict[str, Any] = {} - data = dict(base_data) - payload = await self._qzone_request( - event, - "POST", - endpoint, - params={"g_tk": ctx["gtk"]}, - data=data, - headers=headers, - cookie_header=cookie_header, - ) - code = payload.get("code", 0) - if code not in {0, "0"}: - message = _single_line(payload.get("message") or payload.get("msg") or f"code={code}", 160) - if str(code) not in message: - message = _single_line(f"code={code} {message}", 160) - logger.info( - "[PrivateCompanion] QQ 空间发布失败: endpoint=%s code=%s msg=%s", - urlparse(endpoint).netloc, - code, - message, - ) - stage = "Cookie/g_tk" if self._qzone_auth_failure_message(message) else "发布失败" - raise QzoneIntegrationError(stage, message) - logger.info( - "[PrivateCompanion] QQ 空间说说发布成功: endpoint=%s images=%s", - urlparse(endpoint).netloc, - len(richvals), - ) - return SimpleNamespace( - tid=str(payload.get("tid") or ""), - uin=int(ctx["uin"]), - name=str(ctx["uin"]), - text=content, - images=uploaded_images or (images or []), - create_time=payload.get("now") or int(time.time()), - status="approved", - ) - - async def _qzone_verify_published_post( - self, - event: AstrMessageEvent | None, - post: Any, - *, - expected_text: str, - expected_images: int, - ) -> dict[str, Any]: - tid = str(getattr(post, "tid", "") or "") - expected_clean = _single_line(expected_text, 80) - last_error = "" - for attempt, delay in enumerate((0.0, 0.8, 1.8), start=1): - if delay > 0: - await asyncio.sleep(delay) - try: - feeds = await self._qzone_query_feeds(event, target_id=str(getattr(post, "uin", "") or ""), pos=0, num=5, with_detail=False) - except Exception as exc: - last_error = _single_line(exc, 120) - if attempt >= 3: - return {"verified": False, "message": f"反查失败:{last_error}"} - continue - for feed in feeds: - feed_tid = str(getattr(feed, "tid", "") or "") - feed_text = _single_line(getattr(feed, "text", "") or getattr(feed, "rt_con", ""), 120) - feed_images = len(list(getattr(feed, "images", []) or [])) - tid_match = bool(tid and feed_tid and tid == feed_tid) - text_match = bool(expected_clean and expected_clean in feed_text) - image_match = expected_images <= 0 or feed_images >= expected_images - if tid_match or (image_match and (text_match or not expected_clean)): - return { - "verified": True, - "message": f"已反查到最近说说,图片 {feed_images} 张", - "tid": feed_tid or tid, - "images": feed_images, - } - if last_error: - return {"verified": False, "message": f"反查失败:{last_error}"} - return {"verified": False, "message": "发布接口已返回成功,但最近说说中暂未反查到匹配内容"} - - async def _publish_qzone_text( - self, - text: str, - event: AstrMessageEvent | None = None, - images: list[str] | None = None, - auto_generate_image: bool = False, - publish_reason: str = "manual_publish", - ) -> dict[str, Any]: - 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 {"success": False, "message": message} - return {"success": False, "message": "QQ 空间动态层未启用"} - if not callable(availability) and not self.enable_qzone_integration: - return {"success": False, "message": "QQ 空间动态层未启用"} - content = _single_line(text, 300) - image_list = [str(item).strip() for item in list(images or []) if str(item or "").strip()] - if auto_generate_image and content and not image_list: - image_generator = getattr(self, "_maybe_generate_qzone_publish_image", None) - if callable(image_generator): - try: - generated = await image_generator( - post_text=content, - reason="manual_publish", - state=self._qzone_state_dict(), - force=True, - ) - image_list = [str(item).strip() for item in list(generated or []) if str(item or "").strip()] - except Exception as exc: - logger.info( - "[PrivateCompanion] QQ 空间手动发说说自动配图失败,继续纯文字发布: %s", - _single_line(exc, 160), - ) - if not content and not image_list: - return {"success": False, "message": "说说内容为空"} - - async def publish_once(candidates: list[str]) -> dict[str, Any]: - post = await self._qzone_publish_post(event, text=content, images=candidates) - self._qzone_clear_auth_failure() - post_images = list(getattr(post, "images", []) or []) - verification = await self._qzone_verify_published_post( - event, - post, - expected_text=content, - expected_images=len(post_images), - ) - verified_images = _safe_int(verification.get("images"), len(post_images), 0, 99) - result = { - "success": True, - "text": _single_line(getattr(post, "text", content), 300) or content, - "tid": str(getattr(post, "tid", "") or ""), - "uin": str(getattr(post, "uin", "") or ""), - "images": post_images, - "image_count": max(len(post_images), verified_images if bool(verification.get("verified")) else 0), - "verified": bool(verification.get("verified")), - "verify_message": verification.get("message") or "", - } - recorder = getattr(self, "_qzone_record_published_post", None) - if callable(recorder): - try: - await recorder( - result.get("text") or content, - reason=publish_reason, - tid=result.get("tid", ""), - image_count=_safe_int(result.get("image_count"), 0, 0, 99), - verified=bool(result.get("verified")), - event=event, - ) - except Exception as record_exc: - logger.debug("[PrivateCompanion] QQ 空间发布后自我记录失败: %s", _single_line(record_exc, 120)) - return result - - try: - return await publish_once(image_list) - except Exception as exc: - message = _single_line(exc, 180) - if isinstance(exc, QzoneIntegrationError): - if exc.stage == "Cookie/g_tk" or self._qzone_auth_failure_message(message): - self._qzone_mark_auth_failure(message, source="publish", save=True) - if content and image_list and exc.stage in {"图片读取失败", "图片校验失败", "图片上传失败"}: - logger.warning( - "[PrivateCompanion] QQ 空间图片发布失败,尝试降级纯文字: stage=%s msg=%s", - exc.stage, - message, - ) - try: - fallback = await publish_once([]) - fallback["image_fallback"] = True - fallback["image_fallback_stage"] = exc.stage - fallback["image_fallback_message"] = message - fallback["image_count"] = 0 - fallback["images"] = [] - return fallback - except Exception as retry_exc: - retry_message = _single_line(retry_exc, 180) - if isinstance(retry_exc, QzoneIntegrationError) and ( - retry_exc.stage == "Cookie/g_tk" or self._qzone_auth_failure_message(retry_message) - ): - self._qzone_mark_auth_failure(retry_message, source="publish", save=True) - return { - "success": False, - "stage": exc.stage, - "message": f"{message};降级纯文字也失败:{retry_message}", - "image_fallback_failed": True, - } - return {"success": False, "stage": exc.stage, "message": message} - lowered = message.lower() - if "cookie" in lowered or "p_skey" in lowered or "skey" in lowered or "g_tk" in lowered or "登录" in message: - self._qzone_mark_auth_failure(message, source="publish", save=True) - return {"success": False, "stage": "Cookie/g_tk", "message": f"Cookie/g_tk:{message}"} - if "权限" in message or "403" in message: - return {"success": False, "stage": "权限失败", "message": f"权限失败:{message}"} - return {"success": False, "stage": "发布失败", "message": f"发布失败:{message}"} - diff --git a/qzone_recent_parser.py b/qzone_recent_parser.py deleted file mode 100644 index a51cef0..0000000 --- a/qzone_recent_parser.py +++ /dev/null @@ -1,218 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import annotations - -import re -from html import unescape -from html.parser import HTMLParser -from types import SimpleNamespace -from typing import Any - - -class _QzoneFeedHtmlParser(HTMLParser): - _VOID_TAGS = { - "area", - "base", - "br", - "col", - "embed", - "hr", - "img", - "input", - "link", - "meta", - "param", - "source", - "track", - "wbr", - } - - def __init__(self) -> None: - super().__init__(convert_charrefs=True) - self.text_parts: list[str] = [] - self.repost_parts: list[str] = [] - self.image_urls: list[str] = [] - self.image_items: list[dict[str, str]] = [] - self._class_stack: list[set[str]] = [] - self._tag_stack: list[str] = [] - - @staticmethod - def _classes(attrs: list[tuple[str, str | None]]) -> set[str]: - for key, value in attrs: - if str(key or "").lower() == "class": - return {item.strip() for item in str(value or "").split() if item.strip()} - return set() - - @staticmethod - def _attr(attrs: list[tuple[str, str | None]], name: str) -> str: - lowered = str(name or "").lower() - for key, value in attrs: - if str(key or "").lower() == lowered: - return str(value or "") - return "" - - @classmethod - def _first_attr(cls, attrs: list[tuple[str, str | None]], *names: str) -> str: - for name in names: - value = cls._attr(attrs, name).strip() - if value: - return value - return "" - - @staticmethod - def _is_content_image_url(value: str) -> bool: - source = str(value or "").strip().lower() - return bool(source) and not source.startswith("http://qzonestyle.gtimg.cn") - - def _record_image(self, attrs: list[tuple[str, str | None]]) -> None: - preview_url = self._first_attr(attrs, "src", "data-src", "data-lazy-src", "data-original-src") - full_url = self._first_attr( - attrs, - "data-original", - "data-origin", - "data-origin-url", - "data-original-url", - "data-originalurl", - "data-big-url", - "data-bigurl", - "data-full-url", - "data-fullurl", - "data-raw-url", - "data-rawurl", - "origsrc", - "original", - "data-url", - ) - if not self._is_content_image_url(full_url): - full_url = "" - if not self._is_content_image_url(preview_url): - preview_url = "" - source = full_url or preview_url - if not source: - return - item = {"preview_url": preview_url or source, "full_url": source} - if item not in self.image_items: - self.image_items.append(item) - if source not in self.image_urls: - self.image_urls.append(source) - - def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: - normalized_tag = str(tag or "").lower() - classes = self._classes(attrs) - if normalized_tag != "img": - if normalized_tag not in self._VOID_TAGS: - self._tag_stack.append(normalized_tag) - self._class_stack.append(classes) - elif classes: - self._class_stack.append(classes) - self._class_stack.pop() - return - active_classes = self._class_stack + [classes] - if any({"img-box", "video-img"} & item for item in active_classes): - self._record_image(attrs) - - def handle_startendtag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None: - normalized_tag = str(tag or "").lower() - if normalized_tag == "img": - self.handle_starttag(tag, attrs) - return - classes = self._classes(attrs) - if classes: - self._class_stack.append(classes) - self._class_stack.pop() - - def handle_endtag(self, tag: str) -> None: - normalized_tag = str(tag or "").lower() - for index in range(len(self._tag_stack) - 1, -1, -1): - if self._tag_stack[index] == normalized_tag: - del self._tag_stack[index:] - del self._class_stack[index:] - return - if self._tag_stack and self._class_stack: - self._tag_stack.pop() - self._class_stack.pop() - - def handle_data(self, data: str) -> None: - text = unescape(str(data or "")).strip() - if not text: - return - if any("f-info" in item for item in self._class_stack): - self.text_parts.append(text) - if any("txt-box" in item for item in self._class_stack): - self.repost_parts.append(text) - - -def _parse_feed_html(html_content: str) -> tuple[str, str, list[str]]: - text, repost, image_urls, _items = _parse_feed_html_details(html_content) - return text, repost, image_urls - - -def _parse_feed_html_details(html_content: str) -> tuple[str, str, list[str], list[dict[str, str]]]: - parser = _QzoneFeedHtmlParser() - parser.feed(str(html_content or "")) - text = "".join(parser.text_parts).strip() - repost = "".join(parser.repost_parts).strip() - if ":" in repost: - repost = repost.split(":", 1)[1].strip() - return text, repost, parser.image_urls, parser.image_items - - -def _html_attr_value(html_content: str, *names: str) -> str: - source = str(html_content or "") - for name in names: - escaped = re.escape(str(name or "")) - match = re.search(rf"""{escaped}\s*=\s*["']([^"']+)["']""", source, flags=re.IGNORECASE) - if match: - return unescape(match.group(1)).strip() - return "" - - -def parse_recent_feeds(data: dict[str, Any]) -> list[Any]: - feeds: Any = [] - if isinstance(data, dict): - first = data.get("data") - if isinstance(first, dict): - second = first.get("data") - feeds = second if isinstance(second, list) else [] - elif isinstance(first, list): - feeds = first - elif isinstance(data.get("msglist"), list): - feeds = data.get("msglist") - if not isinstance(feeds, list) or not feeds: - return [] - posts: list[Any] = [] - for feed in feeds: - if not feed: - continue - appid = str(feed.get("appid", "")) - if appid != "311": - continue - uin = int(feed.get("uin") or 0) - tid = str(feed.get("key") or "") - if not uin or not tid: - continue - html_content = str(feed.get("html") or "") - if not html_content: - continue - text, rt_con, image_urls, image_items = _parse_feed_html_details(html_content) - posts.append( - SimpleNamespace( - tid=tid, - uin=uin, - name=str(feed.get("nickname") or feed.get("name") or uin), - text=text, - rt_con=rt_con, - images=image_urls, - image_items=image_items, - comments=[], - create_time=int(feed.get("abstime") or 0), - appid=str(feed.get("appid") or "311"), - typeid=str(feed.get("typeid") or feed.get("type") or "0"), - abstime=int(feed.get("abstime") or 0), - fid=str(feed.get("key") or tid), - unikey=str(feed.get("unikey") or feed.get("likeKey") or feed.get("like_key") or _html_attr_value(html_content, "data-unikey", "unikey")), - curkey=str(feed.get("curkey") or feed.get("curlikekey") or feed.get("likeKey") or feed.get("like_key") or _html_attr_value(html_content, "data-curkey", "curkey")), - raw=feed, - status="approved", - ) - ) - return posts diff --git a/qzone_selection.py b/qzone_selection.py deleted file mode 100644 index dada992..0000000 --- a/qzone_selection.py +++ /dev/null @@ -1,91 +0,0 @@ -# -*- coding: utf-8 -*- -from __future__ import annotations - -import re -from dataclasses import dataclass - -NUMERIC_FID_MIN_LENGTH = 12 - -LATEST_ALIASES = {"", "0", "1", "latest", "newest", "最新", "最新一条", "最近", "第一条", "第1条"} -LAST_ALIASES = {"-1", "last", "最后", "最后一条", "末条"} - - -@dataclass(slots=True) -class QzonePostSelection: - target_id: str = "" - pos: int = 0 - limit: int = 1 - selector: str = "latest" - fid: str = "" - explicit_target: bool = False - explicit_selector: bool = False - - @property - def is_last(self) -> bool: - return self.selector == "last" - - -def _looks_like_fid(value: str) -> bool: - text = str(value or "").strip() - if not text: - return False - if re.fullmatch(rf"\d{{{NUMERIC_FID_MIN_LENGTH},}}", text): - return True - if _parse_index(text) is not None: - return False - return bool(re.fullmatch(r"[A-Za-z0-9_.:-]{6,}", text)) - - -def _parse_index(value: str) -> int | None: - text = str(value or "").strip() - lowered = text.lower() - if text in LATEST_ALIASES or lowered in LATEST_ALIASES: - return 0 - if text in LAST_ALIASES or lowered in LAST_ALIASES: - return -1 - normalized = text.translate(str.maketrans("0123456789", "0123456789")) - match = re.fullmatch(r"第\s*(\d+)\s*(?:条|條)?", normalized) - if not match: - match = re.fullmatch(r"(\d+)\s*(?:条|條)?", normalized) - if not match: - return None - return max(0, int(match.group(1)) - 1) - - -def parse_qzone_post_selection( - *, - user_id: str = "", - selector: str = "", - pos: int = 0, - fid: str = "", -) -> QzonePostSelection: - target_id = str(user_id or "").strip() - raw = str(selector or "").strip() - explicit_target = bool(target_id) - explicit_selector = bool(raw or fid) - - at_match = re.search(r"\[CQ:at,qq=(\d+)[^\]]*\]|@(\d{5,})", raw) - if at_match: - target_id = at_match.group(1) or at_match.group(2) or target_id - explicit_target = True - raw = re.sub(r"\[CQ:at,qq=\d+[^\]]*\]|@\d{5,}", " ", raw, count=1).strip() - - tokens = raw.split() - if not target_id and tokens and re.fullmatch(r"\d{5,}", tokens[0]) and not _looks_like_fid(tokens[0]): - target_id = tokens.pop(0) - explicit_target = True - - explicit_fid = str(fid or "").strip() - if explicit_fid: - return QzonePostSelection(target_id=target_id, fid=explicit_fid, selector="fid", explicit_target=explicit_target, explicit_selector=True) - - if tokens and _looks_like_fid(tokens[0]): - return QzonePostSelection(target_id=target_id, fid=tokens[0], selector="fid", explicit_target=explicit_target, explicit_selector=True) - - parsed = _parse_index(tokens[0]) if tokens else _parse_index(raw) - if parsed is None: - parsed = max(0, int(pos or 0)) - explicit_selector = explicit_selector or parsed > 0 - if parsed < 0: - return QzonePostSelection(target_id=target_id, pos=0, limit=10, selector="last", explicit_target=explicit_target, explicit_selector=True) - return QzonePostSelection(target_id=target_id, pos=parsed, limit=1, selector="index" if parsed > 0 else "latest", explicit_target=explicit_target, explicit_selector=explicit_selector) diff --git a/user_memory.py b/user_memory.py index 52fdb07..591a89e 100644 --- a/user_memory.py +++ b/user_memory.py @@ -5265,12 +5265,6 @@ Local classifier result: abs(mood_score), ) return - vent = getattr(self, "_maybe_publish_qzone_emotional_vent", None) - if callable(vent): - try: - asyncio.create_task(vent(user_snapshot=deepcopy(user), relationship_state=deepcopy(state), intent=deepcopy(intent))) - except Exception as exc: - logger.debug("[PrivateCompanion] 公开心情动态任务创建失败: %s", _single_line(exc, 120)) def _remember_passive_reply_topic(self, user: dict[str, Any], text: str, inbound_text: str = "") -> None: if not self.enable_passive_topic_suppression: