发送时,上传到微信,获取URL,进行发送

This commit is contained in:
liuwei
2025-06-11 10:58:42 +08:00
parent 3982319e1d
commit c85cf16368

View File

@@ -1,4 +1,6 @@
import base64
import json
import os
from datetime import datetime, timedelta
from typing import Dict, Any, List, Optional, Tuple
@@ -142,7 +144,7 @@ class MessagePushTask(MessagePluginInterface):
# 检查任务是否应该执行
now = datetime.now()
schedule_time = task['schedule_time']
# 对于重复任务,检查是否到达执行时间点
if task['schedule_type'] == 'recurring':
recurring_time = task.get('recurring_time')
@@ -162,26 +164,26 @@ class MessagePushTask(MessagePluginInterface):
else:
hour, minute = map(int, time_parts)
second = 0
# 检查当前时间是否在目标时间的前后5秒内
target_time = now.replace(hour=hour, minute=minute, second=second, microsecond=0)
time_diff = abs((now - target_time).total_seconds())
if time_diff > 5: # 允许5秒的误差
continue
# 检查是否已经在这个时间点执行过
execution_key = self._get_execution_key(task['task_id'], hour, minute)
if execution_key in self._task_execution_records:
self.LOG.debug(f"任务 {task['task_id']} 今天已经执行过,跳过")
continue
# 记录执行状态
self._task_execution_records[execution_key] = now
except (ValueError, AttributeError) as e:
self.LOG.error(f"无效的执行时间格式: {recurring_time}, 错误: {e}")
continue
# 更新任务状态为执行中
self.db.update_task(task['task_id'], {'status': 'running'})
@@ -209,6 +211,22 @@ class MessagePushTask(MessagePluginInterface):
if not self.bot:
raise Exception("机器人实例未初始化")
# 发送链接消息,提前进行数据整理,上传缩略图
if content_link:
# content_link json 读取内容
link_data = json.loads(content_link)
thumburl_path = link_data.get('thumburl', '')
thumburl_wx = ""
if thumburl_path and os.path.exists(thumburl_path):
# Read local image file
with open(thumburl_path, 'rb') as image_file:
# Convert image to base64
base64_string = base64.b64encode(image_file.read()).decode('utf-8')
# Call upload method with base64 string
thumburl_wx = await self.bot.friend_circle_upload(base64=base64_string)
else:
print(f"Image file not found at: {thumburl_path}")
success_count = 0
fail_count = 0
@@ -229,7 +247,7 @@ class MessagePushTask(MessagePluginInterface):
xml_content = f"{LINK_XML_NORMAL}".format(title=link_data.get('title', ''),
des=link_data.get('des', ''),
url=link_data.get('url', ''),
thumburl=link_data.get('thumburl', '')
thumburl=thumburl_wx
)
await self.bot.send_link_xml_message(xml_content, group_id)
@@ -305,8 +323,8 @@ class MessagePushTask(MessagePluginInterface):
self.LOG.error(f"处理定时任务出错: {e}")
def _calculate_next_schedule_time(self, schedule_time: datetime, recurring_interval: str,
recurring_end: datetime, recurring_time: str,
weekly_days: str = None, monthly_day: int = None) -> Optional[datetime]:
recurring_end: datetime, recurring_time: str,
weekly_days: str = None, monthly_day: int = None) -> Optional[datetime]:
"""计算下次执行时间"""
try:
# 解析执行时间
@@ -335,7 +353,7 @@ class MessagePushTask(MessagePluginInterface):
# 获取当前时间
now = datetime.now()
# 如果已经超过结束时间返回None
if recurring_end and now > recurring_end:
return None
@@ -346,7 +364,7 @@ class MessagePushTask(MessagePluginInterface):
next_time = now.replace(hour=hour, minute=minute, second=second, microsecond=0)
if next_time <= now:
next_time = next_time + timedelta(days=1)
elif recurring_interval == 'weekly':
# 每周执行
try:
@@ -354,10 +372,10 @@ class MessagePushTask(MessagePluginInterface):
weekly_days = json.loads(weekly_days)
if not weekly_days:
return None
# 获取当前是周几0-60是周一
current_weekday = now.weekday()
# 找到下一个执行日
next_weekday = None
for day in sorted(weekly_days):
@@ -365,31 +383,32 @@ class MessagePushTask(MessagePluginInterface):
if day > current_weekday:
next_weekday = day
break
# 如果本周没有下一个执行日,取下周的第一个执行日
if next_weekday is None:
next_weekday = int(weekly_days[0])
days_ahead = 7 - current_weekday + next_weekday
else:
days_ahead = next_weekday - current_weekday
next_time = now.replace(hour=hour, minute=minute, second=second, microsecond=0) + timedelta(days=days_ahead)
next_time = now.replace(hour=hour, minute=minute, second=second, microsecond=0) + timedelta(
days=days_ahead)
except (json.JSONDecodeError, ValueError, IndexError) as e:
self.LOG.error(f"处理每周执行日失败: {e}")
return None
elif recurring_interval == 'monthly':
# 每月执行
try:
if not monthly_day:
return None
# 获取当前日期
current_day = now.day
current_month = now.month
current_year = now.year
# 如果当前日期已经过了执行日,移到下个月
if current_day >= monthly_day:
if current_month == 12:
@@ -401,7 +420,7 @@ class MessagePushTask(MessagePluginInterface):
else:
next_month = current_month
next_year = current_year
# 处理无效日期如2月30日
try:
next_time = datetime(next_year, next_month, monthly_day, hour, minute, second)
@@ -412,7 +431,7 @@ class MessagePushTask(MessagePluginInterface):
else:
last_day = (datetime(next_year, next_month + 1, 1) - timedelta(days=1)).day
next_time = datetime(next_year, next_month, last_day, hour, minute, second)
except Exception as e:
self.LOG.error(f"处理每月执行日失败: {e}")
return None