使用 Google Apps Script 同步 Markdown 筆記至 NotebookLM
TLDR
- NotebookLM 目前不支援直接同步 Markdown (
.md) 檔案,且重複上傳會導致來源重複,無法自動更新。 - 透過 Google Apps Script (GAS) 建立自動化流程,可將本機 Markdown 檔案轉換為 Google Docs,並利用 Google Drive 的同步機制實現 NotebookLM 的自動更新。
- 核心邏輯:GAS 監控來源資料夾,將 Markdown 內容寫入 Google Docs,並在內容更新時進行覆寫,確保 NotebookLM 的引用與對話紀錄不中斷。
- 建議使用「分批寫入 (Chunking)」策略處理長篇筆記,避免超過 Google Docs 的單次寫入限制。
- 建議將核心同步邏輯封裝為 Library,以利多個專案共用並維持維護性。
NotebookLM 的同步機制與痛點
NotebookLM 目前支援從 Google Drive 同步 Google 文件 (Docs)、Google 簡報 (Slides)、PDF 和 Word (.docx) 等格式。當雲端檔案更新時,NotebookLM 會顯示同步提示。
什麼情況下會遇到這個問題: 當你習慣使用 Markdown 撰寫筆記,且希望將這些筆記作為 NotebookLM 的知識來源,並能隨著筆記內容迭代自動更新時。
目前面臨的主要痛點:
- 格式不支援:Google Drive 的 NotebookLM 同步功能不支援直接讀取
.md檔案。 - 重複上傳機制:即便檔名相同,NotebookLM 仍會將其視為全新來源,導致舊來源與新來源並存,無法直接更新內容。
- 目錄結構複雜:筆記若包含子資料夾,無法一次性選取並批次同步。
Google Apps Script 實作
為了解決上述問題,我們透過 GAS 建立一個「中轉服務」,將 Markdown 檔案轉換為 Google Docs。
1. 核心同步邏輯
將以下程式碼貼入 GAS 專案中,負責處理檔案遞迴掃描、Markdown 讀取以及 Google Doc 的建立與更新。
javascript
/**
* 將單一檔案同步至 Google Doc (含重試機制)
*/
function syncFileToGoogleDoc(sourceFile, targetFolder, targetDocName) {
const maxRetries = 3;
let attempt = 0;
let success = false;
while (attempt < maxRetries && !success) {
try {
attempt++;
const existingFiles = targetFolder.getFilesByName(targetDocName);
let targetDocFile = null;
while (existingFiles.hasNext()) {
const f = existingFiles.next();
if (f.getMimeType() === MimeType.GOOGLE_DOCS) {
targetDocFile = f;
break;
}
}
if (targetDocFile) {
if (sourceFile.getLastUpdated() > targetDocFile.getLastUpdated()) {
updateDocContent(targetDocFile.getId(), sourceFile);
}
} else {
createDocContent(targetFolder, targetDocName, sourceFile);
}
success = true;
} catch (e) {
if (attempt < maxRetries) {
Utilities.sleep(attempt * 3000);
} else {
throw new Error(`重試 ${maxRetries} 次後仍失敗: ` + e.message);
}
}
}
}
/**
* 分批寫入長文字內容 (Chunking Strategy)
*/
function writeContentInChunks(docBody, fullText) {
const CHUNK_SIZE = 20000;
docBody.setText("");
if (!fullText || fullText.length === 0) return;
for (let i = 0; i < fullText.length; i += CHUNK_SIZE) {
const chunk = fullText.substring(i, i + CHUNK_SIZE);
const paragraphs = docBody.getParagraphs();
const lastParagraph = paragraphs[paragraphs.length - 1];
if (lastParagraph) {
lastParagraph.appendText(chunk);
} else {
docBody.appendParagraph(chunk);
}
Utilities.sleep(150);
}
}什麼情況下會遇到這個問題: 當筆記內容過長,超過 Google Docs 單次寫入字數限制時,會導致同步失敗,必須採用分批寫入策略。
部署與自動化建議
1. 模組化管理
若有多個筆記專案,建議將核心同步邏輯部署為「資料庫 (Library)」。
- 在核心專案點擊「部署」 -> 「新增部署」 -> 選擇「資料庫」。
- 複製「指令碼 ID」,在其他專案的「資料庫」區塊中引用。
- 透過
SyncUtils.startSyncEngine(...)呼叫,並在各專案中設定不同的黑白名單。
2. 設定自動化觸發
- 點擊 GAS 左側的「觸發條件」圖示。
- 新增觸發條件,選擇主函式 (如
syncCloudyWingLog)。 - 活動來源選擇「時間驅動」,建議設定為每小時執行一次,確保筆記與 NotebookLM 保持同步。
TIP
首次執行時,Google 會要求授權存取 Google Drive 與建立文件的權限。若出現「Google 尚未驗證應用程式」警示,請點擊「進階」並選擇「前往...... (不安全)」即可完成授權。
異動歷程
- 2026-01-27 初版文件建立。
