#!/usr/bin/env python3
"""
baoyu-post-to-wechat 简化版发布脚本
使用 WeWrite 相同的微信账号配置
"""
import os
import json
import requests
import yaml
import markdown
from pathlib import Path
# 配置文件路径
EXTEND_PATH = "/home/ubuntu/.nanobot/workspace/skills/baoyu-post-to-wechat/EXTEND.md"
WEWRITE_CONFIG = "/home/ubuntu/wewrite/config.yaml"
def load_config():
"""加载配置,优先使用 EXTEND.md,回退到 WeWrite 配置"""
config = {}
# 尝试加载 EXTEND.md
if os.path.exists(EXTEND_PATH):
with open(EXTEND_PATH, 'r', encoding='utf-8') as f:
content = f.read()
# 简单解析 key: value 格式
for line in content.split('\n'):
if ':' in line and not line.strip().startswith('#'):
key, value = line.split(':', 1)
config[key.strip()] = value.strip()
# 如果 EXTEND.md 中没有账号信息,使用 WeWrite 配置
if 'app_id' not in config and os.path.exists(WEWRITE_CONFIG):
with open(WEWRITE_CONFIG, 'r', encoding='utf-8') as f:
wewrite_config = yaml.safe_load(f)
config['app_id'] = wewrite_config['wechat']['appid']
config['app_secret'] = wewrite_config['wechat']['secret']
config['default_author'] = wewrite_config['wechat']['author']
return config
def get_access_token(app_id, app_secret):
"""获取微信 access_token"""
url = f"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={app_id}&secret={app_secret}"
response = requests.get(url)
data = response.json()
if 'access_token' in data:
return data['access_token']
else:
raise Exception(f"获取 access_token 失败: {data}")
def upload_cover_image(image_path, access_token):
"""上传封面图到微信(永久素材)"""
url = f"https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={access_token}&type=image"
with open(image_path, 'rb') as f:
files = {'media': f}
response = requests.post(url, files=files)
data = response.json()
if 'media_id' in data:
return data['media_id']
else:
raise Exception(f"上传封面图失败: {data}")
def markdown_to_wechat_html(md_content):
"""将 Markdown 转换为微信公众号兼容的 HTML"""
# 先将 Markdown 转为标准 HTML
html = markdown.markdown(
md_content,
extensions=[
'markdown.extensions.fenced_code',
'markdown.extensions.tables',
'markdown.extensions.codehilite',
]
)
# 转换图片为微信兼容的格式(确保图片有正确的样式)
import re
html = re.sub(
r'',
r'
',
html
)
# 转换表格为微信兼容格式
html = re.sub(
r'
| ', ' | ', html ) html = re.sub( r' | ', ' | ',
html
)
# 转换代码块为微信兼容的 pre 标签
html = re.sub(
r' |
|---|