# 微信公众号功能模块示例

本文档提供各模块的详细使用示例。

## 最简使用示例

只需要配置 `WECHAT_TOKEN_SECRET` 即可开始使用：

```python
from xqcwechat import Auth, Draft, Publish

auth = Auth.from_env()  # 自动检测环境变量配置

draft = Draft(auth)
publish = Publish(auth)

# 创建草稿
result = draft.create_draft([...])

# 发布草稿
publish.publish_draft(result["media_id"])
```

## 快速创建草稿（推荐）

### 使用 add_news_article 方法（最简单）

```python
from xqcwechat import Auth, Draft

auth = Auth.from_env()
draft = Draft(auth)

# 最简单的方式 - 自动上传封面并创建草稿
result = draft.add_news_article(
    title="文章标题",
    content="文章内容",
    thumb_image_path="cover.jpg",  # 自动上传封面图
    author="作者",
    digest="文章摘要",
    auto_draft=True  # 自动创建草稿
)

print(result)  # {"media_id": "xxx"}
```

### 多账号快速创建草稿

```python
from xqcwechat import Auth, Draft, Asset

# 账号1
auth1 = Auth.from_env("1")
draft1 = Draft(auth1)
result1 = draft1.add_news_article(
    title="文章标题",
    content="文章内容",
    thumb_image_path="cover.jpg"
)

# 账号2
auth2 = Auth.from_env("2")
draft2 = Draft(auth2)
result2 = draft2.add_news_article(
    title="文章标题",
    content="文章内容",
    thumb_image_path="cover.jpg"
)
```

## 草稿管理 (Draft)

### 基础操作

```python
from xqcwechat import Auth, Draft

auth = Auth.from_env()
draft = Draft(auth)

# 获取草稿列表
drafts = draft.get_draft_list(offset=0, count=20)

# 获取单个草稿
draft_info = draft.get_draft("media_id_xxx")

# 获取草稿总数
count = draft.get_draft_count()
```

### 创建草稿

```python
from xqcwechat import Auth, Asset, Draft

auth = Auth.from_env()

# 1. 先上传封面图，获取 thumb_media_id
asset = Asset(auth)
cover_result = asset.add_material("image", "cover.jpg")
thumb_media_id = cover_result["media_id"]

# 2. (可选) 上传正文内的图片，获取 URL
image_url = asset.upload_image("content.jpg")

# 3. 创建草稿
draft = Draft(auth)
result = draft.create_draft([{
    "title": "文章标题",
    "author": "作者名",
    "content": "正文内容，可以插入图片<img src='" + image_url + "'>",
    "digest": "文章摘要",
    "content_source_url": "https://example.com/original",
    "thumb_media_id": thumb_media_id,
    "show_cover_pic": 1
}])

print(result)  # {"media_id": "xxx"}
```

### 更新草稿

```python
result = draft.update_draft("media_id_xxx", [{
    "title": "新标题",
    "content": "新内容"
}])
```

### 批量创建多图文草稿

从目录批量读取HTML文件，自动解析文件头的元数据，创建多图文草稿。

```python
from xqcwechat import Auth
from xqcwechat.wechat import Draft

auth = Auth.from_env()
draft = Draft(auth)

# 目录下的每个HTML文件应包含文件头元数据
result = draft.create_multi_article_draft_from_dir(
    dir_path="path/to/articles/directory",
    replace_image_links=True,
    sort_key=True  # True: 按文件名开头数字排序; False: 不排序; callable: 自定义排序函数
)

if result["success"]:
    print(f"草稿创建成功，media_id: {result['media_id']}")
    print(f"文章数量: {result['articles_count']}")
else:
    print(f"创建失败: {result['error']}")

# 如需发布，请调用 publish_draft 方法
if result["success"]:
    from xqcwechat.wechat import Publish
    publish = Publish(auth=auth)
    publish.publish_draft(result["media_id"])
```

### HTML文件格式

每个HTML文件头部需要包含元数据注释：

```html
<!--
title：文章标题
author：作者名
digest：摘要
thumb_media_id：封面图片media_id（已有）
cover_local_path：本地封面图片路径（自动上传）
cover_url：封面图片URL（自动下载并上传）
-->
<section>
    文章正文内容...
</section>
```

### 工具函数

也可以单独使用元数据解析工具：

```python
from xqcwechat.utils import parse_article_metadata, extract_content_from_html

# 解析单个文件的元数据
metadata = parse_article_metadata("path/to/article.html")
print(metadata)
# {'title': '...', 'author': '...', 'thumb_media_id': '...', ...}

# 提取正文内容（去除注释头）
content = extract_content_from_html("path/to/article.html")
```

## 删除草稿

```python
result = draft.delete_draft("media_id_xxx")
```

## 发布管理 (Publish)

### 基础操作

```python
from xqcwechat import Auth, Publish

auth = Auth.from_env()
publish = Publish(auth)

# 获取已发布列表
articles = publish.get_published_articles(offset=0, count=20)

# 查询发布状态
status = publish.get_publish_status("publish_id_xxx")

# 获取已发布图文
article = publish.get_article("article_id_xxx")
```

### 发布草稿

```python
from xqcwechat import Auth, Draft, Publish

auth = Auth.from_env()

# 假设已有草稿 media_id
draft = Draft(auth)
draft_result = draft.create_draft([{...}])
media_id = draft_result["media_id"]

# 发布草稿
publish = Publish(auth)
result = publish.publish_draft(media_id)
print(result)  # {"publish_id": "xxx"}
```

### 删除已发布文章

```python
result = publish.delete_article("article_id_xxx")
```

## 素材管理 (Asset)

### 上传临时素材

```python
from xqcwechat import Auth, Asset

auth = Auth.from_env()
asset = Asset(auth)

# 上传图片，返回 URL（用于正文）
result = asset.upload_image("image.jpg")
print(result)  # {"url": "https://mmbiz.qpic.cn/..."}
```

### 上传永久素材

```python
from xqcwechat import Auth, Asset

auth = Auth.from_env()
asset = Asset(auth)

# 上传图片永久素材，返回 media_id（用于封面）
result = asset.add_material("image", "cover.jpg")
print(result)  # {"media_id": "xxx", "url": "https://..."}

# 上传图文消息
articles = [{
    "title": "标题",
    "thumb_media_id": "xxx",
    "author": "作者",
    "content": "正文内容",
    "digest": "摘要",
    "content_source_url": "https://example.com"
}]
result = asset.add_material("news", articles)
print(result)  # {"media_id": "xxx"}
```

### 获取素材

```python
# 获取素材列表
result = asset.get_materials("image", offset=0, count=20)

# 获取素材总数
count = asset.get_material_count()

# 获取素材内容
material = asset.get_material("media_id_xxx")
```

### 删除素材

```python
result = asset.delete_material("media_id_xxx")
```

## 留言管理 (Comment)

### 基础操作

```python
from xqcwechat import Auth, Comment

auth = Auth.from_env()
comment = Comment(auth)

# 打开评论
result = comment.open_comment(msg_data_id="msg_id", index=0)

# 关闭评论
result = comment.close_comment(msg_data_id="msg_id", index=0)

# 获取评论列表
comments = comment.list_comment(msg_data_id="msg_id", index=0)

# 精选评论
comment.elect_comment(msg_data_id="msg_id", index=0, user_comment_id=1)

# 取消精选
comment.unelect_comment(msg_data_id="msg_id", index=0, user_comment_id=1)

# 回复评论
comment.reply_comment(msg_data_id="msg_id", index=0, user_comment_id=1, content="回复内容")

# 删除评论
comment.delete_comment(msg_data_id="msg_id", index=0, user_comment_id=1)
```

## 完整工作流示例

### 发布文章完整流程

```python
from xqcwechat import Auth, Asset, Draft, Publish

# 1. 初始化（自动从环境变量加载）
auth = Auth.from_env()

# 2. 上传封面图
asset = Asset(auth)
cover_result = asset.add_material("image", "cover.jpg")
thumb_media_id = cover_result["media_id"]

# 3. 上传正文图片
image_url = asset.upload_image("content_image.jpg")

# 4. 创建草稿
draft = Draft(auth)
draft_result = draft.create_draft([{
    "title": "文章标题",
    "author": "作者名",
    "content": f"正文内容<img src='{image_url}'>",
    "digest": "文章摘要",
    "thumb_media_id": thumb_media_id,
    "show_cover_pic": 1
}])

# 5. 发布草稿
publish = Publish(auth)
publish_result = publish.publish_draft(draft_result["media_id"])
print(f"发布成功: {publish_result}")
```

### 使用便捷方法快速发布

```python
from xqcwechat import Auth, Draft, Publish

auth = Auth.from_env()

# 使用 add_news_article 一键创建草稿
draft = Draft(auth)
result = draft.add_news_article(
    title="文章标题",
    content="文章内容",
    thumb_image_path="cover.jpg",  # 自动上传
    author="作者",
    auto_draft=True
)

# 发布
publish = Publish(auth)
publish_result = publish.publish_draft(result["media_id"])
print(f"发布成功: {publish_result}")
```

### 多账号同时发布同一篇文章

```python
from xqcwechat import Auth, Draft, Publish, Asset

# 配置多账号后，分别为每个账号发布
account_nums = ["1", "2"]  # 要发布的账号列表
title = "文章标题"
content = "文章内容"
cover_path = "cover.jpg"

results = []

for account_num in account_nums:
    try:
        auth = Auth.from_env(account_num)
        asset = Asset(auth)

        # 上传封面
        cover_result = asset.add_material("image", cover_path)

        # 创建草稿
        draft = Draft(auth)
        draft_result = draft.add_news_article(
            title=title,
            content=content,
            thumb_media_id=cover_result["media_id"],
            auto_draft=True
        )

        # 发布
        publish = Publish(auth)
        publish_result = publish.publish_draft(draft_result["media_id"])

        results.append({
            "account": account_num,
            "success": True,
            "publish_id": publish_result.get("publish_id")
        })
    except Exception as e:
        results.append({
            "account": account_num,
            "success": False,
            "error": str(e)
        })

# 查看结果
for result in results:
    if result["success"]:
        print(f"账号 {result['account']} 发布成功: {result['publish_id']}")
    else:
        print(f"账号 {result['account']} 发布失败: {result['error']}")
```
