# -*- coding: gbk -*- """从飞书知识库批量拉取文档内容,填充到本地SQLite数据库""" import sqlite3 import os import sys import json import time import urllib.request import urllib.error DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "audit_data.db") FEISHU_BASE = "https://open.feishu.cn/open-apis" def get_feishu_config(): """从config.py获取飞书应用凭证""" config_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, config_dir) try: import config app_id = getattr(config, "FEISHU_APP_ID", None) or getattr(config, "APP_ID", None) app_secret = getattr(config, "FEISHU_APP_SECRET", None) or getattr(config, "APP_SECRET", None) if not app_id or not app_secret: print("config.py 中未找到飞书凭证 (FEISHU_APP_ID / FEISHU_APP_SECRET)") print(f"config.py 中的属性: {[k for k in dir(config) if not k.startswith('_')]}") return None, None return app_id, app_secret except ImportError: print("无法导入 config.py,请确认文件存在") return None, None def get_tenant_token(app_id, app_secret): """获取飞书租户access_token""" url = f"{FEISHU_BASE}/auth/v3/tenant_access_token/internal" data = json.dumps({"app_id": app_id, "app_secret": app_secret}).encode("utf-8") req = urllib.request.Request(url, data=data, headers={"Content-Type": "application/json; charset=utf-8"}) with urllib.request.urlopen(req, timeout=10) as resp: result = json.loads(resp.read().decode("utf-8")) if result.get("code") != 0: raise Exception(f"获取token失败: {result.get('msg')}") return result["tenant_access_token"] def get_wiki_nodes(space_id, token): """获取知识空间顶层节点""" nodes = [] page_token = "" has_more = True while has_more: url = f"{FEISHU_BASE}/wiki/v2/spaces/{space_id}/nodes?page_size=50" if page_token: url += f"&page_token={page_token}" req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"}) try: with urllib.request.urlopen(req, timeout=15) as resp: result = json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as e: print(f" 获取节点失败 (HTTP {e.code}): {e.reason}") break if result.get("code") != 0: print(f" 获取节点失败: {result.get('msg')}") break data = result.get("data", {}) for node in data.get("items", []): nodes.append({ "node_token": node.get("node_token", ""), "obj_token": node.get("obj_token", ""), "obj_type": node.get("obj_type", ""), "title": node.get("title", ""), "has_child": node.get("has_child", False), }) page_token = data.get("page_token", "") has_more = data.get("has_more", False) return nodes def get_sub_nodes(space_id, parent_token, token): """获取子节点""" url = f"{FEISHU_BASE}/wiki/v2/spaces/{space_id}/nodes?parent_node_token={parent_token}&page_size=50" req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"}) try: with urllib.request.urlopen(req, timeout=15) as resp: result = json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError: return [] if result.get("code") != 0: return [] return result.get("data", {}).get("items", []) def get_all_nodes_recursive(space_id, token): """递归获取知识空间下所有节点,返回 {node_token: node_info}""" all_nodes = {} top_nodes = get_wiki_nodes(space_id, token) queue = list(top_nodes) while queue: node = queue.pop(0) nt = node.get("node_token", "") if nt and nt not in all_nodes: all_nodes[nt] = node if node.get("has_child"): subs = get_sub_nodes(space_id, nt, token) for sn in subs: queue.append({ "node_token": sn.get("node_token", ""), "obj_token": sn.get("obj_token", ""), "obj_type": sn.get("obj_type", ""), "title": sn.get("title", ""), "has_child": sn.get("has_child", False), }) return all_nodes def get_doc_content(obj_token, token): """获取文档正文(原始格式)""" url = f"{FEISHU_BASE}/docx/v1/documents/{obj_token}/raw_content" req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"}) try: with urllib.request.urlopen(req, timeout=15) as resp: result = json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as e: print(f" HTTP {e.code}: {e.reason}", end="") return "" if result.get("code") != 0: return "" return result.get("data", {}).get("content", "") def get_doc_blocks(obj_token, token): """通过blocks API获取文档内容(备用方案)""" url = f"{FEISHU_BASE}/docx/v1/documents/{obj_token}/blocks?page_size=500&document_revision_id=-1" req = urllib.request.Request(url, headers={"Authorization": f"Bearer {token}"}) try: with urllib.request.urlopen(req, timeout=15) as resp: result = json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError: return "" if result.get("code") != 0: return "" blocks = result.get("data", {}).get("items", []) text_parts = [] for block in blocks: btype = block.get("block_type", 0) if btype in (2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15): elements = block.get("text", {}).get("elements", []) line = "".join(e.get("text_run", {}).get("content", "") for e in elements) if line.strip(): if btype == 3: text_parts.append(f"# {line}") elif btype == 4: text_parts.append(f"## {line}") elif btype == 5: text_parts.append(f"### {line}") else: text_parts.append(line) return "\n".join(text_parts) def main(): print("=" * 60) print("飞书知识库内容批量同步脚本") print("=" * 60) app_id, app_secret = get_feishu_config() if not app_id: print("\n请手动在脚本中填写飞书凭证后运行。") return print("\n[1/4] 获取飞书访问令牌...") try: token = get_tenant_token(app_id, app_secret) print(f" 令牌获取成功: {token[:20]}...") except Exception as e: print(f" 令牌获取失败: {e}") return conn = sqlite3.connect(DB_PATH, timeout=10) conn.row_factory = sqlite3.Row conn.execute("PRAGMA journal_mode = WAL") total_docs = conn.execute("SELECT COUNT(*) FROM knowledge_docs").fetchone()[0] empty_docs = conn.execute("SELECT COUNT(*) FROM knowledge_docs WHERE content IS NULL OR content = ''").fetchone()[0] print(f"\n[2/4] 数据库统计:") print(f" 文档总数: {total_docs}") print(f" 空内容: {empty_docs}") print(f" 有内容: {total_docs - empty_docs}") if empty_docs == 0: print("\n所有文档都有内容,无需同步。") conn.close() return spaces = conn.execute("SELECT space_id, name FROM knowledge_spaces ORDER BY id").fetchall() print(f"\n[3/4] 知识空间数: {len(spaces)}") empty_rows = conn.execute( "SELECT id, space_id, node_token, title FROM knowledge_docs WHERE content IS NULL OR content = '' ORDER BY id" ).fetchall() print(f"\n[4/4] 开始从飞书拉取内容...") updated = 0 failed = 0 skipped = 0 for space in spaces: space_id = space["space_id"] space_name = space["name"] print(f"\n--- 空间: {space_name} ({space_id}) ---") print(f" 获取飞书节点树...") try: feishu_nodes = get_all_nodes_recursive(space_id, token) print(f" 飞书返回 {len(feishu_nodes)} 个节点") except Exception as e: print(f" 获取节点树失败: {e}") continue space_rows = [r for r in empty_rows if r["space_id"] == space_id] for row in space_rows: node_token = row["node_token"] title = row["title"] idx = updated + failed + skipped + 1 print(f" [{idx}/{empty_docs}] {title[:40]}...", end=" ") feishu_node = feishu_nodes.get(node_token) if not feishu_node: for fn_token, fn_data in feishu_nodes.items(): if fn_data.get("title") == title: feishu_node = fn_data break if not feishu_node: print("跳过(节点未找到)") skipped += 1 continue obj_token = feishu_node.get("obj_token", "") obj_type = feishu_node.get("obj_type", "") if not obj_token: print("跳过(无obj_token)") skipped += 1 continue if obj_type and obj_type != "docx": print(f"跳过(类型={obj_type})") skipped += 1 continue try: content = get_doc_content(obj_token, token) if not content: content = get_doc_blocks(obj_token, token) if content: if len(content) > 50000: content = content[:50000] + "\n...(内容过长已截断)" conn.execute("UPDATE knowledge_docs SET content = ? WHERE id = ?", (content, row["id"])) conn.commit() updated += 1 print(f"成功 ({len(content)}字符)") else: failed += 1 print("失败(内容为空)") except Exception as e: failed += 1 print(f"失败({e})") time.sleep(0.5) conn.close() print("\n" + "=" * 60) print(f"同步完成!") print(f" 成功更新: {updated}") print(f" 失败: {failed}") print(f" 跳过: {skipped}") print(f" 总计: {empty_docs}") print("=" * 60) if __name__ == "__main__": main()