Skip to content
How I use AI

Self-running SEO/GEO blog

How I built the script that writes, illustrates and publishes posts on the Cactus Marketing blog without anyone touching them. With the code, the prompts and the bugs I ran into along the way.

12 min read · Claude Code · Gemini API

01

Why I built it

The channel that brings Cactus the most clients is this one: someone asks ChatGPT, Perplexity or Gemini for an ad agency and we show up in the answer. That's GEO (Generative Engine Optimization): getting AI assistants to name you when someone asks about what you do.

To name you, they first have to find you, and that takes a lot of published content answering specific questions. A good post written by hand takes me a morning. One a day, on top of running client campaigns, wasn't happening.

So I turned it into a script. Every run picks a topic the blog doesn't cover yet, finds real data, writes the post, generates the images, checks nothing is broken and leaves it ready to publish. I wrote it with Claude Code, but the script doesn't need Claude Code to run: it calls the Claude and Gemini APIs directly.

02

What you'll need

  • Claude CodeTo write the script and fix it when something breaks. You explain what you want and tune it together.
  • Claude APIThis is what writes. You need an API key from the Anthropic console with credit on it.
  • Nano Banana 2Makes the images. The key comes from Google AI Studio, and the project needs billing turned on to generate images.
  • CloudinaryStores the images and serves them already cropped. For a blog, the free plan is plenty.
  • Next.jsThe website. Each post is a TypeScript file inside the repository.
  • VercelPublishes the site every time a change lands in the repository.
  • GitHub ActionsA simple way to run the script every day without leaving a computer on.

If your blog isn't built with Next.js, that's fine. The logic works for any site that stores posts as files or has an API to publish them. Only the last step changes.

03

How it works inside

It all lives in one file, scripts/generate-posts.mjs, about 750 lines long. It does these things in order and, if something goes wrong, starts over with another topic:

  1. Picks a keyword that hasn't been published.
  2. Finds two real statistics with their source.
  3. Writes the whole post as a TypeScript file.
  4. Generates the images and uploads them to Cloudinary.
  5. Checks the file will compile.
  6. Saves it in the posts folder and adds it to the blog index.

The final step, pushing the change to the repository, is up to whatever runs the script. As soon as the commit lands, Vercel builds the site and the post goes live.

I use two Claude models. Haiku 4.5 picks topics and writes, because it's fast, cheap and more than enough for a blog post. Sonnet 4.6 only searches the web for data. That's where a mistake hurts most: a made-up statistic with a link that goes nowhere wrecks the credibility of the whole post.

04

One file per post

On the Cactus site every post is a .ts file inside src/posts/ exporting an object with everything: title, slug, dates, images, SEO data, the content split into sections and the FAQs. The site reads those files and builds the pages. These are the types the model has to follow:

Post types
interface BlogImage { url: string; altText?: string; caption?: string; }

interface BlogSection {
  title: string;
  level: 'h2' | 'h3' | 'h4';
  content: string;      // HTML
  image?: BlogImage;
}

interface BlogSEO {
  metaTitle: string;
  metaDescription: string;
  canonicalUrl: string;
  keywords: string[];
}

interface EnhancedBlogPost extends BlogPost {
  faqs: Array<{ question: string; answer: string }>;
}

Using TypeScript has an upside and a downside, and both come from the same place. If the model invents a field, the build fails and nothing weird gets published. But a single syntax error in one post takes down the deploy for the whole site. Further down I explain how I dealt with it.

If you're starting from scratch, define these types and write one post by hand in that structure. It'll be your example inside the prompt, and the model copies examples far more than it follows instructions.

05

Picking the topic

Let the model pick topics freely and it keeps suggesting the same thing in different words. Within a month you have five posts about Google reviews.

I fixed it with three things. Categories rotate by day of the month, so each day gets a different mix of SEO, social media, paid media and strategy. Before asking for topics, the script reads the names of every published post and passes them to Claude with orders not to repeat or reword any. And if the call fails, there are three hand-written backup topics so the day never goes without a post.

scripts/generate-posts.mjs
const TOPIC_ROTATION = [
  { category: "SEO" },
  { category: "Social Media" },
  { category: "Paid Media" },
  { category: "Strategy" },
];

async function getTrendingTopics(extraAvoid = "") {
  const day = new Date().getDate();
  const cats = [TOPIC_ROTATION[day % 4], TOPIC_ROTATION[(day + 1) % 4], TOPIC_ROTATION[(day + 2) % 4]];
  const existingTopics = getExistingSlugs().join(" | ");

  const res = await anthropic.messages.create({
    model: "claude-haiku-4-5-20251001",
    max_tokens: 1500,
    messages: [{
      role: "user",
      content: `Genera 6 keywords de marketing digital en español COLOQUIAL para empresarios sin conocimientos técnicos.
Categorías: ${cats.map(c => c.category).join(", ")}.

TEMAS YA CUBIERTOS — elige algo COMPLETAMENTE DIFERENTE, NO variaciones de estos:
${existingTopics}
${extraAvoid ? "Evita también: " + extraAvoid : ""}

BUENOS EJEMPLOS: "cómo conseguir reseñas en Google", "qué es el email marketing", "cómo vender en TikTok sin seguidores"
MALOS EJEMPLOS: variaciones de los temas ya cubiertos, tecnicismos como "optimización GEO"

Solo JSON sin texto extra:
{"posts":[{"category":"SEO","mainKeyword":"...","angle":"...","secondaryKeywords":["...","..."]}, ...]}`,
    }],
  });
  // ...si falla o no hay JSON válido, devuelve FALLBACK_POSTS
}

Notice the tone I ask for: plain, everyday Spanish, the way someone who doesn't know marketing would put it. Nobody searches for “conversion rate optimization”. People search for “why isn't my website selling”. A couple of good examples and a couple of bad ones in the prompt and it gets it first time.

If the resulting slug already exists in the posts folder, the script asks for topics again and adds that one to the banned list.

06

Finding real data

AI assistants are quicker to cite a text with data and a source than an opinion piece. The catch: ask a model to “include statistics” and it makes them up. Link included.

So this step is a separate call with the Claude API's web search turned on. I ask for two statistics on the keyword, only from a fixed list of sources, plus the exact URL of the page where each figure appears. The code is simplified, without the error handling:

Statistics search
const response = await anthropic.messages.create({
  model: "claude-sonnet-4-6",
  max_tokens: 1000,
  tools: [{ type: "web_search_20250305", name: "web_search" }],
  messages: [{
    role: "user",
    content: `Search for 2 real, specific marketing statistics with exact source URLs related to: "${topic.mainKeyword}".
Only use authoritative sources: HubSpot, Statista, Meta Business, Google Think with Google, Semrush, Hootsuite, Sprout Social, WordStream, eMarketer.
Return ONLY a valid JSON array (no extra text):
[{"stat":"brief stat in Spanish","url":"exact full URL to the page containing this data","source":"Source Name (Year)"}]`,
  }],
});

const text = response.content.filter(b => b.type === "text").map(b => b.text).join("");
const stats = JSON.parse(text.match(/\[[\s\S]*?\]/)[0]);

Those statistics go into the writing prompt as the only external links allowed. If the search fails or returns nothing usable, the post still gets written, with a different instruction: name the source as text, no link. I'd rather have a post with one less number than one with a link that 404s.

07

The writing prompt

It's the longest prompt in the script and the one I've changed the most. It runs past 150 lines, so I won't paste it all. These are the parts that make the biggest difference.

Titles that don't sound like AI

Models love colon titles (“Local SEO: why your business needs it”), tacking the year on the end and words like “ultimate” or “complete”. I ban them with examples of what's wrong and how it should read. The prompt is in Spanish because the blog is:

Title rules
TÍTULO DEL POST:
- Máximo 60 caracteres
- Incluye la keyword principal de forma natural
- PROHIBIDO usar dos puntos (:) para añadir coletillas. El título debe ser una sola idea clara.
  MAL: "Cómo saber si tu web atrae clientes de verdad: métricas que importan"
  BIEN: "Cómo saber si tu web atrae clientes de verdad"
  MAL: "Anuncios en YouTube que realmente funcionan: estrategia probada en 2026"
  BIEN: "Anuncios en YouTube que funcionan con poco presupuesto"
- PROHIBIDO añadir el año al final del título

PROHIBIDO en todos los headings (title, H2, H3, metaTitle):
- Superlativos vacíos: "definitivo", "completo", "que realmente funciona", "probado"
- Fórmulas genéricas: "Guía de X", "Todo sobre X", "Introducción", "Conclusión"

The voice

I give it a persona, tell it to address the reader informally and hand it a list of banned phrases. They're the ones that show up in nearly everything AI writes in Spanish:

Voice and style
VOZ Y ESTILO:
Eres un consultor de marketing español con 10 años de experiencia escribiendo para sus clientes.
Tienes personalidad propia. Escribes como te sale natural para el tema concreto que estás tratando.
A veces eres directo y vas al grano. A veces usas ironía si el tema lo pide. A veces haces una pregunta. A veces no.
No sigues una fórmula.

- Tutear al lector
- No usar estas frases que delatan IA: "Sin duda alguna", "Es fundamental destacar",
  "Cabe destacar que", "En el panorama actual", "No hay que olvidar que", "En definitiva",
  "Sin lugar a dudas", "Resulta evidente que", "Como hemos visto",
  "A lo largo de este artículo", "landscape", "game-changer", "sinergia", "holístico",
  "ecosistema digital"

Telling it which phrases it can't use works much better than asking it to write “naturally”. That instruction doesn't tell it anything concrete.

A structure built for Google and for assistants

Every section opens by answering its heading in one or two sentences, straight to the point. That answer is what Google lifts for featured snippets and what ChatGPT or Perplexity copy when they cite. The detail comes after. The rest of the structure is fixed:

  • An 80 to 100 word intro with the keyword in bold and one internal link.
  • Four H2 sections and one H3 inside one of them, phrased the way someone would type it into Google.
  • A table, always with the same HTML structure so the site renders it properly.
  • A numbered list of steps. Google uses those for “how to” snippets.
  • Three FAQs that answer in the first sentence and expand afterwards.
  • A definition along the lines of “X is…” and a comparison like “the difference between A and B is…”. Those are the sentences assistants cite most.

Links that exist

Ask for internal links without more and it invents URLs. The script passes it the real list of published posts with their titles and the four Cactus service pages, and makes it choose from there: one or two related posts and the service page closest to the topic, worked into a normal sentence rather than an ad.

08

The images

Each post has a featured image and one or two inside the text. Claude doesn't generate images. It leaves a placeholder in the url field describing what it wants to show:

A section with its placeholder
{
  title: 'Qué mirar antes de subir el presupuesto',
  level: 'h2' as const,
  content: '<p>...</p>',
  image: {
    url: 'IMAGE_PROMPT_SECTION: [GRAPHIC] diagrama de embudo con tres fases Conciencia, Consideración y Conversión, con flechas',
    altText: 'Embudo de conversión en tres fases',
    caption: 'Las tres fases que recorre un cliente antes de comprar'
  }
}

Once the post is written, the script finds those placeholders. Each description goes to Nano Banana 2 (Gemini's image model) with a fixed style appended, the image is uploaded to Cloudinary and the final URL replaces the placeholder.

Generate and upload an image
const STYLE = "Clean professional minimalist 3D illustration, 16:9. IMPORTANT: all text labels, titles, captions and annotations in the image must be written in Spanish (Castilian), not English.";

async function generateAIImage(prompt, slug) {
  const enriched = `${prompt.replace(/^\[GRAPHIC\]\s*/i, "")}. ${STYLE}`;

  for (let attempt = 1; attempt <= 3; attempt++) {
    try {
      const res = await genai.models.generateContent({
        model: "gemini-3.1-flash-image-preview",
        contents: [{ role: "user", parts: [{ text: enriched }] }],
        config: { responseModalities: ["TEXT", "IMAGE"] },
      });

      const parts = res.candidates?.[0]?.content?.parts ?? [];
      const img = parts.find(p => p.inlineData?.mimeType?.startsWith("image/"));
      if (!img?.inlineData?.data) throw new Error("Gemini no devolvió imagen");

      const dataUri = `data:${img.inlineData.mimeType};base64,${img.inlineData.data}`;
      const r = await cloudinary.uploader.upload(dataUri, {
        folder: "cactus-blog",
        public_id: slug,
        overwrite: true,
        transformation: [
          { width: 1200, height: 630, crop: "fill" },
          { quality: "auto:good" },
          { format: "webp" },
        ],
      });
      return r.secure_url;
    } catch (e) {
      if (attempt < 3) await wait(4000);
    }
  }
  return ""; // sin imagen, el artículo sale igual
}

The script always adds the style, not the model, which is why every image on the blog looks like part of the same series. Cloudinary crops to 1200×630 and converts to WebP on upload, the size social networks use when someone shares a link. And if an image fails three times in a row, the post goes out without it. I'd rather that than lose the day's post.

09

Checking before saving

This step wasn't there at first. I kept adding to it every time a broken post took down a deploy. Before saving anything, the script checks the code the model wrote:

Validation
const REQUIRED_FIELDS = ["id:", "slug:", "title:", "excerpt:", "category:", "publishedAt:",
  "modifiedAt:", "readTime:", "featuredImage:", "author:", "seo:", "content:", "faqs:"];
const FORBIDDEN_FIELDS = ["relatedPosts:", "  tags:", "schema:", "  type:"];

function validatePost(code) {
  const open = (code.match(/\{/g) || []).length;
  const close = (code.match(/\}/g) || []).length;
  const missing = REQUIRED_FIELDS.filter(f => !code.includes(f));
  const forbidden = FORBIDDEN_FIELDS.filter(f => code.includes(f));
  const doubleQuotes = (code.match(/''/g) || []).length;
  const hasImageHtmlTag = /<image\s/i.test(code) || /<img\s[^>]*url=/i.test(code);
  const urlFieldContamination = /url:\s*'[^']*',[^,}\s\n][^}\n]*'/g.test(code);

  const checks = [
    { test: code.includes("export default post;"), msg: "Falta export default" },
    { test: missing.length === 0, msg: `Faltan: ${missing.join(", ")}` },
    { test: forbidden.length === 0, msg: `Campos prohibidos: ${forbidden.join(", ")}` },
    { test: open === close, msg: `Post cortado (${open} llaves abiertas vs ${close} cerradas)` },
    { test: doubleQuotes === 0, msg: "Comillas dobles consecutivas ('')" },
    { test: !hasImageHtmlTag, msg: "Etiqueta <image> o <img> dentro del content" },
    { test: !urlFieldContamination, msg: "Texto pegado después de una URL de imagen" },
  ];

  return checks.every(c => c.test);
}

If any check fails, the post is thrown away and the next topic gets a go, up to three attempts. Separately, there's a cleanup that always runs: it cuts anything after a colon in titles, strips the markdown fences the model sometimes wraps around the code and deletes any text left stuck to an image URL.

10

Saving, publishing and running on its own

The post is saved to src/posts/ with the slug as the file name, and the script adds the import to the blog index, src/data/blogData.ts. From there the site has it. All that's left is pushing it: as soon as the commit lands, Vercel builds and publishes in a couple of minutes.

To make it happen every day without touching anything, the easiest route is a GitHub Actions workflow on a cron. This one is a good starting point:

.github/workflows/daily-post.yml
name: Artículo diario

on:
  schedule:
    - cron: "0 6 * * *"   # todos los días a las 6:00 UTC
  workflow_dispatch:       # y un botón para lanzarlo a mano

jobs:
  post:
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
      - run: npm ci
      - run: node scripts/generate-posts.mjs
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
          GOOGLE_API_KEY: ${{ secrets.GOOGLE_API_KEY }}
          CLOUDINARY_CLOUD_NAME: ${{ secrets.CLOUDINARY_CLOUD_NAME }}
          CLOUDINARY_API_KEY: ${{ secrets.CLOUDINARY_API_KEY }}
          CLOUDINARY_API_SECRET: ${{ secrets.CLOUDINARY_API_SECRET }}
      - name: Subir el artículo
        run: |
          git config user.name "blog-bot"
          git config user.email "blog-bot@users.noreply.github.com"
          git add src/posts src/data/blogData.ts
          git diff --cached --quiet || (git commit -m "Nuevo artículo" && git push)

The keys go in the repository under Settings → Secrets and variables → Actions. If Vercel is connected to the repository there's nothing else to do: the workflow's push triggers the deploy.

11

The llms.txt

Besides the blog, the Cactus site has an llms.txt file at the root. It's plain text meant for AI assistants to read: what the agency is, where it's based, what it offers, who it works with and the URL of every important page.

Nobody guarantees every assistant reads it, but it takes half an hour. Write it the way you'd explain your business to someone who doesn't know you, with proper accents if your language has them. The first version Claude wrote for me stripped every accent and ñ out of the Spanish, and there was no technical reason for it: the file is served as UTF-8 and people's questions have accents in them.

12

Building it yourself with Claude Code

You don't need to write 750 lines by hand. The whole script can be built by talking to Claude Code, one piece at a time. Start with a first message that gives it all the context and asks it to go step by step. This is it in Spanish, as I'd write it:

First message to Claude Code
Quiero un script en Node (scripts/generate-posts.mjs) que publique un artículo
nuevo en el blog cada vez que se ejecute.

Contexto:
- Los artículos están en src/posts/, uno por archivo .ts, con los tipos de
  src/types/blog.ts. Mira src/posts/[un-articulo-que-ya-exista].ts como ejemplo.
- El índice del blog es src/data/blogData.ts.

Pasos:
1. Lee los artículos que ya existen y pide a la API de Claude (Haiku) seis
   keywords nuevas en español coloquial que no repitan ninguno.
2. Con la API de Claude (Sonnet) y la búsqueda web, busca dos estadísticas
   reales con su URL para la keyword elegida.
3. Pide a Haiku el artículo completo como archivo TypeScript con esos tipos.
   Las imágenes van como marcadores IMAGE_PROMPT en el campo url.
4. Genera cada imagen con la API de Gemini, súbela a Cloudinary a 1200x630
   en WebP y cambia el marcador por la URL.
5. Comprueba que el archivo es válido antes de guardarlo. Si no, prueba
   otro tema, hasta tres veces.
6. Guarda el artículo y añádelo a blogData.ts.

Las claves están en ANTHROPIC_API_KEY, GOOGLE_API_KEY y CLOUDINARY_*.
Empieza por el paso 1 y enséñame el resultado antes de seguir.

From there, this is the order that works:

  1. Let it do step 1 and run it yourself with node scripts/generate-posts.mjs. Look at the keywords that come out and fix the prompt until you like them.
  2. Once the topics are right, move on to the post without images. Generate three or four and read them all the way through. This is where you tune the voice and where your list of banned phrases comes from.
  3. Then the images. Check the style stays the same from one post to the next.
  4. Add validation as things break. Don't try to guess every failure on day one.
  5. Finally, the workflow that runs it on its own.

13

How to tell if it's working

Classic SEO is measured in Search Console: impressions, clicks and position for each post. GEO is less direct, but there are three ways to see it:

  • Ask them yourself. Every so often, put the questions a client would ask to ChatGPT, Perplexity and Gemini (“which Meta Ads agency do you recommend in Murcia”) and note whether you appear, where, and which of your pages they cite.
  • Look at traffic from the assistants. ChatGPT adds utm_source=chatgpt.com to the links it shows, so it appears as a source in GA4. Perplexity and Gemini show up as referrals from their domains.
  • Ask every new client how they found you. Lots of people don't click: they read your name in the answer and then search for you or message you directly, and no analytics tool catches that.

14

The bugs I ran into

Almost every broken deploy had the same cause. Here they are so they don't happen to you.

Text stuck to an image URL

The model wrote the image description with quotes in it, or with figures from the post, and the regular expression looking for the placeholder stopped too early. The leftover text ended up glued to the URL and the file stopped compiling:

What reached Vercel
featuredImage: {
  url: 'https://res.cloudinary.com/.../como-conseguir-que-google-entienda-que-vende-negocio-featured.png'Estructura clara de una web que Google entiende fácilmente'
},

I fixed it from both ends. In the prompt, by banning quotes, apostrophes and figures inside the image description, with an example of how not to do it. In the code, with a regular expression that only stops at the closing quote and a final cleanup that leaves nothing but the URL in url. If something still sneaks through, validation throws the post away.

A badly written example in the prompt itself

One of the examples in the prompt had an unclosed quote, and the model copied that mistake into some posts. If the example is wrong, it doesn't matter what you write around it. Check your examples carefully.

How I fix it when it breaks

When Vercel errors out, I copy the build message and paste it into Claude Code with two jobs: fix the broken post and change the script so it doesn't happen again. The first takes two minutes. The second is what matters, because every bug you fix in the script never comes back.

Want something like this in your business?

Email me and let's talk.

Email me