# Feishu Docx Block API 实战笔记 ## 概述 飞书文档(docx)的 block-level API 允许直接读取和修改文档结构。这是比 `lark docs content get` 更底层的操作,能精确控制每个段落、标题、代码块的位置。 ## Wiki 链接 → 文档 token 转换 用户分享的链接通常是 wiki 链接(`wudaima.feishu.cn/wiki/`),但 API 需要的是 docx 的 `obj_token`。 ```python # Step 1: 用 wiki node_token 获取文档元数据 wiki_token = "Glf6wVz75iqegWkc2CKcOqhrnjc" req = urllib.request.Request( f"https://open.feishu.cn/open-apis/wiki/v2/spaces/get_node?token={wiki_token}", headers={"Authorization": f"Bearer {TOKEN}"}) with urllib.request.urlopen(req, timeout=15) as r: node_info = json.loads(r.read()) # Step 2: 提取 obj_token(这才是 docx API 用的 document_id) doc_id = node_info["data"]["node"]["obj_token"] # e.g. "FGbsdJvCUohmxkxSnatcYvtdn2b" doc_title = node_info["data"]["node"]["title"] obj_type = node_info["data"]["node"]["obj_type"] # "docx" ``` ## 权限模型:文档协作者授权 **关键**:即使应用在开放平台有 `docx:document` 权限,也需要在**每个具体文档**上把应用添加为协作者。 - 文档分享 → 搜索应用名(如 "pixel phone agent")→ 权限选「可编辑」→ 确认 - 未授权时:block 写操作返回 `403 Forbidden`(code 1770032) - 授权后:读写都正常 这与 Bitable 不同——Bitable 的权限在表格层面,Docx 的权限在文档层面。 ## 读取文档 Block ```python # 获取文档所有 block(page_size=500 通常够用) doc_id = "FGbsdJvCUohmxkxSnatcYvtdn2b" req = urllib.request.Request( f"https://open.feishu.cn/open-apis/docx/v1/documents/{doc_id}/blocks?page_size=500", headers={"Authorization": f"Bearer {TOKEN}"}) with urllib.request.urlopen(req, timeout=20) as r: doc = json.loads(r.read()) blocks = doc.get("data", {}).get("items", []) has_more = doc.get("data", {}).get("has_more", False) # Root block (block_type=1) 的 children 数组定义了文档的块顺序 root = next((b for b in blocks if b.get("block_type") == 1), None) children_order = root.get("children", []) # block_id 列表,按文档顺序 ``` ### Block 类型速查 | block_type | 含义 | 内容字段 | |:---:|------|----------| | 1 | Page(根块) | `children`: 子块 ID 列表 | | 2 | 文本 | `text.elements[].text_run.content` | | 3-12 | 标题 H1-H10 | `headingN.elements[].text_run.content` | | 13 | 无序列表 | `bullet.elements[].text_run.content` | | 14 | 有序列表 | `ordered.elements[].text_run.content` | | 15 | 代码块 | `code.elements[].text_run.content` | | 17 | 引用 | `quote.elements[].text_run.content` | | 19 | 分割线 | — | | 27 | 图片 | `image.token`, `image.width`, `image.height` | | 34 | 图片/文件 | — | ### 提取 block 文本的通用方法 ```python def get_block_text(block): """Extract text content from any block type""" btype = block.get("block_type", 0) text = "" # Map block type to content key key_map = { 2: "text", 3: "heading1", 4: "heading2", 5: "heading3", 6: "heading4", 7: "heading5", 8: "heading6", 9: "heading7", 10: "heading8", 11: "heading9", 12: "heading10", 13: "bullet", 14: "ordered", 15: "code", 17: "quote" } key = key_map.get(btype) if key: elements = block.get(key, {}).get("elements", []) for el in elements: run = el.get("text_run", {}) if run: text += run.get("content", "") return text ``` ## 插入 Block ```python # 在指定位置插入新 block(index 从 0 开始) block_data = { "block_type": 2, # 文本块 "text": { "elements": [{"text_run": {"content": "中文翻译内容"}}] } } # POST 到根块的 children 端点 # index = 插入位置(0=最前面,N=第N个子块后面) data = json.dumps({"index": insert_index, "children": [block_data]}).encode() req = urllib.request.Request( f"https://open.feishu.cn/open-apis/docx/v1/documents/{doc_id}/blocks/{doc_id}/children", data=data, headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}, method="POST") with urllib.request.urlopen(req, timeout=15) as r: result = json.loads(r.read()) # result["code"] == 0 表示成功 ``` ### 批量插入:逆序插入避免索引偏移 当需要在多个位置插入 block 时,**必须从后往前插入**,否则前面的插入会使后面的索引偏移。 ```python # 收集所有要插入的位置和内容 inserts = [(index_1, text_1), (index_2, text_2), ...] # 按索引降序排序 inserts.sort(key=lambda x: x[0], reverse=True) for insert_idx, text in inserts: block_data = { "block_type": 2, "text": {"elements": [{"text_run": {"content": text}}]} } # POST insert at insert_idx... ``` ### 标题块插入 ```python # H2 标题 block_data = { "block_type": 4, # heading2 "heading2": { "elements": [{"text_run": {"content": "标题文字"}}] } } ``` ## 删除 Block ```python # 删除根块的第 start_index 到 end_index 个子块 data = json.dumps({"start_index": 0, "end_index": 1}).encode() req = urllib.request.Request( f"https://open.feishu.cn/open-apis/docx/v1/documents/{doc_id}/blocks/{doc_id}/children/batch_delete", data=data, headers={"Authorization": f"Bearer {TOKEN}", "Content-Type": "application/json"}, method="DELETE") with urllib.request.urlopen(req, timeout=10) as r: result = json.loads(r.read()) # result["code"] == 0 表示成功 ``` 注意:不是 `DELETE /blocks/{block_id}`,而是 `DELETE /blocks/{root_id}/children/batch_delete` + start/end index。 ## 图片 Block 插入(需要 Drive 上传) ```python # Step 1: 上传图片到飞书 Drive # POST /drive/v1/medias/upload_all # parent_type=DOCX_IMAGE, parent_node=doc_id # 返回 file_token # Step 2: 插入图片 block block_data = { "block_type": 27, # image "image": { "token": file_token, # 从 upload_all 获取 "width": 1024, "height": 1024 } } # POST insert 同文本块 ``` ⚠️ Drive media upload (`upload_all`) 可能返回 `1061002 params error`。需要确认应用有 `drive:drive:write` 或等效权限,且 parent_type/parent_node 格式正确。如果持续失败,可改为:发图片到飞书聊天 → 获取消息中的 image key → 用该 key 插入图片 block。 ## 中文弯引号陷阱 处理飞书文档中文内容时,文本中可能包含中文弯引号 `""`(U+201C/U+201D),在 Python 字符串中会破坏语法。 ```python # ❌ 这会报 SyntaxError: invalid character ',' text = "常见的错误是把"然后"当作边" # ✅ 替换为直角引号「」 text = "常见的错误是把「然后」当作边" # 批量修复已写入的 .py 文件 data = open(file, 'rb').read() data = data.replace(b'\xe2\x80\x9c', b'\xe3\x80\x8c') # " → 「 data = data.replace(b'\xe2\x80\x9d', b'\xe3\x80\x8f') # " → 」 open(file, 'wb').write(data) ``` ## 完整工作流:翻译文档 1. **解析 wiki 链接** → 获取 obj_token (doc_id) 2. **读取所有 block** → GET /blocks?page_size=500 3. **提取文本** → 遍历 block,提取每个 block 的文本内容 4. **翻译** → 对每个英文 block 生成中文翻译 5. **逆序插入** → 从后往前在每个原文 block 后插入中文翻译 block 6. **验证** → 重新读取 block 列表确认数量翻倍 7. **清理** → 删除测试插入的 block ## 速率限制 - 插入操作建议间隔 0.3-0.5 秒 - 读取操作间隔可更短 - 批量插入 95 个 block 约 35 秒可完成