飞书Doc与Drive模块深度解析:文档协作与云盘文件管理
摘要:文档与云盘是企业知识管理的基础设施。本文深入
lark-cli的shortcuts/doc/和shortcuts/drive/包,从文档的创建/读取/更新到云盘文件的上传/下载/导出,完整解析这两个模块的Shortcuts实现。包含文档操作流程图、云盘文件生命周期图、以及Python文档处理客户端的实战代码。
一、引言:知识管理的API化
1.1 场景驱动
# 基于模板创建周报lark-cli doc +create--title"周报-第3周"--markdown"# 本周进展\n- ..."# 搜索包含"架构设计"的文档lark-cli doc +search--query"架构设计"# 下载云盘文件lark-cli drive +download --file-token"boxxxxxxxxx"# 导出文档为PDFlark-cli drive +export --file-token"doxxxxxxxxx"--formatpdf二、Doc Shortcuts体系
2.1 文档操作
2.2 Markdown转飞书文档
飞书文档不是纯文本,而是块(Block)结构。Shortcuts负责将用户输入的Markdown转换为Block列表:
defmarkdown_to_blocks(md:str)->list:"""Markdown转飞书文档块"""blocks=[]forlineinmd.split("\n"):ifline.startswith("# "):blocks.append({"block_type":1,"heading1":{"elements":[{"text_run":{"content":line[2:]}}]}})elifline.startswith("## "):blocks.append({"block_type":2,"heading2":{"elements":[{"text_run":{"content":line[3:]}}]}})elifline.startswith("- "):blocks.append({"block_type":13,"bullet":{"elements":[{"text_run":{"content":line[2:]}}]}})elifline.strip():blocks.append({"block_type":2,"text":{"elements":[{"text_run":{"content":line}}]}})returnblocks三、Drive Shortcuts体系
3.1 云盘文件操作
// shortcuts/drive/drive_download.govarDownloadShortcut=common.Shortcut{Service:"drive",Command:"+download",AuthTypes:[]string{"user","bot"},Flags:[]common.Flag{{Name:"file-token",Type:"string",Required:true,Desc:"文件Token"},{Name:"output",Type:"string",Required:true,Desc:"保存路径"},},Execute:func(ctx context.Context,rctx*common.RuntimeContext)error{fileToken:=rctx.Str("file-token")outputPath:=rctx.Str("output")// 使用DoAPI获取原始响应(二进制)req:=&larkcore.ApiReq{HttpMethod:"GET",ApiPath:fmt.Sprintf("/open-apis/drive/v1/files/%s/download",fileToken),}resp,err:=rctx.DoAPI(req,larkcore.WithFileDownload())iferr!=nil{returnerr}// 写入文件os.WriteFile(outputPath,resp.RawBody,0644)rctx.Out(map[string]string{"downloaded":outputPath},nil)returnnil},}四、Python实战:文档批处理工具
#!/usr/bin/env python3# -*- coding: utf-8 -*-""" doc_processor.py 飞书文档批处理工具 """importjsonfrompathlibimportPathimportrequestsclassDocProcessor:"""文档处理器"""def__init__(self,access_token:str):self.token=access_token self.base="https://open.feishu.cn"defcreate_doc(self,title:str,content_md:str)->str:"""基于Markdown创建文档"""url=f"{self.base}/open-apis/docx/v1/documents"resp=requests.post(url,json={"title":title},headers={"Authorization":f"Bearer{self.token}"})doc_id=resp.json()["data"]["document"]["document_id"]# 批量插入内容块(简化版)blocks=self._md_to_blocks(content_md)batch_url=f"{self.base}/open-apis/docx/v1/documents/{doc_id}/blocks/{doc_id}/children/batch_create"requests.post(batch_url,json={"children":blocks},headers={"Authorization":f"Bearer{self.token}"})returndoc_iddef_md_to_blocks(self,md:str)->list:"""Markdown转Block(简化版)"""blocks=[]forlineinmd.split("\n"):line=line.strip()ifnotline:continueifline.startswith("# "):blocks.append({"block_type":1,"heading1":{"elements":[{"text_run":{"content":line[2:]}}]}})elifline.startswith("## "):blocks.append({"block_type":2,"heading2":{"elements":[{"text_run":{"content":line[3:]}}]}})else:blocks.append({"block_type":2,"text":{"elements":[{"text_run":{"content":line}}]}})returnblocksdefdownload_file(self,file_token:str,output_path:str)->None:"""下载云盘文件"""url=f"{self.base}/open-apis/drive/v1/files/{file_token}/download"resp=requests.get(url,headers={"Authorization":f"Bearer{self.token}"})Path(output_path).write_bytes(resp.content)if__name__=="__main__":processor=DocProcessor("u-xxxxxxxx")doc_id=processor.create_doc("测试文档","# 标题\n正文内容")print(f"创建文档:{doc_id}")五、FAQ与最佳实践
Q1:Doc和Drive的Token有什么区别?
Doc使用
document_id(doc_xxx/dox_xxx),Drive文件使用file_token(box_xxx)。下载文档内容通过Docx API,下载云盘文件通过Drive API。
Q2:如何导出文档为PDF?
飞书提供异步导出接口:先创建导出任务,轮询任务状态,最后下载导出文件。lark-cli的
+exportShortcut封装了这一复杂流程。
六、总结
Doc与Drive的设计要点:
- Doc是块结构:不是纯文本,而是heading/paragraph/bullet/image等块的组合
- Drive处理二进制:上传/下载需要multipart/form-data和流式处理
- 导出是异步的:PDF/Word导出需要创建任务→轮询→下载的三步流程
参考资料
- lark-cli 源码-
shortcuts/doc/: Doc Shortcuts - lark-cli 源码-
shortcuts/drive/: Drive Shortcuts - 飞书Docx API: https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/docx-v1
- 飞书Drive API: https://open.feishu.cn/document/uAjLw4CM/ukTMukTMukTM/reference/drive-v1
本文基于 lark-cli Doc/Drive模块源码分析。
