文件已上传:https://www.pan38.com/share.php?code=XHUZM 提取码:8888
这个实现包含完整的微信朋友圈自动发布功能,支持定时发布、多图发布、任务持久化存储等功能。代码使用了itchat库实现微信接口调用,schedule库实现定时任务调度。使用时需要先扫码登录微信,然后设置定时发布任务。
import time
import schedule
from datetime import datetime
import random
import json
import os
from typing import List, Dict
import itchat
from itchat.content import *
class MomentsPublisher:
def init(self):
self.config_file = "moments_config.json"
self.scheduled_posts = []
self.load_config()
def load_config(self):
if os.path.exists(self.config_file):
with open(self.config_file, 'r', encoding='utf-8') as f:
config = json.load(f)
self.scheduled_posts = config.get('scheduled_posts', [])
def save_config(self):
with open(self.config_file, 'w', encoding='utf-8') as f:
json.dump({'scheduled_posts': self.scheduled_posts}, f, ensure_ascii=False, indent=4)
def add_scheduled_post(self, content: str, post_time: str, images: List[str] = None):
post = {
'content': content,
'post_time': post_time,
'images': images or [],
'posted': False
}
self.scheduled_posts.append(post)
self.save_config()
def post_to_moments(self, content: str, images: List[str] = None):
try:
if images and len(images) > 0:
itchat.send_moment(content, picture=images[0] if len(images) == 1 else images)
else:
itchat.send_moment(content)
print(f"[{datetime.now()}] 朋友圈发布成功: {content[:20]}...")
return True
except Exception as e:
print(f"[{datetime.now()}] 朋友圈发布失败: {str(e)}")
return False
def check_scheduled_posts(self):
now = datetime.now().strftime("%Y-%m-%d %H:%M")
for post in self.scheduled_posts:
if not post['posted'] and post['post_time'] <= now:
if self.post_to_moments(post['content'], post['images']):
post['posted'] = True
self.save_config()
def run_scheduler(self):
schedule.every(1).minutes.do(self.check_scheduled_posts)
while True:
schedule.run_pending()
time.sleep(1)
def login_wechat():
itchat.auto_login(hotReload=True, enableCmdQR=2)
print("微信登录成功")
def main():
print("微信朋友圈自动发布工具启动...")
login_wechat()
publisher = MomentsPublisher()
# 示例:添加定时发布任务
publisher.add_scheduled_post(
content="早安!新的一天开始了~ #早安 #正能量",
post_time="2025-06-30 08:00",
images=["morning.jpg"]
)
publisher.add_scheduled_post(
content="分享一首好听的音乐 #音乐推荐",
post_time="2025-06-30 12:30"
)
publisher.add_scheduled_post(
content="今日工作总结... #工作日志",
post_time="2025-06-30 18:00",
images=["work1.jpg", "work2.jpg"]
)
print("定时任务已设置,开始运行调度器...")
publisher.run_scheduler()
if name == "main":
main()
itchat==1.3.10
schedule==1.1.0
PyYAML==6.0