跳转至

📚 飞书对话归档完整操作指南

⚠️ 重要: 本文档记录了完整的飞书对话归档操作流程和关键信息,下次归档前**必须先阅读此文档**!

创建日期: 2026-03-17
最后更新: 2026-03-17
版本: v1.0


🎯 核心流程概览

1. 创建云文档 → 2. 写入内容 → 3. 移动到知识空间

📁 关键 URL 路径信息

知识库空间

项目 Token URL
知识库空间 ID 7616106849955220687 https://xcny2sco1sb0.feishu.cn/wiki/E2UqwmC5IiIymWkhvgpcFzqOnKh
对话归档目录 W01EwPEiniSyEfkQd3ZctQsfnMb 知识库 → 对话归档

云文档文件夹

项目 Token URL
openclaw 对话存档文件夹 PimdfCKZQliPNFdOxpscb8tknUb https://xcny2sco1sb0.feishu.cn/drive/folder/PimdfCKZQliPNFdOxpscb8tknUb

归档文档

日期 Document ID Wiki Token URL
2026-03-16 WG4YdDe16oZwcdxJbNscyEPOnwg VyaEwGNDaiH13tk62uycKU2in0e https://xcny2sco1sb0.feishu.cn/wiki/VyaEwGNDaiH13tk62uycKU2in0e

🔑 认证信息

User Access Token

u-fLM1T9ZUJ0qWLyWRcZeTmg14hYkw5hMjq28a3xk007vp

⚠️ 注意: 必须使用 user_access_tokentenant_access_token 无法创建/移动文档!


📝 完整操作步骤

步骤 1:创建云文档

API 端点:

POST https://open.feishu.cn/open-apis/docx/v1/documents

请求参数:

1
2
3
4
{
  "title": "2026-03-16 对话归档",
  "folder_token": "PimdfCKZQliPNFdOxpscb8tknUb"
}

Python 代码:

import json
import urllib.request

USER_ACCESS_TOKEN = "u-fLM1T9ZUJ0qWLyWRcZeTmg14hYkw5hMjq28a3xk007vp"
FOLDER_TOKEN = "PimdfCKZQliPNFdOxpscb8tknUb"

def create_docx(title, folder_token, user_token):
    url = "https://open.feishu.cn/open-apis/docx/v1/documents"
    data = json.dumps({
        "title": title,
        "folder_token": folder_token
    }).encode('utf-8')
    req = urllib.request.Request(url, data=data, headers={
        'Authorization': f'Bearer {user_token}',
        'Content-Type': 'application/json'
    })
    response = urllib.request.urlopen(req, timeout=10)
    result = json.loads(response.read().decode('utf-8'))
    return result

# 调用
result = create_docx("2026-03-16 对话归档", FOLDER_TOKEN, USER_ACCESS_TOKEN)
document_id = result['data']['document']['document_id']
print(f"文档创建成功:{document_id}")

返回结果:

1
2
3
4
5
6
7
8
9
{
  "code": 0,
  "data": {
    "document": {
      "document_id": "WG4YdDe16oZwcdxJbNscyEPOnwg",
      "title": "2026-03-16 对话归档"
    }
  }
}


步骤 2:写入文档内容

API 端点:

POST https://open.feishu.cn/open-apis/docx/v1/documents/{document_id}/blocks/{block_id}/children

关键参数: - document_id: 云文档 ID - block_id: 页面本身的 block_id(与 document_id 相同) - document_revision_id: 文档版本号(创建后为 1)

Python 代码:

def create_block_children(document_id, block_id, revision_id, children, user_token):
    url = f"https://open.feishu.cn/open-apis/docx/v1/documents/{document_id}/blocks/{block_id}/children"
    data = json.dumps({
        "document_revision_id": revision_id,
        "children": children,
        "index": 0
    }).encode('utf-8')
    req = urllib.request.Request(url, data=data, method='POST', headers={
        'Authorization': f'Bearer {user_token}',
        'Content-Type': 'application/json'
    })
    response = urllib.request.urlopen(req, timeout=10)
    return json.loads(response.read().decode('utf-8'))

# 构建内容块
CONTENT_BLOCKS = [
    {
        "block_type": 2,  # 2=文本段落
        "text": {
            "elements": [{
                "text_run": {
                    "content": "📅 时间:2026-03-16 23:36 - 2026-03-17 01:35\n"
                }
            }]
        }
    },
    # ... 更多内容块
]

# 调用
result = create_block_children(DOCUMENT_ID, DOCUMENT_ID, 1, CONTENT_BLOCKS, USER_ACCESS_TOKEN)

⚠️ 常见错误: - ❌ block not support to create → block_type 不能用 1(页面类型),必须用 2(文本段落) - ❌ 404 Not Found → 检查 document_id 和 block_id 是否正确


步骤 3:移动云文档到知识空间

API 端点:

POST https://open.feishu.cn/open-apis/wiki/v2/spaces/{space_id}/nodes/move_docs_to_wiki

请求参数:

1
2
3
4
5
{
  "parent_wiki_token": "W01EwPEiniSyEfkQd3ZctQsfnMb",  // 对话归档目录 token,空字符串表示根目录
  "obj_type": "docx",
  "obj_token": "WG4YdDe16oZwcdxJbNscyEPOnwg"  // 云文档的 document_id
}

Python 代码:

def move_doc_to_wiki(space_id, doc_id, parent_wiki_token, user_token):
    url = f"https://open.feishu.cn/open-apis/wiki/v2/spaces/{space_id}/nodes/move_docs_to_wiki"
    data = json.dumps({
        "parent_wiki_token": parent_wiki_token,
        "obj_type": "docx",
        "obj_token": doc_id
    }).encode('utf-8')
    req = urllib.request.Request(url, data=data, method='POST', headers={
        'Authorization': f'Bearer {user_token}',
        'Content-Type': 'application/json'
    })
    response = urllib.request.urlopen(req, timeout=10)
    return json.loads(response.read().decode('utf-8'))

# 调用
result = move_doc_to_wiki(SPACE_ID, DOCUMENT_ID, PARENT_WIKI_TOKEN, USER_ACCESS_TOKEN)
wiki_token = result['data']['wiki_token']
print(f"移动成功:https://xcny2sco1sb0.feishu.cn/wiki/{wiki_token}")

返回结果:

1
2
3
4
5
6
{
  "code": 0,
  "data": {
    "wiki_token": "VyaEwGNDaiH13tk62uycKU2in0e"
  }
}


❌ 踩过的坑(重要!)

1. 认证 Token 错误

问题: 使用 tenant_access_token 创建文档失败
错误信息: 99991672 - Access denied. One of the following scopes is required: [docx:document, docx:document:create]
解决: 必须使用 user_access_token

2. API 端点错误

问题: 尝试多个端点都返回 404
错误端点: - /wiki/v2/spaces/{space_id}/move_docs_to_wiki ❌ - /wiki/v2/space_node/move_docs_to_wiki ❌ - /wiki/v2/nodes/move_docs_to_wiki_space

正确端点:

/wiki/v2/spaces/{space_id}/nodes/move_docs_to_wiki ✅

3. parent_wiki_token 参数

问题: 使用错误的父节点 token 导致移动失败
错误信息: 131005 - not found: parent wiki node or space not exist
解决: - 移动到根目录:使用空字符串 "" - 移动到子目录:使用正确的 wiki node token

4. 云文档 vs Wiki 文档

问题: 尝试直接"移动"云文档到知识库
真相: 飞书不支持直接移动,API 实际是"在知识库中创建引用"
结果: 原文档 URL 变为 Wiki URL,内容保留

5. Block 类型错误

问题: 使用 block_type=1 创建内容失败
错误信息: 1770029 - block not support to create
解决: 内容块必须用 block_type=2(文本段落)


📊 完整脚本模板

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
飞书对话归档自动化脚本
用法:python3 feishu-archive.py
"""

import json
import urllib.request
from datetime import datetime

# ========== 配置信息 ==========
USER_ACCESS_TOKEN = "u-fLM1T9ZUJ0qWLyWRcZeTmg14hYkw5hMjq28a3xk007vp"
SPACE_ID = "7616106849955220687"
FOLDER_TOKEN = "PimdfCKZQliPNFdOxpscb8tknUb"  # 云文档文件夹
PARENT_WIKI_TOKEN = "W01EwPEiniSyEfkQd3ZctQsfnMb"  # 知识库对话归档目录

# ========== 核心函数 ==========
def create_docx(title, folder_token, user_token):
    """创建云文档"""
    url = "https://open.feishu.cn/open-apis/docx/v1/documents"
    data = json.dumps({"title": title, "folder_token": folder_token}).encode('utf-8')
    req = urllib.request.Request(url, data=data, headers={
        'Authorization': f'Bearer {user_token}',
        'Content-Type': 'application/json'
    })
    response = urllib.request.urlopen(req, timeout=10)
    return json.loads(response.read().decode('utf-8'))

def create_block_children(document_id, block_id, revision_id, children, user_token):
    """写入文档内容"""
    url = f"https://open.feishu.cn/open-apis/docx/v1/documents/{document_id}/blocks/{block_id}/children"
    data = json.dumps({
        "document_revision_id": revision_id,
        "children": children,
        "index": 0
    }).encode('utf-8')
    req = urllib.request.Request(url, data=data, method='POST', headers={
        'Authorization': f'Bearer {user_token}',
        'Content-Type': 'application/json'
    })
    response = urllib.request.urlopen(req, timeout=10)
    return json.loads(response.read().decode('utf-8'))

def move_doc_to_wiki(space_id, doc_id, parent_wiki_token, user_token):
    """移动云文档到知识空间"""
    url = f"https://open.feishu.cn/open-apis/wiki/v2/spaces/{space_id}/nodes/move_docs_to_wiki"
    data = json.dumps({
        "parent_wiki_token": parent_wiki_token,
        "obj_type": "docx",
        "obj_token": doc_id
    }).encode('utf-8')
    req = urllib.request.Request(url, data=data, method='POST', headers={
        'Authorization': f'Bearer {user_token}',
        'Content-Type': 'application/json'
    })
    response = urllib.request.urlopen(req, timeout=10)
    return json.loads(response.read().decode('utf-8'))

# ========== 主流程 ==========
def archive_conversation(date, content_blocks):
    """归档对话完整流程"""
    print(f"📝 开始归档:{date}")

    # 1. 创建云文档
    print("1️⃣ 创建云文档...")
    result = create_docx(f"{date} 对话归档", FOLDER_TOKEN, USER_ACCESS_TOKEN)
    if result.get('code') != 0:
        print(f"❌ 创建失败:{result}")
        return
    document_id = result['data']['document']['document_id']
    print(f"✅ 文档创建成功:{document_id}")

    # 2. 写入内容
    print("2️⃣ 写入内容...")
    result = create_block_children(document_id, document_id, 1, content_blocks, USER_ACCESS_TOKEN)
    if result.get('code') != 0:
        print(f"❌ 写入失败:{result}")
        return
    print(f"✅ 内容写入成功")

    # 3. 移动到知识库
    print("3️⃣ 移动到知识空间...")
    result = move_doc_to_wiki(SPACE_ID, document_id, PARENT_WIKI_TOKEN, USER_ACCESS_TOKEN)
    if result.get('code') != 0:
        print(f"❌ 移动失败:{result}")
        return
    wiki_token = result['data']['wiki_token']
    print(f"✅ 移动成功")
    print(f"🔗 最终 URL: https://xcny2sco1sb0.feishu.cn/wiki/{wiki_token}")

# ========== 执行 ==========
if __name__ == "__main__":
    # 示例:归档今日对话
    today = datetime.now().strftime("%Y-%m-%d")
    content = [
        {
            "block_type": 2,
            "text": {"elements": [{"text_run": {"content": f"# {today} 对话归档\n"}}]}
        },
        # ... 更多内容
    ]
    archive_conversation(today, content)

🔧 故障排查

错误码 错误信息 原因 解决方案
99991672 Access denied 使用 tenant_access_token 改用 user_access_token
1770029 block not support to create block_type 错误 使用 block_type=2
131005 not found: parent wiki node parent_wiki_token 错误 检查 token 是否正确
404 Not Found API 端点错误 使用正确的端点路径
400 Bad Request 参数格式错误 检查 JSON 格式

📌 快速参考卡片

┌─────────────────────────────────────────────────────────────┐
│ 飞书对话归档 - 快速参考                                      │
├─────────────────────────────────────────────────────────────┤
│ 知识库空间 ID:7616106849955220687                          │
│ 对话归档目录:W01EwPEiniSyEfkQd3ZctQsfnMb                   │
│ 云文档文件夹:PimdfCKZQliPNFdOxpscb8tknUb                   │
│ User Token: u-fLM1T9ZUJ0qWLyWRcZeTmg14hYkw5hMjq28a3xk007vp  │
├─────────────────────────────────────────────────────────────┤
│ API 端点:                                                  │
│ 创建:POST /open-apis/docx/v1/documents                     │
│ 写入:POST /docx/v1/documents/{id}/blocks/{id}/children     │
│ 移动:POST /wiki/v2/spaces/{id}/nodes/move_docs_to_wiki     │
└─────────────────────────────────────────────────────────────┘

🚀 后续优化

  • 封装为可复用脚本
  • 配置每日自动归档 Cron
  • 添加错误重试机制
  • 支持批量归档
  • 添加日志记录功能

⚠️ 下次归档前必读此文档!

最后更新:2026-03-17 02:08