- 修改config.py中的文件路径和定时发送时间 - 在各个脚本中添加日志记录功能,提升错误追踪和调试能力 - 更新README.md,详细说明程序功能和使用方法 - 重构scheduler.py、sendmsg.py、send_openmsg.py和send_filemsg.py,增强代码可读性和可维护性
141 lines
4.9 KiB
Python
141 lines
4.9 KiB
Python
from wxauto import WeChat
|
||
from datetime import date, datetime, time as dt_time
|
||
import sys
|
||
import os
|
||
import subprocess
|
||
from config import CONFIG
|
||
import time
|
||
from logger_config import setup_logger
|
||
|
||
# 设置日志记录器
|
||
logger = setup_logger('sendmsg')
|
||
|
||
def wait_until_time():
|
||
"""等待到配置的发送时间"""
|
||
now = datetime.now()
|
||
|
||
# 从配置文件中读取发送时间
|
||
send_time_str = CONFIG['sending_time'] # "17:10"
|
||
hour, minute = map(int, send_time_str.split(':'))
|
||
|
||
target_time = now.replace(hour=hour, minute=minute, second=0, microsecond=0)
|
||
|
||
# 如果当前时间已经过了今天的发送时间,则设置为明天的发送时间
|
||
if now >= target_time:
|
||
target_time = target_time.replace(day=target_time.day + 1)
|
||
|
||
wait_seconds = (target_time - now).total_seconds()
|
||
|
||
logger.info(f"当前时间: {now.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
logger.info(f"目标发送时间: {target_time.strftime('%Y-%m-%d %H:%M:%S')}")
|
||
logger.info(f"等待时间: {wait_seconds/3600:.2f} 小时 ({wait_seconds:.0f} 秒)")
|
||
|
||
time.sleep(wait_seconds)
|
||
logger.info("等待完成,开始执行发送操作")
|
||
|
||
def send_daily_message(count):
|
||
"""发送每日消息的主函数"""
|
||
logger.info(f"开始执行每日消息发送任务,当前尝试次数: {count}")
|
||
|
||
today = date.today()
|
||
formatted_date = today.strftime('%Y-%m-%d')
|
||
file_name = formatted_date + ".jpg"
|
||
file_path = CONFIG['file_path'] + file_name
|
||
|
||
logger.info(f"目标日期: {formatted_date}")
|
||
logger.info(f"目标文件: {file_name}")
|
||
logger.info(f"完整文件路径: {file_path}")
|
||
|
||
num = count
|
||
if num >= 4:
|
||
logger.error("已尝试4次,程序将退出")
|
||
sys.exit(0) # 直接终止程序
|
||
|
||
try:
|
||
logger.info("尝试初始化微信客户端...")
|
||
wx = WeChat()
|
||
logger.info("微信客户端初始化成功")
|
||
except Exception as e:
|
||
logger.error(f"微信客户端初始化失败: {str(e)}")
|
||
logger.info("尝试发送飞书提醒消息...")
|
||
subprocess.run([sys.executable, 'send_openmsg.py'])
|
||
if num<4:
|
||
logger.info(f"等待60秒后重试,当前尝试次数: {num+1}")
|
||
time.sleep(60)
|
||
num += 1
|
||
send_daily_message(num)
|
||
else:
|
||
logger.error("已尝试4次,程序将退出")
|
||
sys.exit(0) # 直接终止程序
|
||
|
||
msg = CONFIG['message']
|
||
who = CONFIG['messages_reciever']
|
||
|
||
logger.info(f"消息内容: {msg}")
|
||
logger.info(f"接收者: {who}")
|
||
|
||
if os.path.isfile(file_path):
|
||
logger.info("找到了指定文件!")
|
||
logger.info(f"文件大小: {os.path.getsize(file_path)} 字节")
|
||
|
||
# 等待到配置的时间再执行发送操作
|
||
wait_until_time()
|
||
|
||
logger.info("开始发送文件和消息...")
|
||
try:
|
||
# 发送文件
|
||
logger.info(f"正在发送文件: {file_path}")
|
||
wx.SendFiles(filepath=file_path, who=who)
|
||
logger.info("文件发送成功")
|
||
|
||
# 发送消息
|
||
logger.info(f"正在发送消息: {msg}")
|
||
wx.SendMsg(msg=msg, who=who)
|
||
logger.info("消息发送成功")
|
||
|
||
logger.info("所有内容发送完成!")
|
||
return True
|
||
|
||
except Exception as e:
|
||
logger.error(f"发送过程中出现错误: {str(e)}")
|
||
logger.error(f"错误类型: {type(e).__name__}")
|
||
# 发送失败时也尝试发送飞书提醒
|
||
subprocess.run([sys.executable, 'send_filemsg.py'])
|
||
if num<4:
|
||
logger.info(f"等待60秒后重试,当前尝试次数: {num+1}")
|
||
time.sleep(60)
|
||
num += 1
|
||
send_daily_message(num)
|
||
else:
|
||
logger.error("已尝试4次,程序将退出")
|
||
sys.exit(0)
|
||
else:
|
||
logger.warning(f"没找到指定文件: {file_path}")
|
||
logger.info("尝试发送飞书提醒消息...")
|
||
subprocess.run([sys.executable, 'send_filemsg.py'])
|
||
if num<4:
|
||
logger.info(f"等待60秒后重试,当前尝试次数: {num+1}")
|
||
time.sleep(60)
|
||
num += 1
|
||
send_daily_message(num)
|
||
else:
|
||
logger.error("已尝试4次,程序将退出")
|
||
sys.exit(0) # 直接终止程序
|
||
|
||
# 如果直接运行此脚本,执行发送消息功能
|
||
if __name__ == "__main__":
|
||
logger.info("=" * 50)
|
||
logger.info("开始执行微信消息发送程序")
|
||
logger.info("=" * 50)
|
||
|
||
count = 0
|
||
try:
|
||
send_daily_message(count)
|
||
logger.info("程序执行完成")
|
||
except Exception as e:
|
||
logger.error(f"程序执行过程中出现未捕获的异常: {str(e)}")
|
||
logger.error(f"异常类型: {type(e).__name__}")
|
||
import traceback
|
||
logger.error(f"异常堆栈: {traceback.format_exc()}")
|
||
sys.exit(1)
|