{
  "name": "Đăng bài SỰ AI tự động (có ảnh minh họa)",
  "nodes": [
    {
      "parameters": {
        "rule": {
          "interval": [
            {
              "triggerAtHour": 19
            }
          ]
        }
      },
      "type": "n8n-nodes-base.scheduleTrigger",
      "typeVersion": 1.3,
      "position": [
        -1856,
        160
      ],
      "id": "cb341e2c-f495-4960-b2f0-db9a3629430d",
      "name": "Schedule Trigger"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const staticData = $getWorkflowStaticData('global');\nconst topics = staticData.topics || [];\nconst index = staticData.topicIndex || 0;\n\nif (!topics.length || index >= topics.length) {\n  return [{ json: { needNewTopics: true } }];\n}\n\nreturn [{ json: { needNewTopics: false } }];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -1632,
        160
      ],
      "id": "a1b2c3d4-0001-0001-0001-000000000001",
      "name": "Kiểm Tra Lộ Trình"
    },
    {
      "parameters": {
        "conditions": {
          "options": {
            "caseSensitive": true,
            "leftValue": "",
            "typeValidation": "strict"
          },
          "conditions": [
            {
              "id": "cond-1",
              "leftValue": "={{ $json.needNewTopics }}",
              "rightValue": true,
              "operator": {
                "type": "boolean",
                "operation": "true",
                "singleValue": true
              }
            }
          ],
          "combinator": "and"
        },
        "options": {}
      },
      "type": "n8n-nodes-base.if",
      "typeVersion": 2,
      "position": [
        -1408,
        160
      ],
      "id": "a1b2c3d4-0002-0002-0002-000000000002",
      "name": "Cần Lộ Trình Mới?"
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "models/gemini-2.5-flash",
          "mode": "id"
        },
        "messages": {
          "values": [
            {
              "content": "Nghiên cứu các trend mới nhất hiện tại về AI (công cụ AI, mô hình AI, ứng dụng AI trong công việc/kinh doanh, tin tức AI nổi bật). Dựa vào đó, đề xuất 7 CHỦ ĐỀ bài viết SEO tiếng Việt khác nhau, đa dạng góc nhìn, không trùng lặp ý tưởng, không trùng chủ đề với nhau.\n\nMỗi chủ đề chỉ cần là 1 câu ngắn gọn mô tả góc viết (không cần viết bài đầy đủ).\n\nQUAN TRỌNG: Tuyệt đối KHÔNG dùng dấu ngoặc kép (\") bên trong các chủ đề.\n\nHãy trả lời CHÍNH XÁC theo format JSON array sau, không thêm text giải thích, không thêm markdown code block:\n[\"chủ đề 1\", \"chủ đề 2\", \"chủ đề 3\", \"chủ đề 4\", \"chủ đề 5\", \"chủ đề 6\", \"chủ đề 7\"]"
            }
          ]
        },
        "simplify": false,
        "builtInTools": {},
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1.2,
      "position": [
        -1184,
        64
      ],
      "id": "a1b2c3d4-0003-0003-0003-000000000003",
      "name": "Tạo Lộ Trình 7 Chủ Đề"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const raw = $('Tạo Lộ Trình 7 Chủ Đề').item.json.candidates[0].content.parts[0].text;\n\nlet text = raw.replace(/```json/g, '').replace(/```/g, '').trim();\n\nlet topics;\ntry {\n  topics = JSON.parse(text);\n} catch (e) {\n  throw new Error('Khong parse duoc danh sach chu de tra ve: ' + text.substring(0, 300));\n}\n\nif (!Array.isArray(topics) || topics.length === 0) {\n  throw new Error('Danh sach chu de khong hop le: ' + text.substring(0, 300));\n}\n\nconst staticData = $getWorkflowStaticData('global');\nstaticData.topics = topics;\nstaticData.topicIndex = 1; // da dung topic[0], lan sau dung index 1\n\nreturn [{ json: { topic: topics[0] } }];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -960,
        64
      ],
      "id": "a1b2c3d4-0004-0004-0004-000000000004",
      "name": "Lưu Lộ Trình & Lấy Chủ Đề #1"
    },
    {
      "parameters": {
        "mode": "runOnceForAllItems",
        "jsCode": "const staticData = $getWorkflowStaticData('global');\nconst topics = staticData.topics || [];\nconst index = staticData.topicIndex || 0;\n\nconst topic = topics[index];\nstaticData.topicIndex = index + 1;\n\nreturn [{ json: { topic } }];"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -1184,
        256
      ],
      "id": "a1b2c3d4-0005-0005-0005-000000000005",
      "name": "Lấy Chủ Đề Tiếp Theo"
    },
    {
      "parameters": {
        "modelId": {
          "__rl": true,
          "value": "models/gemini-2.5-flash",
          "mode": "id"
        },
        "messages": {
          "values": [
            {
              "content": "=Viết bài đúng chuẩn SEO bằng tiếng Việt về chủ đề sau: {{ $json.topic }}\n\nYêu cầu:\n- dài 1000 - 2000 từ\n- Có các tiêu đề đặt trong thẻ html H2, H3\n- ĐÚng chuẩn SEO\n- có mở bài, thân bài, kết luận\n\nQUAN TRỌNG: Tuyệt đối KHÔNG dùng dấu ngoặc kép (\") bên trong tiêu đề hoặc nội dung bài viết. Nếu cần nhấn mạnh một từ/cụm từ, hãy dùng dấu nháy đơn (') hoặc viết hoa thay thế, không dùng dấu ngoặc kép.\n\nHãy trả lời CHÍNH XÁC theo format JSON sau, không thêm text giải thích, không thêm markdown code block:\n{\"title\": \"tiêu đề bài viết\", \"content\": \"nội dung bài viết đầy đủ\"}"
            }
          ]
        },
        "simplify": false,
        "builtInTools": {},
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1.2,
      "position": [
        -704,
        160
      ],
      "id": "6f893f33-4393-422e-a492-afad51cccab4",
      "name": "Message a model"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const raw = $('Message a model').item.json.candidates[0].content.parts[0].text;\n\nfunction unescape(s) {\n  return s\n    .replace(/\\\\n/g, '\\n')\n    .replace(/\\\\r/g, '\\r')\n    .replace(/\\\\t/g, '\\t')\n    .replace(/\\\\\"/g, '\"')\n    .replace(/\\\\\\\\/g, '\\\\');\n}\n\nfunction extractAndFix(text) {\n  text = text.replace(/```json/g, '').replace(/```/g, '').trim();\n\n  try {\n    const parsed = JSON.parse(text);\n    if (parsed && typeof parsed.title === 'string' && typeof parsed.content === 'string') {\n      return parsed;\n    }\n  } catch (e) {\n    // fallback xuong duoi\n  }\n\n  const titleKeyIdx = text.indexOf('\"title\"');\n  const contentKeyIdx = text.indexOf('\"content\"');\n  if (titleKeyIdx === -1 || contentKeyIdx === -1) {\n    throw new Error('Khong tim thay field title/content trong text tra ve: ' + text.substring(0, 300));\n  }\n\n  let titleValStart = text.indexOf(':', titleKeyIdx) + 1;\n  while (text[titleValStart] === ' ') titleValStart++;\n  titleValStart++;\n\n  const titleValEnd = text.lastIndexOf('\"', contentKeyIdx);\n  const titleRaw = text.substring(titleValStart, titleValEnd);\n\n  let contentValStart = text.indexOf(':', contentKeyIdx) + 1;\n  while (text[contentValStart] === ' ') contentValStart++;\n  contentValStart++;\n\n  const contentValEnd = text.lastIndexOf('\"');\n  const contentRaw = text.substring(contentValStart, contentValEnd);\n\n  return {\n    title: unescape(titleRaw),\n    content: unescape(contentRaw)\n  };\n}\n\nconst data = extractAndFix(raw);\n\nreturn {\n  title: data.title,\n  content: data.content\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -480,
        160
      ],
      "id": "ae5e1c10-765a-4171-93f1-8639f1ef08d6",
      "name": "Parse Gemini Output"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const title = $json.title;\n\n// Tao prompt anh minh hoa tu tieu de bai viet\nconst imagePrompt = `Flat minimalist illustration, navy blue and white color palette, modern tech style, no text, no logo, no watermark, wide 16:9 composition. Topic: ${title}`;\n\nreturn {\n  ...$json,\n  imagePrompt\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        -256,
        160
      ],
      "id": "4cdf7d66-312e-473c-b934-024090b7b707",
      "name": "Build Image Prompt"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://api.cloudflare.com/client/v4/accounts/YOUR_ACCOUNT_ID/ai/run/@cf/stabilityai/stable-diffusion-xl-base-1.0",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpHeaderAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ JSON.stringify({ \n  prompt:  `genarate illustration, ratio 3:2, topic: ${$json.title}`\n}) }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        -32,
        160
      ],
      "id": "3bf72023-75b9-414d-9ca9-9816d8d0e682",
      "name": "HTTP Request"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const genImageItem = $input.item;\n\nreturn {\n  json: {\n    title: $('Parse Gemini Output').item.json.title,\n    content: $('Parse Gemini Output').item.json.content\n  },\n  binary: genImageItem.binary\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        192,
        160
      ],
      "id": "36896b50-172a-41c1-8194-de0a7d50ef07",
      "name": "Prepare Image Binary"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://YOUR_DOMAIN.com/wp-json/wp/v2/media",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendHeaders": true,
        "headerParameters": {
          "parameters": [
            {
              "name": "Content-Disposition",
              "value": "attachment; filename=\"illustration.png\""
            }
          ]
        },
        "sendBody": true,
        "contentType": "binaryData",
        "inputDataFieldName": "data",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        416,
        0
      ],
      "id": "64f1be98-6e13-430c-b418-43aaabdc841f",
      "name": "Upload Image to WordPress"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const title = $('Parse Gemini Output').item.json.title;\nconst content = $('Parse Gemini Output').item.json.content;\nconst mediaId = $json.id;\nconst imageUrl = $json.source_url;\n\nconst contentWithImage = `<img src=\"${imageUrl}\" alt=\"${title}\" style=\"max-width:100%;\" /><br/><br/>` + content;\n\nreturn {\n  jsonBody: JSON.stringify({\n    title: title,\n    content: contentWithImage,\n    status: \"publish\",\n    featured_media: mediaId,\n    categories: [192]\n  })\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        640,
        0
      ],
      "id": "fb95d8b5-b8f3-460a-a1c5-588fd11c5094",
      "name": "Build Post Body"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://YOUR_DOMAIN.com/wp-json/wp/v2/posts",
        "authentication": "genericCredentialType",
        "genericAuthType": "httpBasicAuth",
        "sendBody": true,
        "specifyBody": "json",
        "jsonBody": "={{ $json.jsonBody }}",
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        864,
        0
      ],
      "id": "1097adde-c585-4f50-baa6-7868870377fa",
      "name": "Create Post"
    },
    {
      "parameters": {
        "mode": "runOnceForEachItem",
        "jsCode": "const title = $json.title;\nconst content = $json.content;\n\n// Xoa the HTML neu co, lay doan dau lam caption\nconst plainText = content.replace(/<[^>]*>/g, '');\nconst shortContent = plainText.substring(0, 400).trim();\n\nconst caption = `${title}\\n\\n${shortContent}...\\n\\nXem đầy đủ tại: https://YOUR_DOMAIN.com`;\n\nreturn {\n  json: {\n    ...$json,\n    fbCaption: caption\n  },\n  binary: $input.item.binary\n};"
      },
      "type": "n8n-nodes-base.code",
      "typeVersion": 2,
      "position": [
        416,
        320
      ],
      "id": "6a47eeb5-7608-4b9d-908b-548055c5b0d0",
      "name": "Cắt Ngắn Nội Dung FB"
    },
    {
      "parameters": {
        "method": "POST",
        "url": "https://hook.usX.make.com/YOUR_WEBHOOK_ID",
        "sendBody": true,
        "contentType": "multipart-form-data",
        "bodyParameters": {
          "parameters": [
            {
              "name": "caption",
              "value": "={{ $json.fbCaption }}"
            },
            {
              "name": "title",
              "value": "={{ $json.title }}"
            },
            {
              "parameterType": "formBinaryData",
              "name": "image",
              "inputDataFieldName": "data"
            }
          ]
        },
        "options": {}
      },
      "type": "n8n-nodes-base.httpRequest",
      "typeVersion": 4.4,
      "position": [
        640,
        320
      ],
      "id": "045e9718-62b7-46be-8437-abfe7c49bd08",
      "name": "Gửi Sang Make Đăng Facebook"
    },
    {
      "parameters": {
        "resource": "image",
        "modelId": {
          "__rl": true,
          "value": "models/gemini-3.1-flash-image",
          "mode": "list",
          "cachedResultName": "models/gemini-3.1-flash-image (Nano Banana 2)"
        },
        "prompt": "= Create a flat minimalist poster ( landscape 3:2) for an AI education brand.\nTopic of poster : {{ $json.title }}\nStyle:\n- Flat design, minimalist\n- Small \"Sự AI\" logo/wordmark in a corner\n- Professional, modern, educational tone — no clutter, lots of negative space",
        "options": {}
      },
      "type": "@n8n/n8n-nodes-langchain.googleGemini",
      "typeVersion": 1.2,
      "position": [
        -256,
        -160
      ],
      "id": "466ecaf2-b3ee-4d4a-bfa0-38e09947432e",
      "name": "Generate an image"
    }
  ],
  "pinData": {},
  "connections": {
    "Schedule Trigger": {
      "main": [
        [
          {
            "node": "Kiểm Tra Lộ Trình",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Kiểm Tra Lộ Trình": {
      "main": [
        [
          {
            "node": "Cần Lộ Trình Mới?",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cần Lộ Trình Mới?": {
      "main": [
        [
          {
            "node": "Tạo Lộ Trình 7 Chủ Đề",
            "type": "main",
            "index": 0
          }
        ],
        [
          {
            "node": "Lấy Chủ Đề Tiếp Theo",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Tạo Lộ Trình 7 Chủ Đề": {
      "main": [
        [
          {
            "node": "Lưu Lộ Trình & Lấy Chủ Đề #1",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lưu Lộ Trình & Lấy Chủ Đề #1": {
      "main": [
        [
          {
            "node": "Message a model",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Lấy Chủ Đề Tiếp Theo": {
      "main": [
        [
          {
            "node": "Message a model",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Message a model": {
      "main": [
        [
          {
            "node": "Parse Gemini Output",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Parse Gemini Output": {
      "main": [
        [
          {
            "node": "Build Image Prompt",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Image Prompt": {
      "main": [
        [
          {
            "node": "HTTP Request",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "HTTP Request": {
      "main": [
        [
          {
            "node": "Prepare Image Binary",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Prepare Image Binary": {
      "main": [
        [
          {
            "node": "Upload Image to WordPress",
            "type": "main",
            "index": 0
          },
          {
            "node": "Cắt Ngắn Nội Dung FB",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Upload Image to WordPress": {
      "main": [
        [
          {
            "node": "Build Post Body",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Build Post Body": {
      "main": [
        [
          {
            "node": "Create Post",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Cắt Ngắn Nội Dung FB": {
      "main": [
        [
          {
            "node": "Gửi Sang Make Đăng Facebook",
            "type": "main",
            "index": 0
          }
        ]
      ]
    },
    "Generate an image": {
      "main": [
        []
      ]
    }
  },
  "active": false,
  "settings": {
    "executionOrder": "v1",
    "binaryMode": "separate",
    "availableInMCP": false
  },
  "versionId": "7a8b9c0d-1e2f-3a4b-5c6d-7e8f9a0b1c2d",
  "meta": {
    "instanceId": "b74c9eb8a208e23e664a465e72ebfaf38ba3cc42ad0fd8fe4867a95fc514bdea"
  },
  "nodeGroups": [],
  "id": "vQeyTn18VHNzsjqH",
  "tags": []
}