调整总结业务。支持每天早上9点总结昨天的消息
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import asyncio
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Dict, Any, Tuple, Optional, List
|
||||
|
||||
@@ -10,6 +12,7 @@ from loguru import logger
|
||||
from base.plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
from base.plugin_common.plugin_interface import PluginStatus
|
||||
from utils.compress_chat_data import compress_chat_data
|
||||
from utils.decorator.async_job import async_job
|
||||
from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
from utils.decorator.points_decorator import plugin_points_cost
|
||||
from utils.decorator.rate_limit_decorator import group_feature_rate_limit
|
||||
@@ -67,6 +70,8 @@ class MessageSummaryPlugin(MessagePluginInterface):
|
||||
self.revoke = None
|
||||
# 注册功能权限
|
||||
self.feature = self.register_feature()
|
||||
# 注册定时任务:每天早上9点总结昨天的聊天信息
|
||||
async_job.at_times(["09:00"])(self.daily_summary_job)
|
||||
|
||||
def initialize(self, context: Dict[str, Any]) -> bool:
|
||||
"""初始化插件"""
|
||||
@@ -288,3 +293,107 @@ class MessageSummaryPlugin(MessagePluginInterface):
|
||||
except Exception as e:
|
||||
self.LOG.error(f"处理总结时出现未知错误: {e}")
|
||||
return f"生成总结时出现未知错误: {str(e)}", None
|
||||
|
||||
async def daily_summary_job(self):
|
||||
"""定时任务:每天早上9点总结昨天的聊天信息"""
|
||||
try:
|
||||
self.LOG.info("开始执行每日聊天总结任务")
|
||||
|
||||
# 计算昨天的时间范围
|
||||
yesterday = datetime.now() - timedelta(days=1)
|
||||
yesterday_start = yesterday.replace(hour=0, minute=0, second=0, microsecond=0)
|
||||
yesterday_end = yesterday.replace(hour=23, minute=59, second=59, microsecond=999999)
|
||||
|
||||
self.LOG.info(f"总结时间范围: {yesterday_start.strftime('%Y-%m-%d %H:%M:%S')} 至 {yesterday_end.strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
|
||||
# 获取所有启用了群机器人的群聊
|
||||
all_groups = GroupBotManager.get_group_list()
|
||||
|
||||
if not all_groups:
|
||||
self.LOG.info("没有群聊启用群机器人,跳过定时总结")
|
||||
return
|
||||
|
||||
# 筛选出开启了总结功能的群聊
|
||||
enabled_groups = []
|
||||
for group_id in all_groups:
|
||||
if GroupBotManager.get_group_permission(group_id, self.feature) == PermissionStatus.ENABLED:
|
||||
enabled_groups.append(group_id)
|
||||
|
||||
if not enabled_groups:
|
||||
self.LOG.info("没有群聊开启定时总结功能,跳过")
|
||||
return
|
||||
|
||||
self.LOG.info(f"找到 {len(enabled_groups)} 个开启定时总结的群聊")
|
||||
|
||||
# 获取所有联系人
|
||||
all_contacts = ContactManager.get_instance().get_all_contacts()
|
||||
|
||||
# 为每个群生成总结
|
||||
for group_id in enabled_groups:
|
||||
try:
|
||||
# 先统计昨天的消息数量
|
||||
message_count = self.message_storage.count_messages_by_date_range(
|
||||
group_id,
|
||||
yesterday_start,
|
||||
yesterday_end
|
||||
)
|
||||
|
||||
# 消息少于50条,跳过总结
|
||||
if message_count < 50:
|
||||
self.LOG.info(f"群 {group_id} 昨天只有 {message_count} 条消息,不足50条,跳过总结")
|
||||
continue
|
||||
|
||||
self.LOG.info(f"群 {group_id} 昨天有 {message_count} 条消息,开始获取内容")
|
||||
|
||||
# 获取群名
|
||||
group_name = all_contacts.get(group_id, group_id)
|
||||
group_name = self._sanitize_group_name(group_name)
|
||||
|
||||
# 获取昨天的聊天记录
|
||||
chat_content = self.message_storage.get_messages_by_date_range(
|
||||
group_id,
|
||||
all_contacts,
|
||||
yesterday_start,
|
||||
yesterday_end
|
||||
)
|
||||
|
||||
if not chat_content:
|
||||
self.LOG.info(f"群 {group_id} 昨天聊天记录为空,跳过总结")
|
||||
continue
|
||||
|
||||
self.LOG.info(f"开始为群 {group_name} 生成总结,消息数量: {message_count},内容长度: {len(chat_content)}")
|
||||
|
||||
# 发送提示消息
|
||||
await self.bot.send_text_message(
|
||||
group_id,
|
||||
f"⏳ 正在生成昨日聊天总结 ({yesterday.strftime('%Y-%m-%d')})… 😊"
|
||||
)
|
||||
|
||||
# 生成总结
|
||||
summary, image_path = await self._generate_summary(chat_content, group_name)
|
||||
|
||||
if image_path:
|
||||
# 图片生成成功,发送图片
|
||||
await self.bot.send_image_message(group_id, Path(image_path))
|
||||
self.LOG.info(f"成功发送群 {group_name} 的昨日总结图片")
|
||||
else:
|
||||
# 图片生成失败,发送文本消息
|
||||
if summary and len(summary.strip()) > 0:
|
||||
max_length = 2000
|
||||
if len(summary) > max_length:
|
||||
summary = summary[:max_length] + "\n\n... (内容过长,已截断)"
|
||||
|
||||
await self.bot.send_text_message(group_id, summary)
|
||||
self.LOG.info(f"成功发送群 {group_name} 的昨日总结文本")
|
||||
|
||||
# 避免请求过快
|
||||
await asyncio.sleep(2)
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"为群 {group_id} 生成昨日总结失败: {e}", exc_info=True)
|
||||
continue
|
||||
|
||||
self.LOG.info("每日聊天总结任务执行完成")
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"每日聊天总结任务执行失败: {e}", exc_info=True)
|
||||
|
||||
Reference in New Issue
Block a user