How to automate social media posts with AI agents using CrewAI and n8n
You can build a completely hands-off pipeline that researches topics, drafts copy, generates images, and schedules posts to Twitter, LinkedIn, Instagram and Facebook - all without lifting a finger. The result is a faceless AI content agent that runs on a schedule, pulls fresh data from an RSS feed, and publishes on multiple platforms automatically. What you need Tool Plan / Price Role CrewAI Check the provider's current pricing Orchestrates multiple LLM calls and decision logic n8n (Community Edition) Free (self-hosted Docker) Workflow engine that ties together APIs, webhooks and data stores OpenAI (GPT-4o) Pay-as-you-go Generates copy and images Buffer (or Hootsuite) Check the provider's current pricing Schedules posts to each social network Google Sheets Free with a Google account Stores content ideas, status flags and API keys RSS source (your blog, industry site) Free Supplies fresh topics to research Webhook (n8n built-in) Free Receives trigger events from the scheduler Estimated build time: ~6-8 hours for a production-ready workflow, assuming basic familiarity with Docker and API keys. Step-by-step build 1. Spin up n8n Install Docker if you don't have it: sudo apt-get update && sudo apt-get install -y docker.io Pull the official n8n image and run it on port 5678: docker run -d --name n8n \ -p 5678:5678 \ -v ~/.n8n:/root/.n8n \ n8nio/n8n Open http://localhost:5678 in a browser and create your first workflow. n8n's UI will ask you to set a Workflow Name; call it "AI Social Agent". Tip: Use a strong N8N_BASIC_AUTH_USER and N8N_BASIC_AUTH_PASSWORD environment variable to protect the UI if you expose the port to the internet. 2. Create a Google Sheet for content bookkeeping In Google Sheets, create a new spreadsheet named AI Content Queue. Add columns: Topic, Status (Pending/Generated/Scheduled), Copy, Image URL, Posted URL. Share the sheet with a service account (we'll generate one in the next step) so n8n can read/write via the Google Sheets API. 3. Set up OpenAI credentials Sign up at https://platform.openai.com/ and generate a secret API key. In n8n, go to Credentials → New Credential → OpenAI and paste the key. Choose the GPT-4o model for text and DALL·E 3 for image generation. Why GPT-4o? It offers the best balance of cost and capability for nuanced copy generation and can follow system prompts that enforce brand voice. 4. Install CrewAI and expose it as an HTTP endpoint CrewAI is a Python library that lets you chain LLM calls with tool use. We'll run it inside a small Flask server that n8n can call via webhook. python -m venv .venv source .venv/bin/activate pip install crewai flask openai Create agent_server.py: # agent_server.py - exposes a /run endpoint that executes the content-generation crew from flask import Flask, request, jsonify from crewai import Crew, Agent, Task, Tool app = Flask(__name__) # Define a simple tool to fetch RSS items class RSSFetcher(Tool): def run(self, url: str): import feedparser feed = feedparser.parse(url) return [entry.title for entry in feed.entries[:3]] # Agent that drafts copy copy_agent = Agent( role="Content Writer", goal="Write engaging social-media copy for a given topic", backstory="You are a brand-aware copywriter with a witty tone.", tools=[RSSFetcher()] ) # Agent that creates images image_agent = Agent( role="Image Creator", goal="Generate a DALL·E-compatible prompt and image URL", backstory="You understand visual branding and can translate copy into imagery." ) crew = Crew( agents=[copy_agent, image_agent], tasks=[ Task( description="Given a topic, fetch three related headlines, draft a 280-char tweet, and create an image prompt.", agent=copy_agent ), Task( description="Turn the copy into a DALL·E prompt and request an image URL.", agent=image_agent ) ] ) @app.route("/run", methods=["POST"]) def run(): data = request.json topic = data.get("topic") result = crew.kickoff(inputs={"topic": topic}) return jsonify(result) if __name__ == "__main__": app.run(host="0.0.0.0", port=5001) Run the server in the background: nohup python agent_server.py & What this does: The Flask endpoint receives a JSON payload like {"topic":"AI automation trends"} and returns generated copy plus an image URL. 5. Build the n8n workflow Trigger node - RSS Feed Choose "RSS Feed Read" Set the Feed URL to your industry blog. Enable "Emit items individually". Google Sheets - Read Row Search the AI Content Queue for rows where Status = Pending. Map the Topic field to the RSS item's title. HTTP Request - Call CrewAI server Method: POST URL: http://host.docker.internal:5001/run (Docker host bridge) Body Type: JSON JSON Payload: { "topic": "{{$json[\"Topic\"]}}" } Set - Update Google Sheet Write back Copy and Image URL from the HTTP response. Change Status to Generated. Buffer (or Hootsuite) - Create Post Use the Buffer node (available via n8n's community nodes) Authenticate with your Buffer account (see Buffer's API docs). Map Copy to the Message field, Image URL to Media URL, and select the target social profiles. Google Sheets - Mark as Posted Update the same row, setting Status to Scheduled and Posted URL to the response from Buffer. Cron node - Schedule Set to run every 4 hours (or any cadence you prefer). Connect the Cron node to the RSS node to start the chain. Full n8n JSON snippet for the HTTP Request node (copy-paste into the node's "JSON" tab): { "name": "Call CrewAI", "type": "n8n-nodes-base.httpRequest", "typeVersion": 1, "position": [600, 300], "parameters": { "url": "http://host.docker.internal:5001/run", "method": "POST", "responseFormat": "json", "jsonParameters": true, "options": {}, "bodyParametersJson": "{\"topic\":\"={{$json[\"Topic\"]}}\"}" }, "credentials": { "httpBasicAuth": { "id": "crewai-http-cred", "name": "CrewAI HTTP Basic" } } } What this does: It sends the current topic to the Flask-served CrewAI crew and receives both copy and an image URL in one request. 6. Test the end-to-end flow Manually add a row to AI Content Queue with Topic = "Latest trends in AI agents" and Status = Pending. Trigger the n8n workflow via the UI's "Execute Workflow" button. Verify: The Google Sheet now shows generated Copy and a valid Image URL. Buffer's UI lists a new scheduled post with the correct text and media. If any step fails, the n8n execution log will point to the exact node with an error message. 7. Deploy to production Docker-compose the n8n container together with the Flask server for easier orchestration. Use letsencrypt to secure both endpoints (https). Store all secrets (OpenAI key, Buffer token, Google service account JSON) in environment variables or a vault like HashiCorp Vault. version: "3.8" services: n8n: image: n8nio/n8n ports: - "5678:5678" environment: - N8N_BASIC_AUTH_USER=${N8N_USER} - N8N_BASIC_AUTH_PASSWORD=${N8N_PASS} volumes: - ~/.n8n:/root/.n8n agent: build: . ports: - "5001:5001" environment: - OPENAI_API_KEY=${OPENAI_API_KEY} Now the pipeline runs 24/7, pulling fresh topics, creating brand-consistent copy, and publishing it automatically - exactly what you set out to achieve when you asked how to build a fully automated AI system for cross-platform social media content. Where this breaks Failure mode Symptom Fix OpenAI rate-limit HTTP 429 returned from the OpenAI node Batch requests: add a Throttle node to keep calls under 60 req/min; monitor usage in the OpenAI dashboard. Expired Google service account token "Invalid credentials" error when reading/writing the sheet Rotate the service-account JSON every 30 days or use a long-lived OAuth refresh token. n8n container restarts Workflow stops at the "Call CrewAI" node because host.docker.internal becomes unavailable Use Docker network alias (my_network) and reference the Flask service by its container name. Buffer API quota exceeded Buffer node returns "Rate limit exceeded" and posts are dropped Upgrade or request higher limits; alternatively spread posts over a longer cron interval. RSS feed changes format RSS node returns empty items, no new topics appear Add a Function node that validates entry.title and falls back to a secondary feed URL. Image generation fails DALL·E returns "content_policy_violation" → no image URL Pre-filter the copy for prohibited keywords; add a retry with a sanitized prompt. Pro tip: Enable n8n's built-in Error Workflow to capture failures, log them to a Slack channel, and automatically reset the problematic node. For a deeper technical reference, see n8n's documentation. FAQ How do I keep the system completely free? The n8n Community Edition and Google Sheets are free to self-host, but the OpenAI API and any scheduling platform (Buffer, Hootsuite, etc.) charge per usage. Check each provider's current pricing to see if your projected volume stays within a free-tier limit; you may need to add a cost-monitoring step in n8n. Can I replace Buffer with a native platform API (e.g., Twitter API v2)? Yes. n8n includes built-in Twitter, LinkedIn and Facebook nodes. Swap the Buffer node for the appropriate platform node and use the same Copy field mapping. You'll need developer apps and bearer tokens for each network. What is a "faceless AI content agent"? A faceless AI content agent is an autonomous software persona that creates and publishes content without a human-visible author, relying on LLMs and tool integrations to mimic a content creator. How do I add image generation without DALL·E? You can plug any image-generation API (Stable Diffusion, Midjourney) by adding a HTTP Request node after the copy-generation step. Feed the copy into the prompt, capture the returned URL, and pass it to the scheduler. How can I monitor the pipeline's health? Use n8n's Execution List and enable the Error Workflow to send alerts to Slack or email. Additionally, log OpenAI token usage and Buffer post counts to a separate Google Sheet for periodic review. Where can I learn more about selling similar automations? Check our internal guide on AI automations you can sell for pricing models and client onboarding templates. If you need a quick-start checklist, grab the free guide we publish for new automation consultants. By following these steps you'll have a production-grade pipeline that automate social media posts with ai agents, scales with your content volume, and requires only occasional human oversight for strategy tweaks. The same pattern can be extended to newsletters, blog drafts, or even video script generation - anywhere you need a faceless AI content agent to do the heavy lifting. Happy building. Related reading how to build cold outreach ai agents with n8n and Perplexity API How to automate social media with AI - Build a never-dry posting engine Automate Content Repurposing with AI: Turn One Idea into a Week of Posts
This is a summary aggregated from Dev.to. Read the complete article on the original site:
Read full article at Dev.to