Automated Social Media Publishing with n8n and AI Agents

This workflow automates tailored social media content creation and publishing across multiple platforms using n8n’s Langchain AI nodes and integration with Google Docs, image generation, and platform APIs. It streamlines content creation, approval, and multi-channel distribution to save time and ensure consistency.
chatTrigger
agent
googleDrive
+16
Learn how to Build this Workflow with AI:
Workflow Identifier: 1001
NODES in Use: chatTrigger, stickyNote, toolWorkflow, code, googleDocs, agent, httpRequest, googleDrive, gmail, facebookGraphApi, twitter, linkedIn, telegram, switch, set, extractFromFile, if, merge, noOp

Press CTRL+F5 if the workflow didn't load.

Visit through Desktop for Best experience

Opening Problem Statement

Meet Sarah, a digital marketing specialist managing multiple social media accounts across platforms like Twitter (X), Instagram, Facebook, LinkedIn, Threads, and YouTube Shorts. Every day, she spends hours crafting unique posts tailored to each platform’s nuances and audience preferences. Sarah struggles with maintaining a consistent brand voice, keeping up with trending topics, ensuring image content aligns with post themes, and managing approval workflows with her team. The sheer volume and complexity lead to delays, errors, and lost engagement opportunities.

What if Sarah could automate this entire content creation and publication process, leveraging the power of AI to generate platform-optimized posts and images, automatically route content for approval, and publish seamlessly? This is exactly the real-world challenge solved by our advanced n8n workflow that integrates AI content generation, dynamic prompt management, multi-platform publishing, and cloud image storage.

What This Automation Does

When activated, this sophisticated workflow transforms a simple user prompt into fully formed social media posts crafted for each platform with matched images. Here’s what happens:

  • Generates platform-specific social media content using Langchain AI agents based on system prompts and schemas stored externally in Google Docs.
  • Automatically creates matching post images through integration with an AI image generation API (Pollinations.ai) and stores them safely on Google Drive and imgbb.com.
  • Routes content through an email approval process managed via Gmail, waiting for user confirmation before proceeding.
  • Publishes approved posts directly to their respective social platforms using native API nodes (Twitter, Instagram, Facebook, LinkedIn) embedded within n8n.
  • Archives all posts and images on Google Drive for record-keeping and future reuse.
  • Sends optional Telegram notifications to keep the team updated on workflow status and errors.

Benefits include hours saved in content creation, error reduction by validating JSON schemas for each platform, brand consistency through controlled system prompts, and a single place for team collaboration on prompt and schema management.

Prerequisites ⚙️

  • n8n account (cloud or self-hosted) configured to run complex workflows.
  • OpenAI account for Langchain AI nodes to generate platform-specific content.
  • Google Docs account with documents set up for system prompts and social media schemas.
  • Google Drive account for storing generated images and post archives.
  • Pollinations.ai (or alternative AI image generation service) API access for creating post images.
  • API credentials for social media platforms: Twitter (X), Instagram, Facebook (Facebook Graph API), LinkedIn.
  • Gmail account with OAuth2 for sending approval emails.
  • Telegram account (optional) for notifications.

Step-by-Step Guide

Step 1: Trigger on Incoming Chat Message

Navigate to the “When chat message received” Langchain Chat Trigger node. This node listens for incoming inputs (prompts) that will initiate the content creation process. This could be linked to a chatbot or internal command system.

Expected outcome: When you send a prompt through the chat, the workflow activates and begins processing.

Common mistake: Not properly connecting input sources or misconfiguring the webhook ID, resulting in the trigger not firing.

Step 2: Fetch External System Prompts and Social Media Schemas

Two Google Docs nodes named “Social Media System Prompt” and “Social Media Schema” retrieve the system prompt text and JSON schema documents respectively. You must set the Google Docs document URLs or IDs in these nodes.

Expected outcome: Pull consistent, externally managed prompts and schemas that define how content should be crafted and validated for each social network.

Common mistake: Not updating the document URLs, leading to content fetching errors or outdated schema usage.

Step 3: Parse the Retrieved Prompts and Schemas

Two Code nodes — Parse System Prompt and Parse Schema — parse XML-like content from Google Docs into usable JSON objects. They extract the common, root, and platform-specific schema and prompt components.

JS snippet example for Parse Schema node:

// Extract content between XML tags
function extractFromXmlTags(xmlString, tagName) {
  const regex = new RegExp(<${tagName}>(.*?), 'gs');
  const match = regex.exec(xmlString);
  return match ? match[1].trim() : null;
}

const platform = inputData.platform;
const extractedContent = extractFromXmlTags(xmlString, platform);
const rootContent = extractFromXmlTags(xmlString, 'root');
const commonContent = extractFromXmlTags(xmlString, 'common');

jsonData = JSON.parse(extractedContent);
rootSchema = JSON.parse(rootContent);
commonSchema = JSON.parse(commonContent);

Expected outcome: Structured JSON schemas and prompt components ready for use in subsequent AI calls.

Common mistake: Malformed or improperly formatted external docs cause JSON parsing errors.

Step 4: Merge and Compose AI Prompt

The Merge Prompts and Schema node combines these components and passes them into the Compose Prompt & Schema node that sets required variables for the AI agent including route (platform), user prompt, system messages, and schemas.

Expected outcome: A fully prepared prompt and configuration ready to drive the AI content generation.

Step 5: Generate Platform-Specific Social Media Content

The Social Media Content Creator Langchain Agent node uses the composed prompt and schemas to instruct the OpenAI LLM to generate content for the desired platform formatting specifically.

Expected outcome: AI-written, platform-optimized JSON-content for posts matching schema requirements.

Common mistake: Failing to verify schema or invalid platform tags causing generation errors.

Step 6: Generate Matching Social Media Image

The pollinations.ai1 HTTP Request node uses the AI output’s image suggestion to generate a corresponding image. On success, the image file is saved using Save Image to imgbb.com and Save Image to Google Drive nodes for redundancy and archival.

Expected outcome: Visually consistent images saved and linked for post publication.

Common mistake: Incorrect image API endpoint or missing API keys.

Step 7: Merge Content and Image Data for Publishing

The workflow merges generated content JSON and image metadata using Merge and Merge Image and Post Contents nodes, preparing a single payload for social media platform API calls.

Step 8: Route Content to Proper Publishing Node

The Social Media Publishing Router Switch node directs the payload to the correct social media platform node: Twitter (X Post), Instagram (Instagram Image), Facebook (Facebook Post), LinkedIn (LinkedIn Post), Threads, or YouTube Shorts (placeholders).

Each platform’s native node then posts the content using stored OAuth credentials.

Expected outcome: Posts published simultaneously or sequentially to all desired social networks.

Step 9: Email Approval Process

Before publishing, the workflow triggers a Gmail User for Approval node that sends a formatted HTML email allowing recipients to approve or reject content.

The Is Approved? If node checks the response and proceeds if approved.

Step 10: Archive Content and Notify Team

After approval and publishing, posts and images are saved to Google Drive again for archival. Optional Telegram notifications inform the team on the workflow status success or failure.

Customizations ✏️

  • Add New Social Platform Support: Duplicate the existing setup (toolWorkflow nodes, publishing nodes, router rules) to add TikTok or Pinterest posts, updating prompt schemas accordingly.
  • Change Image Generation Service: Replace Pollinations.ai with another image API by updating the HTTP Request node URL and payload format.
  • Adjust Approval Workflow: Modify the Gmail User for Approval node to include additional approvers or change the waiting time in the limitWaitTime option.
  • Customize System Prompts: Edit Google Docs content for the system prompt to align with your brand’s voice and add new rules for content style.
  • Modify Hashtag Sets: Update the JSON schema in the Social Media Schema Google Doc to include more or different hashtags based on trending topics.

Troubleshooting 🔧

  • Problem: “Trigger not firing on chat input”

    Cause: Incorrect webhook ID or missing trigger setup in the Langchain Chat Trigger node.

    Solution: Verify webhook configuration and test with the raw webhook URL.
  • Problem: “JSON parsing errors in Parse Schema node”

    Cause: Malformed or inconsistent external schema documents.

    Solution: Validate external Google Docs JSON content format and structure, use JSON lint tools.
  • Problem: “Image generation API failures”

    Cause: Invalid API key or unstable API endpoint.

    Solution: Check and reconfigure API keys, test with alternative image generation services.
  • Problem: “Content not publishing to social media”

    Cause: OAuth token expiration or improper permissions.

    Solution: Renew credentials, check API scopes, and inspect node error output for specifics.

Pre-Production Checklist ✅

  • Confirm Google Docs IDs and permissions for System Prompt and Social Media Schema nodes.
  • Test AI model API keys and account limits (OpenAI, Pollinations.ai).
  • Verify OAuth connections and permissions for all social media platform nodes.
  • Run end-to-end tests with sample chat triggers to ensure full workflow execution.
  • Check email deliverability and approval process timing.
  • Backup all prompt and schema Google Docs content externally.

Deployment Guide

Enable the workflow in your n8n instance and start by sending a test prompt through your chat trigger. Monitor execution logs directly in n8n to verify successful AI content creation, image generation, approval emailing, and social media publishing.

Set up Telegram notifications to be informed of errors or successful completion in real time.

Regularly update your external prompt and schema documents to adapt to platform changes and content strategy updates without redeploying the workflow code.

FAQs

Can I use other AI models instead of OpenAI GPT-4o-mini?

Yes, the Langchain AI nodes in n8n support multiple models. You can replace or add models like GPT-3.5-turbo or other providers by updating the AI nodes credentials and model parameters.

Does this workflow consume a lot of API credits?

It depends on your usage volume, especially the frequency of prompt generation and image requests. Monitor your OpenAI and image generation service usage to estimate costs.

Is my data secure in this process?

Yes, n8n handles data securely and OAuth credentials are encrypted. Data stays within your configured environment and authorized APIs.

Can this scale to large social media teams?

Absolutely, the modular design with external prompt and schema management enables collaboration and scalability for marketing teams managing multiple brands or platforms.

Conclusion

By implementing this advanced n8n workflow, you have streamlined the entire social media content creation and publishing cycle. From receiving a user prompt through chat, generating platform-optimized posts and images, routing for approval, to publishing across multiple social networks and archiving content — all done automatically.

This automation saves marketing teams countless hours, reduces errors, and ensures consistent, timely, and engaging posts tailored to each audience. Next, consider extending this workflow with advanced analytics integrations, social media listening for trend detection, or automated content repurposing across campaigns.

Excited to try this out? Let’s start automating your social presence today with n8n and AI-powered creativity!

Related Workflows

Automate Viral UGC Video Creation Using n8n + Degaus (Beginner-Friendly Guide)

Learn how to automate viral UGC video creation using n8n, AI prompts, and Degaus. This beginner-friendly guide shows how to import, configure, and run the workflow without technical complexity.
Form Trigger
Google Sheets
Gmail
+37
Free

AI SEO Blog Writer Automation in n8n (Beginner Guide)

A complete beginner guide to building an AI-powered SEO blog writer automation using n8n.
AI Agent
Google Sheets
httpRequest
+5
Free

Automate CrowdStrike Alerts with VirusTotal, Jira & Slack

This workflow automates processing of CrowdStrike detections by enriching threat data via VirusTotal, creating Jira tickets for incident tracking, and notifying teams on Slack for quick response. Save hours daily by transforming complex threat data into actionable alerts effortlessly.
scheduleTrigger
httpRequest
jira
+5
Free

Automate Telegram Invoices to Notion with AI Summaries & Reports

Save hours on financial tracking by automating invoice extraction from Telegram photos to Notion using Google Gemini AI. This workflow extracts data, records transactions, and generates detailed spending reports with charts sent on schedule via Telegram.
lmChatGoogleGemini
telegramTrigger
notion
+9
Free

Automate Email Replies with n8n and AI-Powered Summarization

Save hours managing your inbox with this n8n workflow that uses IMAP email triggers, AI summarization, and vector search to draft concise replies requiring minimal review. Automate business email processing efficiently with AI guidance and Gmail integration.
emailReadImap
vectorStoreQdrant
emailSend
+12
Free

Automate Email Campaigns Using n8n with Gmail & Google Sheets

This n8n workflow automates personalized email outreach campaigns by integrating Gmail and Google Sheets, saving hours of manual follow-up work and reducing errors in email sequences. It ensures timely follow-ups based on previous email interactions, optimizing communication efficiency.
googleSheets
gmail
code
+5
Free