作为一名长期折腾家庭存储的NAS玩家,最近发现微信文件传输助手存在几个痛点:文件保存7天自动过期、手机电脑互传大文件经常失败、工作资料和个人生活照片混在一起。于是萌生了一个想法——能不能在NAS上搭建一个私有化的"文件传输助手"?经过两周的摸索,终于实现了通过微信接口将文件自动转存到NAS的功能,现在分享这套方案的完整实现过程。
这个方案的核心价值在于:
整套系统由三个核心组件构成:
mermaid复制graph LR
A[微信客户端] -->|消息推送| B(wxpy机器人)
B --> C{消息类型判断}
C -->|文件消息| D[下载临时存储]
C -->|非文件消息| E[丢弃]
D --> F[文件重命名/分类]
F --> G[通过WebDAV上传NAS]
G --> H[(NAS存储目录)]
由于官方API需要企业资质,我们采用模拟登录方案:
itchat库实现网页版微信协议FileStorage类型消息注意:微信可能会封禁频繁登录的账号,建议使用备用微信号作为传输专用号
python复制def save_wechat_file(msg):
# 下载文件到临时目录
file_path = msg.download(fileDir='/tmp')
# 解析文件信息
file_name = f"{msg.fileName}_{int(time.time())}"
file_type = msg.fileName.split('.')[-1]
# 创建分类目录
save_path = f"/wx_files/{msg.type}/{time.strftime('%Y%m%d')}"
os.makedirs(save_path, exist_ok=True)
# 通过WebDAV上传
with open(file_path, 'rb') as f:
requests.put(
f"http://nas.local:5005{save_path}/{file_name}",
data=f,
auth=HTTPDigestAuth('admin', 'password')
)
建议在NAS上设置以下目录结构:
code复制/wx_files
├── image
│ ├── 20230701
│ └── 20230702
├── video
├── document
└── other
启用定时任务:
硬件要求:
软件依赖:
bash复制pip install itchat requests requests-toolbelt webdavclient
创建wxbot.py:
python复制import itchat
from file_handler import save_wechat_file
@itchat.msg_register(itchat.content.FILE)
def file_receiver(msg):
save_wechat_file(msg)
return "文件已保存到NAS"
itchat.auto_login(hotReload=True)
itchat.run()
启用WebDAV服务:
创建专用账户:
wx_uploader/wx_files目录读写权限设置存储配额:
通过文件扩展名实现智能分类:
python复制FILE_TYPE_MAP = {
'image': ['jpg', 'png', 'gif'],
'document': ['pdf', 'docx', 'xlsx'],
'video': ['mp4', 'mov']
}
def get_file_type(ext):
for typ, exts in FILE_TYPE_MAP.items():
if ext.lower() in exts:
return typ
return 'other'
上传完成后发送处理结果:
python复制def send_notification(msg, status):
itchat.send(
f"文件{msg['FileName']}处理{status}",
toUserName=msg['FromUserName']
)
启用HTTPS加密传输
nginx复制server {
listen 5006 ssl;
ssl_certificate /path/to/cert.pem;
ssl_certificate_key /path/to/key.pem;
location / {
proxy_pass http://localhost:5005;
}
}
添加IP白名单限制
python复制ALLOWED_IPS = ['192.168.1.*']
@itchat.msg_register(itchat.content.FILE)
def file_receiver(msg):
client_ip = get_client_ip()
if not any(fnmatch(client_ip, pattern) for pattern in ALLOWED_IPS):
return "IP未授权"
# ...
现象:机器人频繁掉线
hotReload=True参数itchat.auto_login(enableCmdQR=2)生成ASCII二维码错误日志:WebDAV 507 Insufficient Storage
当处理大量文件时:
改用异步处理架构
python复制from concurrent.futures import ThreadPoolExecutor
executor = ThreadPoolExecutor(4)
@itchat.msg_register(itchat.content.FILE)
def file_receiver(msg):
executor.submit(save_wechat_file, msg)
增加文件去重功能
python复制def file_md5(file_path):
with open(file_path, 'rb') as f:
return hashlib.md5(f.read()).hexdigest()
if file_md5(new_file) in existing_md5s:
return "重复文件已忽略"
经过三个月实际使用,这套方案展现出几个突出优势:
几个待改进点:
建议搭配Synology Drive使用,可以实现: