{
  "name": "Bulk YouTube transcripts (Data Table queue)",
  "nodes": [
    {
      "parameters": {
        "content": "## Bulk YouTube transcripts\n**Part A** (top) adds videos and channels to a queue. **Part B** (bottom) runs every 30 minutes and fetches up to 50 pending transcripts per run.\n\n**Data table (once):** Overview → Data tables → Create. Name it `youtube_transcripts` with these columns: `video_id` (string), `url` (string), `title` (string), `channel` (string), `status` (string), `language` (string), `words` (number), `transcript` (string), `attempts` (number), `last_error` (string), `checked_at` (string).\n\n**YouTubeTranscriptAPI key (once):** Credentials → New → Header Auth. Name: `Authorization`. Value: `Bearer tk_live_…` (your key from youtubetranscriptapi.com/dashboard/keys). Call it *YouTubeTranscriptAPI key* and pick it in every YouTube node.\n\n**Run:** edit *Video links and channels*, execute Part A, then execute Part B by hand once before you activate the workflow.\n\n**Cost:** 1 credit per transcript, 20 per channel listing. Videos without captions, errors and 429s are free.",
        "width": 520,
        "height": 520,
        "color": 5
      },
      "id": "da270134-4fdc-48da-8b57-b8f8a86f3b1c",
      "name": "Setup",
      "type": "n8n-nodes-base.stickyNote",
      "typeVersion": 1,
      "position": [
        -620,
        -40
      ]
    },
    {
      "parameters": {},
      "id": "4664d8c7-c7d0-499c-8dd2-e15947d03285",
      "name": "Add videos",
      "type": "n8n-nodes-base.manualTrigger",
      "typeVersion": 1,
      "position": [
        0,
        0
      ]
    },
    {
      "parameters": {
        "jsCode": "// One per line: video links, youtu.be links, Shorts links, bare video IDs,\n// @handles or channel links. Anything that isn't a video is listed as a channel\n// (20 credits for its 100 most recent uploads).\nconst inputs = [\n  \"https://www.youtube.com/watch?v=dQw4w9WgXcQ\",\n  \"@freecodecamp\",\n];\n\nconst videoId = (s) => {\n  const m = s.match(/(?:[?&]v=|youtu\\.be\\/|\\/shorts\\/|\\/embed\\/|\\/live\\/)([\\w-]{11})/);\n  if (m) return m[1];\n  return /^[\\w-]{11}$/.test(s) ? s : null;\n};\n\n// Duplicates are dropped here: the \"already queued\" check only sees rows\n// saved before this run.\nconst seen = new Set();\nconst out = [];\nfor (const s of inputs.map((x) => x.trim()).filter(Boolean)) {\n  const id = videoId(s);\n  const key = id ?? s.toLowerCase();\n  if (seen.has(key)) continue;\n  seen.add(key);\n  out.push(id\n    ? { json: { kind: \"video\", video_id: id, url: `https://www.youtube.com/watch?v=${id}`, title: \"\", channel: \"\" } }\n    : { json: { kind: \"channel\", channel: s } });\n}\nreturn out;"
      },
      "id": "c803e321-ec30-4f7b-8ff5-9ca142141def",
      "name": "Video links and channels",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        220,
        0
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "9c52cfc2-b9fc-49cf-83de-04dc21941546",
              "leftValue": "={{ $json.kind }}",
              "rightValue": "channel",
              "operator": {
                "type": "string",
                "operation": "equals"
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "16cfb2c7-a1ec-424e-867e-158d8aa54aad",
      "name": "Channel?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        440,
        0
      ]
    },
    {
      "parameters": {
        "url": "https://youtubetranscriptapi.com/api/v2/youtube/channel/videos",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "channel",
              "value": "={{ $json.channel }}"
            }
          ]
        },
        "options": {}
      },
      "id": "373558bc-130c-4b3a-861a-2a099995e469",
      "name": "List channel uploads",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        660,
        -100
      ]
    },
    {
      "parameters": {
        "jsCode": "const seen = new Set();\nconst out = [];\nfor (const item of $input.all()) {\n  for (const v of item.json.results ?? []) {\n    if (!v.videoId || seen.has(v.videoId)) continue;\n    seen.add(v.videoId);\n    out.push({ json: {\n      video_id: v.videoId,\n      url: `https://www.youtube.com/watch?v=${v.videoId}`,\n      title: v.title ?? \"\",\n      channel: v.channelTitle ?? \"\",\n    } });\n  }\n}\nreturn out;"
      },
      "id": "75c9260b-f4c5-4e64-89c9-c1622f544400",
      "name": "One row per upload",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        880,
        -100
      ]
    },
    {
      "parameters": {
        "resource": "row",
        "operation": "rowNotExists",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "youtube_transcripts"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "video_id",
              "condition": "eq",
              "keyValue": "={{ $json.video_id }}"
            }
          ]
        }
      },
      "id": "d2a8e60f-2de7-4ed6-81b5-97120bf48b6e",
      "name": "Skip videos already queued",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1100,
        0
      ]
    },
    {
      "parameters": {
        "resource": "row",
        "operation": "insert",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "youtube_transcripts"
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "video_id": "={{ $json.video_id }}",
            "url": "={{ $json.url }}",
            "title": "={{ $json.title }}",
            "channel": "={{ $json.channel }}",
            "attempts": 0
          },
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "3ce1a324-2f12-4e98-8499-c6e6f64bbe7b",
      "name": "Add to queue",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1320,
        0
      ]
    },
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "field": "minutes",
              "minutesInterval": 30
            }
          ]
        }
      },
      "id": "35343335-5a47-4c0d-8f73-c20280be8473",
      "name": "Every 30 minutes",
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        0,
        420
      ]
    },
    {
      "parameters": {
        "resource": "row",
        "operation": "get",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "youtube_transcripts"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "status",
              "condition": "isEmpty"
            }
          ]
        },
        "returnAll": false,
        "limit": 50
      },
      "id": "2edc0b93-3bd0-4a34-8d79-d8c7eb007c79",
      "name": "Next pending videos",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        220,
        420
      ]
    },
    {
      "parameters": {
        "url": "https://youtubetranscriptapi.com/api/v2/youtube/transcript",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendQuery": true,
        "queryParameters": {
          "parameters": [
            {
              "name": "video_url",
              "value": "={{ $json.video_id }}"
            },
            {
              "name": "format",
              "value": "text"
            },
            {
              "name": "include_timestamp",
              "value": "false"
            },
            {
              "name": "send_metadata",
              "value": "true"
            }
          ]
        },
        "options": {
          "batching": {
            "batch": {
              "batchSize": 4,
              "batchInterval": 1000
            }
          },
          "response": {
            "response": {
              "fullResponse": true,
              "neverError": true,
              "responseFormat": "json"
            }
          },
          "timeout": 60000
        }
      },
      "id": "f96e1641-1b6b-4586-8151-2abd75c8af78",
      "name": "Get transcript",
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.2,
      "position": [
        560,
        420
      ],
      "onError": "continueRegularOutput"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "// Turns one API answer into one row update. It never throws, so a bad video\n// can't stop the other 49. Pending rows keep an empty status and are retried\n// on the next run; errors and 429s are never charged.\nconst row = $('Next pending videos').item.json;\nconst res = $json;\nconst code = Number(res.statusCode ?? 0); // 0: timeout or network error\nconst body = res.body ?? {};\nconst attempts = Number(row.attempts ?? 0) + 1;\nconst left = res.headers?.['x-credits-remaining'];\n\nconst out = {\n  video_id: row.video_id,\n  status: null,\n  title: row.title ?? \"\",\n  channel: row.channel ?? \"\",\n  language: row.language ?? \"\",\n  words: row.words ?? null,\n  transcript: row.transcript ?? \"\",\n  attempts,\n  last_error: \"\",\n  checked_at: new Date().toISOString(),\n  http_status: code,\n  credits_left: left === undefined ? null : Number(left),\n};\n\nif (code === 200) {\n  const text = typeof body.transcript === \"string\"\n    ? body.transcript\n    : (body.transcript ?? []).map((s) => s.text).join(\" \");\n  out.status = \"done\";\n  out.title = body.metadata?.title ?? out.title;\n  out.channel = body.metadata?.author_name ?? out.channel;\n  out.language = body.language ?? \"\";\n  out.transcript = text;\n  out.words = text.split(/\\s+/).filter(Boolean).length;\n} else if (code === 404) {\n  out.status = \"no captions\";\n} else if (code === 422) {\n  out.status = \"bad link\";\n} else {\n  const why = { 401: \"API key rejected\", 402: \"out of credits\", 403: \"account paused\", 408: \"timeout, retrying\", 429: \"rate limited, retrying\", 503: \"busy, retrying\" };\n  out.last_error = why[code] ?? (code ? `HTTP ${code}` : \"no answer (network or timeout)\");\n  if (attempts >= 5 && ![401, 402, 403].includes(code)) out.status = \"failed\";\n}\n\nreturn { json: out };"
      },
      "id": "059e65de-a4db-43c2-8454-77507d4488b6",
      "name": "Sort the result",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        780,
        420
      ]
    },
    {
      "parameters": {
        "resource": "row",
        "operation": "update",
        "dataTableId": {
          "__rl": true,
          "mode": "name",
          "value": "youtube_transcripts"
        },
        "matchType": "allConditions",
        "filters": {
          "conditions": [
            {
              "keyName": "video_id",
              "condition": "eq",
              "keyValue": "={{ $json.video_id }}"
            }
          ]
        },
        "columns": {
          "mappingMode": "defineBelow",
          "value": {
            "status": "={{ $json.status }}",
            "title": "={{ $json.title }}",
            "channel": "={{ $json.channel }}",
            "language": "={{ $json.language }}",
            "words": "={{ $json.words }}",
            "transcript": "={{ $json.transcript }}",
            "attempts": "={{ $json.attempts }}",
            "last_error": "={{ $json.last_error }}",
            "checked_at": "={{ $json.checked_at }}"
          },
          "matchingColumns": [],
          "schema": []
        },
        "options": {}
      },
      "id": "782000aa-723a-4b14-8914-98d43ab41c40",
      "name": "Save the result",
      "type": "n8n-nodes-base.dataTable",
      "typeVersion": 1.1,
      "position": [
        1000,
        420
      ]
    },
    {
      "parameters": {
        "jsCode": "const rows = $('Sort the result').all().map((i) => i.json);\nconst count = (s) => rows.filter((r) => r.status === s).length;\nconst lefts = rows.map((r) => r.credits_left).filter((n) => Number.isFinite(n));\nconst creditsLeft = lefts.length ? Math.min(...lefts) : null;\nconst blocked = rows.find((r) => [401, 402, 403].includes(r.http_status));\nconst LOW = 50; // stop and warn below this many credits\nconst stop = Boolean(blocked) || (creditsLeft !== null && creditsLeft < LOW);\nconst message = blocked\n  ? `Stopped: ${blocked.last_error}. Top up credits or fix the key, then run again.`\n  : `Top up credits: ${creditsLeft} left.`;\nreturn [{ json: {\n  done: count(\"done\"),\n  no_captions: count(\"no captions\"),\n  bad_link: count(\"bad link\"),\n  failed: count(\"failed\"),\n  still_pending: rows.filter((r) => r.status === null).length,\n  credits_left: creditsLeft,\n  stop,\n  message,\n} }];"
      },
      "id": "54b22d8a-822d-4576-8c61-e68fcb3400d9",
      "name": "Run summary",
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        1220,
        420
      ]
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict",
            "version": 2
          },
          "conditions": [
            {
              "id": "fde2d4d1-d146-4767-8cec-74b71d237d3e",
              "leftValue": "={{ $json.stop }}",
              "rightValue": "",
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "id": "e7a9b5cd-ff99-4ab4-83a7-78a033e08d8f",
      "name": "Out of credits?",
      "type": "n8n-nodes-base.if",
      "typeVersion": 2.2,
      "position": [
        1440,
        420
      ]
    },
    {
      "parameters": {
        "errorMessage": "={{ $json.message }}"
      },
      "id": "015dd37f-ca4f-4e2f-8b7b-ed313cff66b6",
      "name": "Top up credits",
      "type": "n8n-nodes-base.stopAndError",
      "typeVersion": 1,
      "position": [
        1660,
        400
      ]
    }
  ],
  "connections": {
    "Add videos": {
      "main": [
        [
          {
            "node": "Video links and channels",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Video links and channels": {
      "main": [
        [
          {
            "node": "Channel?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Channel?": {
      "main": [
        [
          {
            "node": "List channel uploads",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Skip videos already queued",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "List channel uploads": {
      "main": [
        [
          {
            "node": "One row per upload",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "One row per upload": {
      "main": [
        [
          {
            "node": "Skip videos already queued",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Skip videos already queued": {
      "main": [
        [
          {
            "node": "Add to queue",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Every 30 minutes": {
      "main": [
        [
          {
            "node": "Next pending videos",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Next pending videos": {
      "main": [
        [
          {
            "node": "Get transcript",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Get transcript": {
      "main": [
        [
          {
            "node": "Sort the result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sort the result": {
      "main": [
        [
          {
            "node": "Save the result",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Save the result": {
      "main": [
        [
          {
            "node": "Run summary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Run summary": {
      "main": [
        [
          {
            "node": "Out of credits?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Out of credits?": {
      "main": [
        [
          {
            "node": "Top up credits",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "pinData": {},
  "settings": {
    "executionOrder": "v1"
  },
  "meta": {
    "templateCredsSetupCompleted": false
  }
}