{
  "name": "Analyze YouTube channel performance with Telegram, Google Sheets, and Gemini",
  "nodes": [
    {
      "id": "e29eaf3f-1ce0-42da-aa82-e82bcdb1797a",
      "name": "Sticky Note",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        -288,
        80
      ],
      "parameters": {
        "width": 480,
        "height": 896,
        "content": "## Youtube Channel Analyser\n\n### How it works\n\nThis workflow lets a user send a YouTube channel link through Telegram, validates and resolves the channel with the YouTube Data API, then fetches recent upload and video statistics. It computes channel/video velocity metrics, builds a channel fingerprint, logs valid snapshots to Google Sheets, and uses Gemini to generate a Telegram channel analysis report. It also returns Telegram messages for bad links, missing channels, API errors, or insufficient sample size.\n\n### Setup steps\n\n- Connect Telegram credentials for the trigger and all Telegram message nodes, and configure the bot/chat permissions.\n- Configure YouTube Data API access in the HTTP Request nodes, including the API key and any channel lookup parameters used by the expressions.\n- Connect Google Sheets credentials and select the target spreadsheet/sheet for the snapshot log, ensuring the expected columns exist.\n- Connect Google Gemini credentials for the LangChain/Gemini nodes and verify the model is available in your region/account.\n- Test with several YouTube channel URL formats to confirm the parsing and validation expressions match the links users will send.\n\n### Customization\n\nAdjust the number of uploads fetched, the sample-size threshold, velocity/baseline formulas, Google Sheets columns, and the Gemini prompt to match the type of channel analysis you want to produce."
      },
      "typeVersion": 1
    },
    {
      "id": "c55c3bdf-a794-4a3c-9f75-eb0ab6799c49",
      "name": "Sticky Note1",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        272,
        480
      ],
      "parameters": {
        "color": 7,
        "width": 640,
        "height": 320,
        "content": "## Receive channel request\n\nStarts from a Telegram message, extracts the chat and channel lookup details, and checks whether the submitted link is valid before continuing."
      },
      "typeVersion": 1
    },
    {
      "id": "24a66b13-2a3d-4004-8bc7-d334406ac3dc",
      "name": "Sticky Note2",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        944,
        320
      ],
      "parameters": {
        "color": 7,
        "width": 640,
        "height": 592,
        "content": "## Resolve channel status\n\nLooks up the YouTube channel, branches on whether it exists, and sends Telegram responses for invalid links, API errors, or missing channels."
      },
      "typeVersion": 1
    },
    {
      "id": "f663569a-2802-4df5-8d80-723d745a5b93",
      "name": "Sticky Note3",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        1616,
        224
      ],
      "parameters": {
        "color": 7,
        "width": 640,
        "height": 304,
        "content": "## Fetch recent uploads\n\nShapes the resolved channel profile and retrieves the latest upload playlist items, splitting the upload list into individual records."
      },
      "typeVersion": 1
    },
    {
      "id": "1556ac8d-5621-4faf-922e-bd0f3681be24",
      "name": "Sticky Note4",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2288,
        192
      ],
      "parameters": {
        "color": 7,
        "width": 640,
        "height": 320,
        "content": "## Request video statistics\n\nCollects the recent video IDs, requests their detailed YouTube statistics in a batch call, and splits the returned videos for per-video processing."
      },
      "typeVersion": 1
    },
    {
      "id": "20fe5e1a-646b-469f-bffa-436bebb06f16",
      "name": "Sticky Note5",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        2960,
        224
      ],
      "parameters": {
        "color": 7,
        "width": 640,
        "height": 304,
        "content": "## Rank video velocity\n\nNormalizes video metrics, sorts videos by velocity, and aggregates the ranked set for channel-level calculations."
      },
      "typeVersion": 1
    },
    {
      "id": "cf54e5db-00e6-477f-9374-5c5aa4c15928",
      "name": "Sticky Note6",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        3632,
        176
      ],
      "parameters": {
        "color": 7,
        "width": 416,
        "height": 336,
        "content": "## Build channel fingerprint\n\nCalculates baseline performance metrics and creates a compact fingerprint summarizing the channel\u2019s recent publishing and performance characteristics."
      },
      "typeVersion": 1
    },
    {
      "id": "dabee004-19be-4e80-8b69-fe1adbba5726",
      "name": "Sticky Note7",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4080,
        80
      ],
      "parameters": {
        "color": 7,
        "width": 416,
        "height": 528,
        "content": "## Validate sample logging\n\nChecks whether the sample is large enough for analysis, logs valid snapshots to Google Sheets, or notifies the user when no reliable baseline can be created."
      },
      "typeVersion": 1
    },
    {
      "id": "035765c2-5c32-4ade-8779-ade0513d9be6",
      "name": "Sticky Note8",
      "type": "n8n-nodes-base.stickyNote",
      "position": [
        4528,
        128
      ],
      "parameters": {
        "color": 7,
        "width": 544,
        "height": 528,
        "content": "## Generate Telegram report\n\nUses Gemini to analyze the logged channel snapshot and sends the generated channel report back to the Telegram chat."
      },
      "typeVersion": 1
    },
    {
      "id": "2a75bd60-218b-4986-bccd-732e1105466d",
      "name": "Handle Telegram API Error",
      "type": "n8n-nodes-base.telegram",
      "onError": "continueRegularOutput",
      "position": [
        1216,
        640
      ],
      "parameters": {
        "text": "=YouTube API call failed.\n\n{{ String((typeof $json.error === 'object' && $json.error && $json.error.message) ? $json.error.message : ($json.error || 'unknown')).replace(/[`*_\\[\\]()~>#+=|{}\\\\\"]/g, ' ').replace(/\\s+/g, ' ').slice(0, 250) }}\n\nThis is an API or credential problem, not a missing channel.",
        "chatId": "={{ $('Set Channel Lookup Details').first().json.chat_id }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "63474546-1801-4291-ae6b-97aeb792edb0",
      "name": "When Telegram Message Received",
      "type": "n8n-nodes-base.telegramTrigger",
      "position": [
        320,
        640
      ],
      "parameters": {
        "updates": [
          "message"
        ],
        "additionalFields": {}
      },
      "typeVersion": 1.1
    },
    {
      "id": "02acf681-fd92-4910-ad57-25e0fd710b1e",
      "name": "Set Channel Lookup Details",
      "type": "n8n-nodes-base.set",
      "position": [
        544,
        640
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "p1",
              "name": "chat_id",
              "type": "number",
              "value": "={{ $json.message.chat.id }}"
            },
            {
              "id": "p2",
              "name": "lookup_type",
              "type": "string",
              "value": "={{ /youtube\\.com\\/channel\\/(UC[A-Za-z0-9_-]{22})/.test($json.message.text || '') ? 'id' : (/youtube\\.com\\/@([A-Za-z0-9._-]+)/.test($json.message.text || '') ? 'forHandle' : 'none') }}"
            },
            {
              "id": "p3",
              "name": "lookup_value",
              "type": "string",
              "value": "={{ (function(t){ var c = t.match(/youtube\\.com\\/channel\\/(UC[A-Za-z0-9_-]{22})/); if (c) return c[1]; var h = t.match(/youtube\\.com\\/@([A-Za-z0-9._-]+)/); if (h) return '@' + h[1]; return ''; })($json.message.text || '') }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "b3a5154f-fb63-4942-8104-3820f63dced5",
      "name": "If Valid Channel Link",
      "type": "n8n-nodes-base.if",
      "position": [
        768,
        640
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "islink",
              "operator": {
                "type": "string",
                "operation": "notEquals"
              },
              "leftValue": "={{ $json.lookup_type }}",
              "rightValue": "none"
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "1672d09e-d636-4236-b6fa-3e9b875f3e05",
      "name": "Notify Bad Channel Link",
      "type": "n8n-nodes-base.telegram",
      "position": [
        992,
        736
      ],
      "parameters": {
        "text": "=I could not find a channel in that message.\n\nSend a URL like:\nhttps://www.youtube.com/@handle\nhttps://www.youtube.com/channel/UCxxxxxxxxxxxxxxxxxxxxxx",
        "chatId": "={{ $('Set Channel Lookup Details').first().json.chat_id }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "1a9da255-3265-42e6-ad1b-02bef6f08c18",
      "name": "Fetch YouTube Channel Info",
      "type": "n8n-nodes-base.httpRequest",
      "notes": "Filter key is an expression in the parameter NAME field, so the URL stays static and query auth can append the key cleanly.",
      "onError": "continueErrorOutput",
      "position": [
        992,
        544
      ],
      "parameters": {
        "url": "https://www.googleapis.com/youtube/v3/channels",
        "options": {},
        "sendQuery": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "queryParameters": {
          "parameters": [
            {
              "name": "part",
              "value": "snippet,statistics,contentDetails"
            },
            {
              "name": "={{ $json.lookup_type }}",
              "value": "={{ $json.lookup_value }}"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "06750d62-b5fa-4757-a0df-e656e8f5bcaf",
      "name": "If Channel Exists",
      "type": "n8n-nodes-base.if",
      "position": [
        1216,
        448
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "found",
              "operator": {
                "type": "number",
                "operation": "gte"
              },
              "leftValue": "={{ $json.items ? $json.items.length : 0 }}",
              "rightValue": 1
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "1279c21f-a830-48ab-b83b-e96f32ebabef",
      "name": "Notify Channel Not Found",
      "type": "n8n-nodes-base.telegram",
      "position": [
        1440,
        544
      ],
      "parameters": {
        "text": "=No channel matched {{ String($('Set Channel Lookup Details').first().json.lookup_value).replace(/[`*_\\[\\]()~>#+=|{}\\\\]/g, '') }}.\n\nHandles are case sensitive and must be the exact name from the channel page, not the display name.",
        "chatId": "={{ $('Set Channel Lookup Details').first().json.chat_id }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "36ec89a5-52e7-4149-aac7-ff260280cdb6",
      "name": "Prepare Channel Data",
      "type": "n8n-nodes-base.set",
      "position": [
        1664,
        352
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "c1",
              "name": "channel_id",
              "type": "string",
              "value": "={{ $json.items[0].id }}"
            },
            {
              "id": "c2",
              "name": "channel_title",
              "type": "string",
              "value": "={{ $json.items[0].snippet.title }}"
            },
            {
              "id": "c3",
              "name": "subs",
              "type": "number",
              "value": "={{ Number($json.items[0].statistics.subscriberCount || 0) }}"
            },
            {
              "id": "c4",
              "name": "total_videos",
              "type": "number",
              "value": "={{ Number($json.items[0].statistics.videoCount || 0) }}"
            },
            {
              "id": "c5",
              "name": "uploads_playlist",
              "type": "string",
              "value": "={{ $json.items[0].contentDetails.relatedPlaylists.uploads }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "01285233-8caf-40ba-89e8-aa5401d8b5bb",
      "name": "Fetch Last 20 Uploads",
      "type": "n8n-nodes-base.httpRequest",
      "notes": "1 quota unit. search.list would be 100 and lags behind new uploads.",
      "position": [
        1888,
        352
      ],
      "parameters": {
        "url": "https://www.googleapis.com/youtube/v3/playlistItems",
        "options": {},
        "sendQuery": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "queryParameters": {
          "parameters": [
            {
              "name": "part",
              "value": "contentDetails"
            },
            {
              "name": "playlistId",
              "value": "={{ $json.uploads_playlist }}"
            },
            {
              "name": "maxResults",
              "value": "20"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "03d86009-5595-4be9-b272-413011e98a5b",
      "name": "Split Uploads",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        2112,
        352
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "items"
      },
      "typeVersion": 1
    },
    {
      "id": "71b93f1a-ee41-4f9c-b614-b99a03500d8f",
      "name": "Aggregate Video IDs",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        2336,
        352
      ],
      "parameters": {
        "options": {},
        "fieldsToAggregate": {
          "fieldToAggregate": [
            {
              "renameField": true,
              "outputFieldName": "ids",
              "fieldToAggregate": "contentDetails.videoId"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "15cdeef4-4cdd-46fc-b34b-0028bdc9e162",
      "name": "Fetch Video Statistics",
      "type": "n8n-nodes-base.httpRequest",
      "notes": "Up to 50 video IDs in one call. 1 quota unit instead of 20.",
      "position": [
        2560,
        352
      ],
      "parameters": {
        "url": "https://www.googleapis.com/youtube/v3/videos",
        "options": {},
        "sendQuery": true,
        "authentication": "genericCredentialType",
        "genericAuthType": "httpQueryAuth",
        "queryParameters": {
          "parameters": [
            {
              "name": "part",
              "value": "snippet,contentDetails,statistics"
            },
            {
              "name": "id",
              "value": "={{ $json.ids.join(',') }}"
            }
          ]
        }
      },
      "typeVersion": 4.2
    },
    {
      "id": "95a75025-2797-49b7-8cb7-8a2e62741f06",
      "name": "Split Video Statistics",
      "type": "n8n-nodes-base.splitOut",
      "position": [
        2784,
        352
      ],
      "parameters": {
        "options": {},
        "fieldToSplitOut": "items"
      },
      "typeVersion": 1
    },
    {
      "id": "240f24b1-7097-4588-9761-69d7f5fb18e7",
      "name": "Prepare Video Metrics",
      "type": "n8n-nodes-base.set",
      "position": [
        3008,
        352
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "v1",
              "name": "video_id",
              "type": "string",
              "value": "={{ $json.id }}"
            },
            {
              "id": "v2",
              "name": "title",
              "type": "string",
              "value": "={{ $json.snippet.title }}"
            },
            {
              "id": "v3",
              "name": "published_at",
              "type": "string",
              "value": "={{ $json.snippet.publishedAt }}"
            },
            {
              "id": "v4",
              "name": "views",
              "type": "number",
              "value": "={{ Number($json.statistics.viewCount || 0) }}"
            },
            {
              "id": "v5",
              "name": "comments",
              "type": "number",
              "value": "={{ Number($json.statistics.commentCount || 0) }}"
            },
            {
              "id": "v6",
              "name": "age_hours",
              "type": "number",
              "value": "={{ Math.max(1, Math.round($now.diff(DateTime.fromISO($json.snippet.publishedAt), 'hours').hours)) }}"
            },
            {
              "id": "v7",
              "name": "vph",
              "type": "number",
              "value": "={{ Math.round(Number($json.statistics.viewCount || 0) / Math.max(1, $now.diff(DateTime.fromISO($json.snippet.publishedAt), 'hours').hours) * 10) / 10 }}"
            },
            {
              "id": "v8",
              "name": "duration_sec",
              "type": "number",
              "value": "={{ (function(d){ var m = String(d || '').match(/PT(?:(\\d+)H)?(?:(\\d+)M)?(?:(\\d+)S)?/); if (!m) return 0; return (Number(m[1]||0)*3600)+(Number(m[2]||0)*60)+Number(m[3]||0); })($json.contentDetails ? $json.contentDetails.duration : '') }}"
            },
            {
              "id": "v9",
              "name": "chapter_count",
              "type": "number",
              "value": "={{ (String($json.snippet.description || '').match(/(^|\\n)\\s*\\d{1,2}:\\d{2}(:\\d{2})?[\\s\\-\u2013\u2014\\)\\].]+\\S/g) || []).length }}"
            },
            {
              "id": "v10",
              "name": "likes",
              "type": "number",
              "value": "={{ Number($json.statistics.likeCount || 0) }}"
            },
            {
              "id": "v11",
              "name": "title_len",
              "type": "number",
              "value": "={{ String($json.snippet.title || '').length }}"
            },
            {
              "id": "v12",
              "name": "engagement_per_1k",
              "type": "number",
              "value": "={{ Number($json.statistics.viewCount || 0) > 0 ? Math.round((Number($json.statistics.commentCount || 0) + Number($json.statistics.likeCount || 0)) / Number($json.statistics.viewCount) * 1000 * 10) / 10 : 0 }}"
            }
          ]
        }
      },
      "typeVersion": 3.4
    },
    {
      "id": "fa2c5a9a-acd7-489d-912e-79270f52f5b2",
      "name": "Sort by Viewer Velocity",
      "type": "n8n-nodes-base.sort",
      "position": [
        3232,
        352
      ],
      "parameters": {
        "options": {},
        "sortFieldsUi": {
          "sortField": [
            {
              "order": "descending",
              "fieldName": "vph"
            }
          ]
        }
      },
      "typeVersion": 1
    },
    {
      "id": "2403ad9b-7317-4c44-8d65-ac9b8295ecf6",
      "name": "Aggregate Video Data",
      "type": "n8n-nodes-base.aggregate",
      "position": [
        3456,
        352
      ],
      "parameters": {
        "options": {},
        "aggregate": "aggregateAllItemData",
        "destinationFieldName": "videos"
      },
      "typeVersion": 1
    },
    {
      "id": "2fdb513c-6dbd-480e-9262-0abebafdd740",
      "name": "Set Velocity Baseline",
      "type": "n8n-nodes-base.set",
      "notes": "Median, not mean. Also flags the noise floor: under 200 median views a '2x breakout' is a handful of people, not a pattern.",
      "position": [
        3680,
        352
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "b1",
              "name": "baseline_vph",
              "type": "number",
              "value": "={{ (function(a){ var s = a.filter(function(v){ return v.age_hours >= 48; }).map(function(v){ return v.vph; }).sort(function(x,y){ return x - y; }); if (!s.length) return 0; var m = Math.floor(s.length / 2); var med = s.length % 2 ? s[m] : (s[m-1] + s[m]) / 2; return med < 10 ? Math.round(med * 1000) / 1000 : Math.round(med * 10) / 10; })($json.videos) }}"
            },
            {
              "id": "b2",
              "name": "sample_size",
              "type": "number",
              "value": "={{ $json.videos.filter(function(v){ return v.age_hours >= 48; }).length }}"
            },
            {
              "id": "b3",
              "name": "median_duration_min",
              "type": "number",
              "value": "={{ (function(a){ if (!a.length) return 0; var s = a.map(function(v){ return v.duration_sec; }).sort(function(x,y){ return x - y; }); var m = Math.floor(s.length / 2); return Math.round((s.length % 2 ? s[m] : (s[m-1] + s[m]) / 2) / 6) / 10; })($json.videos) }}"
            },
            {
              "id": "b4",
              "name": "pct_with_chapters",
              "type": "number",
              "value": "={{ $json.videos.length ? Math.round($json.videos.filter(function(v){ return v.chapter_count >= 3; }).length / $json.videos.length * 100) : 0 }}"
            },
            {
              "id": "b5",
              "name": "baseline_views_per_day",
              "type": "number",
              "value": "={{ (function(a){ var s = a.filter(function(v){ return v.age_hours >= 48; }).map(function(v){ return v.vph; }).sort(function(x,y){ return x - y; }); if (!s.length) return 0; var m = Math.floor(s.length / 2); return Math.round((s.length % 2 ? s[m] : (s[m-1] + s[m]) / 2) * 24); })($json.videos) }}"
            },
            {
              "id": "b6",
              "name": "median_views",
              "type": "number",
              "value": "={{ (function(a){ var s = a.filter(function(v){ return v.age_hours >= 48; }).map(function(v){ return v.views; }).sort(function(x,y){ return x - y; }); if (!s.length) return 0; var m = Math.floor(s.length / 2); return Math.round(s.length % 2 ? s[m] : (s[m-1] + s[m]) / 2); })($json.videos) }}"
            },
            {
              "id": "b7",
              "name": "noise_floor_hit",
              "type": "boolean",
              "value": "={{ (function(a){ var s = a.filter(function(v){ return v.age_hours >= 48; }).map(function(v){ return v.views; }).sort(function(x,y){ return x - y; }); if (!s.length) return true; var m = Math.floor(s.length / 2); return (s.length % 2 ? s[m] : (s[m-1] + s[m]) / 2) < 200; })($json.videos) }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    },
    {
      "id": "08eac050-2ad5-448b-b623-8c311a788f45",
      "name": "If Sufficient Sample Size",
      "type": "n8n-nodes-base.if",
      "notes": "Under 5 videos older than 48h there is no baseline worth computing.",
      "position": [
        4128,
        352
      ],
      "parameters": {
        "options": {},
        "conditions": {
          "options": {
            "version": 2,
            "leftValue": "",
            "caseSensitive": true,
            "typeValidation": "loose"
          },
          "combinator": "and",
          "conditions": [
            {
              "id": "floor",
              "operator": {
                "type": "number",
                "operation": "gte"
              },
              "leftValue": "={{ $json.sample_size }}",
              "rightValue": 5
            }
          ]
        },
        "looseTypeValidation": true
      },
      "typeVersion": 2.2
    },
    {
      "id": "3b5caa15-7c87-41ea-906d-d24f00d0b125",
      "name": "Notify No Baseline Found",
      "type": "n8n-nodes-base.telegram",
      "position": [
        4352,
        448
      ],
      "parameters": {
        "text": "={{ String($('Prepare Channel Data').first().json.channel_title).replace(/[`*_\\[\\]()~>#+=|{}\\\\]/g, '') }} only has {{ $json.sample_size }} videos older than 48 hours.\n\nThat is not enough to build a velocity baseline, so I am not going to guess at a pattern.",
        "chatId": "={{ $('Set Channel Lookup Details').first().json.chat_id }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "5c2c5de5-b0f6-4d2e-b384-5c85515b124f",
      "name": "Append to Google Sheets",
      "type": "n8n-nodes-base.googleSheets",
      "notes": "Tab 'Channels'. Headers: run_date | channel | subs | baseline_vph | baseline_views_per_day | median_views | noise_floor_hit | sample_size | median_duration_min | pct_with_chapters | top_video | top_vph",
      "onError": "continueRegularOutput",
      "position": [
        4352,
        256
      ],
      "parameters": {
        "columns": {
          "value": {},
          "schema": [],
          "mappingMode": "defineBelow",
          "matchingColumns": [],
          "attemptToConvertTypes": false,
          "convertFieldsToString": false
        },
        "options": {},
        "operation": "append",
        "sheetName": {
          "__rl": true,
          "mode": "list",
          "value": "<REPLACE_WITH_YOUR_SHEET_TAB_ID>",
          "cachedResultUrl": "<REPLACE_WITH_YOUR_SHEET_TAB_URL>",
          "cachedResultName": "youtube comments "
        },
        "documentId": {
          "__rl": true,
          "mode": "list",
          "value": "<REPLACE_WITH_YOUR_GOOGLE_SHEET_ID>",
          "cachedResultUrl": "<REPLACE_WITH_YOUR_GOOGLE_SHEET_URL>",
          "cachedResultName": "triage log"
        },
        "authentication": "serviceAccount"
      },
      "typeVersion": 4.5
    },
    {
      "id": "5aef7b9f-92e8-4a78-9b99-f4739d9aa0df",
      "name": "Gemini Channel Analysis",
      "type": "@n8n/n8n-nodes-langchain.chainLlm",
      "position": [
        4576,
        256
      ],
      "parameters": {
        "text": "=You are a YouTube channel analyst. You work only from the numbers below. You never claim to know retention, watch time, CTR or impressions \u2014 that data does not exist here.\n\nCHANNEL\nName: {{ $('Prepare Channel Data').first().json.channel_title }}\nSubscribers: {{ $('Prepare Channel Data').first().json.subs }}\nTotal videos on channel: {{ $('Prepare Channel Data').first().json.total_videos }}\n\nSCALE\nMedian views per video: {{ $json.median_views }}\nBaseline views/hour: {{ $json.baseline_vph }}  (= {{ $json.baseline_views_per_day }} views/day)\nVideos in baseline: {{ $json.sample_size }}\nNOISE FLOOR HIT: {{ $json.noise_floor_hit }}\n\nFINGERPRINT\n{{ JSON.stringify($json.fp) }}\n\nALL 20 UPLOADS\n{{ JSON.stringify($json.videos.map(function(v){ return {title: v.title, views: v.views, age_h: v.age_hours, mins: Math.round(v.duration_sec/60*10)/10, chapters: v.chapter_count, eng_per_1k: v.engagement_per_1k}; })) }}\n\nWrite a Telegram report in plain text under 320 words. No markdown, no preamble, no sign-off.\n\nUse exactly these five headed sections, each heading on its own line:\n\nCADENCE\nMedian days between uploads, the range, and days since the last upload. Say whether the schedule is consistent or erratic, and back it with the range.\n\nFORMAT\nShort (under 5 min) vs long (5 min+): the count and median views of each. Same for videos with 3+ chapters vs without. State which wins and by how much, or state that the split shows no difference. Give median title length.\n\nTITLES\nThe percentage using first person, a number, and a tool name. Name the single best and worst performing video with their view counts and the spread between them. Say what the best-performing titles share in wording that the others do not.\n\nTREND\nOlder half median views vs newer half median views. Say whether the channel is growing, flat, or declining, with both numbers.\n\nDO THIS NEXT\nExactly three concrete actions, one line each, each tied to a number you cited above. No generic advice like \"post consistently\" or \"improve thumbnails\" unless a number in the data supports it.\n\nARITHMETIC RULES, these override everything:\n- Use the numbers given. Never recompute a median. Never state a figure that is not derived from the data above.\n- Every claim carries its number. \"Long videos win\" is banned; \"long videos: 11 uploads, median 34 views vs short: 4 uploads, median 12\" is required.\n- If NOISE FLOOR HIT is true, add one line at the very top: the median is only {{ $json.median_views }} views per video, so differences between videos are noise and nothing below should be read as proof of cause. Then still complete all five sections \u2014 structure, cadence and titles are readable at any scale.\n- If a comparison group has fewer than 3 videos, say the group is too small instead of comparing it.",
        "promptType": "define"
      },
      "typeVersion": 1.5
    },
    {
      "id": "2a3ddffa-614d-4d5d-9593-0d72ab152e9b",
      "name": "Gemini Model Setup",
      "type": "@n8n/n8n-nodes-langchain.lmChatGoogleGemini",
      "position": [
        4880,
        496
      ],
      "parameters": {
        "options": {
          "temperature": 0.2
        },
        "modelName": "models/gemini-3.1-flash-lite"
      },
      "typeVersion": 1
    },
    {
      "id": "3839d3bb-b82c-4fbf-92f6-bf18ef108492",
      "name": "Send Channel Report",
      "type": "n8n-nodes-base.telegram",
      "position": [
        4928,
        256
      ],
      "parameters": {
        "text": "=\ud83d\udcca {{ String($('Prepare Channel Data').first().json.channel_title).replace(/[`*_\\[\\]()~>#+=|{}\\\\]/g,'') }} \u2014 {{ $('Prepare Channel Data').first().json.subs }} subs\n{{ $('Build Channel Fingerprint').first().json.median_views }} median views \u00b7 every {{ $('Build Channel Fingerprint').first().json.fp.median_days_between_uploads }} days\n\n{{ String($json.text).replace(/[`*_\\[\\]()~>#+=|{}\\\\]/g,'').slice(0, 3800) }}",
        "chatId": "={{ $('Set Channel Lookup Details').first().json.chat_id }}",
        "additionalFields": {
          "appendAttribution": false
        }
      },
      "typeVersion": 1.2
    },
    {
      "id": "b3802a29-6b93-43fd-aba9-cd17874d32f7",
      "name": "Build Channel Fingerprint",
      "type": "n8n-nodes-base.set",
      "notes": "Cadence, engagement ratios, trend, format splits, title patterns. Ratios work at any channel size; multiples do not.",
      "position": [
        3904,
        352
      ],
      "parameters": {
        "options": {},
        "assignments": {
          "assignments": [
            {
              "id": "f1",
              "name": "fp",
              "type": "object",
              "value": "={{ (function(vs, subs){   function med(a){ if(!a.length) return 0; var s=a.slice().sort(function(x,y){return x-y;}); var m=Math.floor(s.length/2); return s.length%2 ? s[m] : (s[m-1]+s[m])/2; }   var byDate = vs.slice().sort(function(a,b){ return new Date(a.published_at) - new Date(b.published_at); });   var gaps = []; for (var i=1;i<byDate.length;i++){ gaps.push((new Date(byDate[i].published_at) - new Date(byDate[i-1].published_at))/86400000); }   var eligible = vs.filter(function(v){ return v.age_hours >= 48; });   var half = Math.floor(byDate.length/2), older = byDate.slice(0,half), newer = byDate.slice(half);   var shortV = eligible.filter(function(v){ return v.duration_sec < 300; });   var longV = eligible.filter(function(v){ return v.duration_sec >= 300; });   var withCh = eligible.filter(function(v){ return v.chapter_count >= 3; });   var noCh = eligible.filter(function(v){ return v.chapter_count < 3; });   var titles = vs.map(function(v){ return v.title; });   var best = eligible.slice().sort(function(a,b){ return b.views-a.views; })[0] || {};   var worst = eligible.slice().sort(function(a,b){ return a.views-b.views; })[0] || {};   return {     days_since_last_upload: byDate.length ? Math.round((Date.now()-new Date(byDate[byDate.length-1].published_at))/86400000) : 0,     median_days_between_uploads: Math.round(med(gaps)*10)/10,     cadence_range: gaps.length ? (Math.round(Math.min.apply(null,gaps)*10)/10)+' to '+(Math.round(Math.max.apply(null,gaps)*10)/10)+' days' : 'n/a',     median_engagement_per_1k: med(eligible.map(function(v){ return v.engagement_per_1k; })),     median_views_per_100_subs: subs ? Math.round(med(eligible.map(function(v){ return v.views; }))/subs*1000)/10 : 0,     newer_half_median_views: Math.round(med(newer.map(function(v){ return v.views; }))),     older_half_median_views: Math.round(med(older.map(function(v){ return v.views; }))),     short_under5min: { n: shortV.length, median_views: Math.round(med(shortV.map(function(v){ return v.views; }))) },     long_over5min: { n: longV.length, median_views: Math.round(med(longV.map(function(v){ return v.views; }))) },     with_chapters: { n: withCh.length, median_views: Math.round(med(withCh.map(function(v){ return v.views; }))) },     without_chapters: { n: noCh.length, median_views: Math.round(med(noCh.map(function(v){ return v.views; }))) },     median_title_len: Math.round(med(vs.map(function(v){ return v.title_len; }))),     pct_titles_first_person: titles.length ? Math.round(titles.filter(function(t){ return /\\b(I|My|Me)\\b/.test(t); }).length/titles.length*100) : 0,     pct_titles_with_number: titles.length ? Math.round(titles.filter(function(t){ return /\\d/.test(t); }).length/titles.length*100) : 0,     pct_titles_naming_tool: titles.length ? Math.round(titles.filter(function(t){ return /n8n|AI|GPT|Gemini|Claude|Python|API|Automat/i.test(t); }).length/titles.length*100) : 0,     best: { title: best.title || '', views: best.views || 0 },     worst: { title: worst.title || '', views: worst.views || 0 },     spread_ratio: (worst.views && best.views) ? Math.round(best.views/worst.views*10)/10 : 0   }; })($json.videos, $('Prepare Channel Data').first().json.subs) }}"
            }
          ]
        },
        "includeOtherFields": true
      },
      "typeVersion": 3.4
    }
  ],
  "connections": {
    "Split Uploads": {
      "main": [
        [
          {
            "node": "Aggregate Video IDs",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If Channel Exists": {
      "main": [
        [
          {
            "node": "Prepare Channel Data",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Notify Channel Not Found",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini Model Setup": {
      "ai_languageModel": [
        [
          {
            "node": "Gemini Channel Analysis",
            "type": "ai_languageModel",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate Video IDs": {
      "main": [
        [
          {
            "node": "Fetch Video Statistics",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Aggregate Video Data": {
      "main": [
        [
          {
            "node": "Set Velocity Baseline",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Channel Data": {
      "main": [
        [
          {
            "node": "Fetch Last 20 Uploads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Last 20 Uploads": {
      "main": [
        [
          {
            "node": "Split Uploads",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If Valid Channel Link": {
      "main": [
        [
          {
            "node": "Fetch YouTube Channel Info",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Notify Bad Channel Link",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Video Metrics": {
      "main": [
        [
          {
            "node": "Sort by Viewer Velocity",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Velocity Baseline": {
      "main": [
        [
          {
            "node": "Build Channel Fingerprint",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch Video Statistics": {
      "main": [
        [
          {
            "node": "Split Video Statistics",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Split Video Statistics": {
      "main": [
        [
          {
            "node": "Prepare Video Metrics",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Append to Google Sheets": {
      "main": [
        [
          {
            "node": "Gemini Channel Analysis",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Gemini Channel Analysis": {
      "main": [
        [
          {
            "node": "Send Channel Report",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Sort by Viewer Velocity": {
      "main": [
        [
          {
            "node": "Aggregate Video Data",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Channel Fingerprint": {
      "main": [
        [
          {
            "node": "If Sufficient Sample Size",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "If Sufficient Sample Size": {
      "main": [
        [
          {
            "node": "Append to Google Sheets",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Notify No Baseline Found",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Fetch YouTube Channel Info": {
      "main": [
        [
          {
            "node": "If Channel Exists",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Handle Telegram API Error",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Set Channel Lookup Details": {
      "main": [
        [
          {
            "node": "If Valid Channel Link",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "When Telegram Message Received": {
      "main": [
        [
          {
            "node": "Set Channel Lookup Details",
            "type": "main",
            "index": 0
          }
        ]
      ]
    }
  },
  "meta": {
    "instanceId": null
  },
  "settings": {
    "binaryMode": "separate",
    "availableInMCP": false,
    "executionOrder": "v1"
  }
}