n8n tutorial - Lesson 14: Auto-Reply YouTube Comments with n8n AI
Hi everyone, in this post we're building a full AI-powered YouTube comment automation system using n8n — covering comment classification, AI draft replies, and an automated reply sender. This is part of our n8n Workflow Automation Tutorial series and is one of the most practical n8n youtube automation pipelines you can build for a real channel.
How to do:
Step 1 — Create the Google Sheet Queue
Before any workflow runs, you need a structured sheet to store every comment and its processing status.- Create a new Google Sheet named T5-Comments-Queue with Sheet ID saved for later reference.
- Add one tab called Queue with exactly 9 column headers in this order:
comment_idvideo_idvideo_titleauthorcomment_textcategorydraft_replystatuscreated_at
- Format column A (
comment_id) as Plain Text to prevent Google Sheets from auto-converting YouTube comment IDs into numbers or dates.
Note — The Plain Text format on column A is critical. YouTube comment IDs are long strings and Sheets will silently corrupt them if left as auto format, breaking your idempotent deduplication later.
Step 2 — Set Up the YouTube OAuth2 Credential with the Correct Scope
The default YouTube scope is not enough for reading comment threads or posting replies — you must upgrade it.- In n8n, open your existing YouTube OAuth2 (HTTP) credential (generic OAuth2 type, not the service-specific one).
- Change the scope from
youtubetoyoutube.force-ssl. - Re-authorize the credential so the new scope takes effect.
Production tip — The youtube.force-ssl scope covers both /commentThreads/list (read) and /comments/insert (write). You will not need to change the credential again for either operation.
Step 3 — Build the Comment Pipeline Workflow (Workflow 1)
This is the main n8n workflow automation pipeline — 13 nodes that fetch, classify, draft, deduplicate, and log every comment.- Create a new workflow named T5-B2-Comment-Pipeline.
- Add a Schedule Trigger node set to run every
30minutes. - Add a Google Sheets node named Get Existing IDs:
- Operation: Get Many, range
A:Aof the Queue tab. - This fetches all existing
comment_idvalues for deduplication.
- Operation: Get Many, range
- Add a Code node named Aggregate IDs:
- Set Mode to Run Once for All Items.
- Output a single item:
{ existing_ids: [ ...all comment_id values ] }. - This collapses all rows into one item so downstream nodes only run once.
- Add an HTTP Request node named Get Latest Videos:
- Method:
GET, URL:https://www.googleapis.com/youtube/v3/search. - Add Query Parameters exactly as the YouTube API docs specify:
part=id,snippetchannelId= your channel IDorder=datemaxResults=10type=video
- Attach the YouTube OAuth2 (HTTP) credential.
- Method:
- Add a Split Out node named Split Videos, field:
items.- The HTTP node returns one n8n item wrapping the whole API response. Split Out unpacks it into one item per video.
- Add an HTTP Request node named Get Video Comments:
- Method:
GET, URL:https://www.googleapis.com/youtube/v3/commentThreads. - Query Parameters:
part=snippetvideoId={{ $json.id.videoId }}order=timetextFormat=plainTextmaxResults=20
- Method:
- Add a second Split Out node named Split Comments, field:
items.- Every HTTP list endpoint wraps results — always add a Split Out after each one.
Note — This is the most common mistake in n8n youtube automation pipelines: forgetting that each HTTP list endpoint returns one wrapped item, not many. Two HTTP list calls = two Split Out nodes. Add them by default whenever you design a pipeline with list endpoints.
Step 4 — Flatten Comments with a Code Node (Cross-Node Lookup)
You need to enrich each comment with its video title, but video title lives in a different node's output — use a Code node with a lookup map, not a.find() expression.
- Add a Code node named Flatten Comments after Split Comments.
- Inside the code, build a title lookup map from the Split Videos output:
const allVideos = $('Split Videos').all();const titleMap = {};- Loop through
allVideosand populate:titleMap[video.json.id.videoId] = video.json.snippet.title;
- For each input item, output a flat object with exactly 5 fields:
comment_id— from$json.snippet.topLevelComment.idvideo_id— from$json.snippet.videoIdvideo_title— fromtitleMap[video_id]author— from$json.snippet.topLevelComment.snippet.authorDisplayNamecomment_text— from$json.snippet.topLevelComment.snippet.textDisplay
Production tip — Never use $('SomeNode').all().find(...).json.x.y in an Edit Fields expression for cross-node lookups. It returns an object instead of a string and will silently produce wrong output. Always use a Code node with an O(1) map instead.
Step 5 — Classify Each Comment with AI
This is where the n8n tutorial gets interesting — an LLM categorizes every comment into one of four buckets automatically.- Add a Basic LLM Chain node named Classify Comment.
- Connect it to the Claude Haiku model with:
- Temperature:
0(deterministic classification) - Max Tokens:
100
- Temperature:
- Add a Structured Output Parser with schema:
{ "category": "string" }. - Write the classification prompt using an XML structure with four tags:
<task>— instruct the model to classify into exactly one of:khen(praise),hỏi(question),spam,tiêu cực(negative)<categories>— define each category clearly<examples>— include at least 5 few-shot examples covering all 4 categories, including real Vietnamese-style comments<output_format>— specify JSON output only
- Pass the comment text using
{{ $json.comment_text }}in the prompt.
Step 6 — Route by Category and Draft Replies for Questions
A Switch node fans out to four branches, and only the "question" branch triggers a second AI call to write a reply draft.- Add a Switch node named Route by Category with 4 rules, each checking:
{{ $json.output.category }}Equals:- Rule 1:
khen - Rule 2:
hỏi - Rule 3:
spam - Rule 4:
tiêu cực
- Rule 1:
- Enable Fallback Extra Output on the Switch to catch any unmatched categories.
- On the
hỏibranch only, add a second Basic LLM Chain node named Draft Reply:- Model: Claude Haiku, Temperature:
0.7, Max Tokens:300 - No Output Parser — plain text output only.
- Reference the original comment using
{{ $('Flatten Comments').item.json.comment_text }}— necessary because the Classify node drops input fields from its output. - Include 3 few-shot reply examples in the prompt matching the channel's tone.
- Model: Claude Haiku, Temperature:
- After Draft Reply, access the reply text with
{{ $json.text }}.
Step 7 — Build Standardized Row Objects for All Branches
Every branch needs to output the same 9-column shape before merging, so the Sheets append node works cleanly.- After each Switch branch, add an Edit Fields node to build the row:
- Build Row Khen: set
category=khen,draft_reply=(empty),status=logged_khen - Build Row Hỏi: set
category=hỏi,draft_reply={{ $json.text }},status=pending_review - Build Row Spam: set
category=spam,status=logged_spam - Build Row Tiêu Cực: set
category=tiêu cực,status=needs_review
- Build Row Khen: set
- In every Build Row node, include all 9 fields. Pull
comment_id,video_id,video_title,author, andcomment_textfrom the Flatten Comments node using$('Flatten Comments').item.json.fieldName. - Add a Merge node named Merge All Categories configured to accept all 4 branch inputs and pass all items through.
Step 8 — Implement Idempotent Deduplication (3-Step Pattern)
Running on a schedule means this workflow will always re-fetch comments that already exist in the sheet — the idempotent guard prevents duplicate rows.- The Get Existing IDs and Aggregate IDs nodes (built in Step 3) already run at the start of the workflow and produce one item with a complete
existing_idsarray. - After Merge All Categories, add a Code node named Filter Idempotent:
- Reference the aggregated IDs:
const existingIds = new Set($('Aggregate IDs').first().json.existing_ids); - Filter the input:
return items.filter(item => !existingIds.has(item.json.comment_id));
- Reference the aggregated IDs:
- Add a Google Sheets node named Append to Queue:
- Operation: Append, target: Queue tab.
- Enable Auto-Map Input Data to Columns — n8n matches your 9 field names to the 9 column headers automatically.
Production tip — Always use this 3-step idempotent pattern (Get IDs → Aggregate → Filter) for any Schedule-triggered polling workflow. Without it, every execution re-appends every comment and your sheet grows into an unusable mess.
Step 9 — Build the Reply Sender Workflow (Workflow 2)
This second workflow polls the sheet for approved replies and sends them to YouTube automatically — the final piece of this n8n youtube automation system.- Create a second workflow named T5-B3-Reply-Sender with 4 nodes.
- Add a Schedule Trigger set to run every
1hour. - Add a Google Sheets node named Get Approved Rows:
- Operation: Get Many with a filter: column
statusequalsapproved.
- Operation: Get Many with a filter: column
- Add an HTTP Request node named Send Reply:
- Method:
POST, URL:https://www.googleapis.com/youtube/v3/comments - Query Parameter:
part=snippet - Body (JSON):
{ "snippet": { "parentId": "{{ $json.comment_id }}", "textOriginal": "{{ $json.draft_reply }}" } }
- Attach the YouTube OAuth2 (HTTP) credential (scope:
youtube.force-ssl).
- Method:
- Add a Google Sheets node named Mark as Sent:
- Operation: Update Row.
- Column to Match On:
comment_id. - Set
status=sent.
Tip — To test end-to-end before activating, manually change one row's status from pending_review to approved in the sheet, then execute the Reply Sender workflow manually. Verify the reply appears on the YouTube video and the row updates to sent.
Step 10 — Activate Both Workflows
With both workflows tested, activate them to run on their schedules.- Open T5-B2-Comment-Pipeline and toggle Active — it will now run every 30 minutes.
- Open T5-B3-Reply-Sender and toggle Active — it will now run every hour.
- Wait 30 minutes and check the Executions tab on both workflows to confirm Success status.
- Check the Queue sheet to verify new rows are being appended with correct categories and statuses.
Key Lessons from This Session
- Always add a Split Out after every HTTP list endpoint. YouTube API list responses wrap results in one n8n item — two list calls means two Split Out nodes, no exceptions.
- Use a Code node with a lookup map for cross-node data enrichment. The
.find().json.x.yexpression pattern in Edit Fields returns an object, not a string — it silently breaks your pipeline. - Query parameter names come from the API docs, not from n8n. Names like
part,channelId, andmaxResultsare defined by the YouTube API — always check the Parameters section atdevelopers.google.com/youtube/v3/docsbefore configuring an HTTP node. - The idempotent 3-step pattern is mandatory for scheduled polling workflows. Get existing IDs → Aggregate into one item → Filter before append. This makes any schedule-triggered n8n workflow safe to re-run.
- The
youtube.force-sslscope covers both reading and writing. One credential upgrade handles/commentThreads/listreads and/comments/insertwrites — no further changes needed. - The Classify node drops input fields. When referencing original comment data after the LLM Chain, always use
$('Flatten Comments').item.json.fieldName, not$json.fieldName.
Conclusion:
In this n8n tutorial, we built a complete two-workflow n8n youtube automation system: a 13-node comment pipeline that classifies, drafts, and logs YouTube comments by category, and a 4-node reply sender that posts approved replies automatically. The key patterns — Split Out after every list endpoint, Code node lookup maps, and the idempotent 3-step deduplication guard — are reusable across any n8n workflow automation project. The next session covers an auto-SEO pipeline that fetches old videos and uses AI to suggest better titles and descriptions for improved click-through rates.
If you have any questions, feel free to leave a comment below. Thank you!Tags: n8n youtube automation, n8n tutorial, n8n workflow automation, YouTube comment automation, n8n AI workflow, n8n HTTP Request, Claude AI n8n, YouTube API n8n
Maybe you are interested!
- Getting Started with n8n: Interface & Your First Manual Trigger
- n8n HTTP Request Node: Connect Any API Without Code
- Branching Workflows: IF, Switch & Merge Nodes in n8n
- n8n Expressions & Built-in Variables: The Complete Guide
- Comparing AI Models in n8n: Claude vs Gemini vs ChatGPT
- Connect Gmail to n8n: OAuth Setup & Reading Emails
- Build an AI Email Classifier with n8n
- Automated Email Digest to Telegram with n8n
- Google Sheets Automation with n8n: 4 Key Operations
- Auto-Generate Google Docs from Data with n8n



