# Plantillas

> Plantillas completas de BuilderBot: un agente con herramientas, ventas por WhatsApp con catálogo, preguntas sobre un PDF o un enlace y soporte con paso a una persona. Un solo archivo para pegar, y corre en tu navegador.
>
> - **Canonical URL:** https://www.builderbot.app/es/templates
> - **Documentation Index:** https://www.builderbot.app/llms.txt
> - **Full Corpus:** https://www.builderbot.app/llms-full.txt

Estos son los diez bots que la gente termina construyendo a mano. Un asistente que consulta un dato antes de responder, un bot de ventas con catálogo y total real, un bot que lee un PDF o un enlace, y un bot de soporte que sabe cuándo pasar el chat.

Cada una es un flow completo: el `state` que guarda, el paso que hace el trabajo y lo que dice el bot cuando el cliente responde algo que el camino feliz no esperaba. Pulsa **Probar en vivo** para hablar con el mismo flow en tu navegador: las llamadas de red se sustituyen por datos fijos, así que no necesitas claves.

_Actualizado 2026-11-18._

### AI agent that can look things up

- **Archivo:** `flows/agent.flow.ts`
- **Documentación:** /add-functions#add-action

Un chat con memoria que puede buscar en la web o consultar un pedido antes de responder, en lugar de inventarse el dato.

**Implementación en BuilderBot:**

```ts
import { EVENTS, addKeyword } from '@builderbot/bot'

const SYSTEM = `You are the assistant of ACME. Reply in the customer's language, in one short WhatsApp message.
When you need live data, reply with exactly one line and nothing else:
TOOL search <query>
TOOL order <id>`

const MAX_TURNS = 12

const searchWeb = async (query: string) => {
    const url = `https://serpapi.com/search.json?q=${encodeURIComponent(query)}&api_key=${process.env.SERPAPI_KEY}`
    const data = await (await fetch(url)).json()
    const snippets = (data.organic_results ?? []).slice(0, 3).map((item: any) => item.snippet)
    return snippets.join(' ') || 'no results'
}

const lookupOrder = async (id: string) => {
    const res = await fetch(`${process.env.ORDERS_API}/orders/${id}`)
    if (!res.ok) return 'order not found'
    const order = await res.json()
    return `status ${order.status}, total ${order.total}`
}

const ask = async (messages: { role: string; content: string }[]) => {
    const res = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
        },
        body: JSON.stringify({ model: 'gpt-4o-mini', messages: [{ role: 'system', content: SYSTEM }, ...messages] }),
    })
    const data = await res.json()
    return data.choices?.[0]?.message?.content ?? 'I could not get an answer. Try again in a moment.'
}

export default addKeyword(EVENTS.WELCOME).addAction(async (ctx, { state, flowDynamic }) => {
    const history = (state.get('history') ?? []) as { role: string; content: string }[]
    const messages = [...history, { role: 'user', content: ctx.body }].slice(-MAX_TURNS)

    let answer = await ask(messages)
    const tool = /^TOOL (search|order) (.+)$/.exec(answer.trim())
    if (tool) {
        const result = tool[1] === 'search' ? await searchWeb(tool[2]) : await lookupOrder(tool[2])
        messages.push({ role: 'assistant', content: answer }, { role: 'user', content: `TOOL RESULT: ${result}` })
        answer = await ask(messages)
    }

    await state.update({ history: [...messages, { role: 'assistant', content: answer }].slice(-MAX_TURNS) })
    await flowDynamic(answer)
})
```

Guarda los últimos turnos en `state`. El modelo responde, o contesta `TOOL search …` / `TOOL order …`. Ejecutas esa llamada y vuelves a preguntarle con el resultado. Una vuelta basta para WhatsApp.

### WhatsApp sales agent with a catalog

- **Archivo:** `flows/sales.flow.ts`
- **Documentación:** /methods#state

Cotiza un precio, pregunta cuántos asientos y solo confirma el pedido cuando la cantidad es un número real.

**Implementación en BuilderBot:**

```ts
import { EVENTS, addKeyword } from '@builderbot/bot'

const CATALOG = [
    { id: 'pro', name: 'Pro plan', price: 29 },
    { id: 'starter', name: 'Starter plan', price: 9 },
]

const findPlan = (text: string) =>
    CATALOG.find((plan) => text.toLowerCase().includes(plan.id))

export default addKeyword(EVENTS.WELCOME)
    .addAnswer(
        'Hi! Pro is $29/month and Starter is $9/month. Which one do you want?',
        { capture: true },
        async (ctx, { state, fallBack }) => {
            const plan = findPlan(ctx.body)
            if (!plan) return fallBack('Write "pro" or "starter".')
            await state.update({ plan })
        }
    )
    .addAnswer('How many seats?', { capture: true }, async (ctx, { state, fallBack }) => {
        const seats = Number(ctx.body.replace(/[^\d]/g, ''))
        if (!seats) return fallBack('Write a number, for example 3.')
        await state.update({ seats })
    })
    .addAnswer('Confirm with "yes".', { capture: true }, async (ctx, { state, flowDynamic, endFlow }) => {
        if (!/^y(es)?$/i.test(ctx.body.trim())) return endFlow('Order cancelled. Write any time to start again.')
        const { plan, seats } = state.getMyState()
        await flowDynamic(`${seats} x ${plan.name} = ${plan.price * seats}/month. I will send the invoice link.`)
    })
```

Un catálogo en código sustituye a la cadena de nodos wait. `capture` mantiene cada respuesta en el mismo flow, `fallBack` repregunta si la cantidad no es un número y `state` lleva la línea hasta el total.

### Assistant for text and voice notes

- **Archivo:** `flows/assistant.flow.ts`
- **Documentación:** /events#received-voice-note

Una nota de voz se transcribe y pasa por el mismo flow que el texto, así los recordatorios caen en una sola lista.

**Implementación en BuilderBot:**

```ts
import { readFile } from 'node:fs/promises'
import { EVENTS, addKeyword } from '@builderbot/bot'

const transcribe = async (filePath: string) => {
    const audio = await readFile(filePath)
    const form = new FormData()
    form.append('file', new Blob([audio]), 'audio.ogg')
    form.append('model', 'whisper-1')
    const res = await fetch('https://api.openai.com/v1/audio/transcriptions', {
        method: 'POST',
        headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}` },
        body: form,
    })
    const data = await res.json()
    return data.text as string
}

/** One place for typed text and for transcripts. */
const remember = async (text: string, state: any, flowDynamic: any) => {
    const reminder = /remind|recu[eé]rd|lembr/i.exec(text)
    if (!reminder) return flowDynamic('Tell me "remind me to ..." and I will keep it.')
    const list = state.get('reminders') ?? []
    await state.update({ reminders: [...list, text] })
    return flowDynamic(`Saved. You have ${list.length + 1} reminder${list.length ? 's' : ''}.`)
}

const voiceFlow = addKeyword(EVENTS.VOICE_NOTE).addAction(async (ctx, { provider, state, flowDynamic }) => {
    const filePath = await provider.saveFile(ctx, { path: './tmp' })
    const text = await transcribe(filePath)
    await flowDynamic(`I heard: "${text}"`)
    await remember(text, state, flowDynamic)
})

const textFlow = addKeyword(EVENTS.WELCOME).addAction(async (ctx, { state, flowDynamic }) => {
    await remember(ctx.body, state, flowDynamic)
})

export default [voiceFlow, textFlow]
```

`EVENTS.VOICE_NOTE` está separado de las imágenes a propósito. Guarda el archivo, mándalo a Whisper y pasa la transcripción a la misma función que lee `ctx.body`. Los recordatorios van a `state`, por contacto.

### Summarize any link in the chat

- **Archivo:** `flows/summarize.flow.ts`
- **Documentación:** /add-functions#regex

Envías una URL y recibes cinco puntos. Cuando la página no carga, el bot lo dice en lugar de quedarse mudo.

**Implementación en BuilderBot:**

```ts
import { addKeyword } from '@builderbot/bot'

const REGEX_URL = '/(https?:\\/\\/[^\\s]+)/g'

const stripHtml = (html: string) =>
    html
        .replace(/<script[\s\S]*?<\/script>/gi, ' ')
        .replace(/<style[\s\S]*?<\/style>/gi, ' ')
        .replace(/<[^>]+>/g, ' ')
        .replace(/\s+/g, ' ')
        .trim()
        .slice(0, 8000)

export default addKeyword(REGEX_URL, { regex: true }).addAction(async (ctx, { flowDynamic }) => {
    const res = await fetch(ctx.body)
    if (!res.ok) return flowDynamic(`I could not open that page (HTTP ${res.status}).`)

    const page = stripHtml(await res.text())
    if (page.length < 200) return flowDynamic('That page has almost no text. Try another link.')

    const answer = await (async () => {
        const res = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
        },
        body: JSON.stringify({ model: 'gpt-4o-mini', messages: [
            { role: 'system', content: 'Summarize in 5 short bullets for WhatsApp. No intro.' },
            { role: 'user', content: page },
        ] }),
    })
    const data = await res.json()
    return data.choices?.[0]?.message?.content ?? 'I could not get an answer. Try again in a moment.'
    })()
    await flowDynamic(answer)
})
```

Un keyword con regex captura el enlace sin un comando. Quita scripts y estilos antes del prompt, limita el texto y, si el fetch falla, responde con el estado HTTP.

### Find leads and draft the first message

- **Archivo:** `flows/leads.flow.ts`
- **Documentación:** /methods#state

Buscas nicho y ciudad, guardas la lista y redactas el primer mensaje de WhatsApp para el lead que elijas.

**Implementación en BuilderBot:**

```ts
import { addKeyword } from '@builderbot/bot'

type Lead = { name: string; phone?: string; address?: string }

const searchMaps = async (query: string): Promise<Lead[]> => {
    const url = `https://serpapi.com/search.json?engine=google_maps&q=${encodeURIComponent(query)}&api_key=${process.env.SERPAPI_KEY}`
    const data = await (await fetch(url)).json()
    return (data.local_results ?? []).slice(0, 8).map((item: any) => ({
        name: item.title,
        phone: item.phone,
        address: item.address,
    }))
}

export default addKeyword(['leads', 'prospectos'])
    .addAnswer('Niche and city, for example "dentists in Madrid".', { capture: true }, async (ctx, { state, flowDynamic, endFlow }) => {
        const leads = await searchMaps(ctx.body)
        if (!leads.length) return endFlow('No results. Try a broader search.')
        await state.update({ leads })
        const lines = leads.map((lead, i) => `${i + 1}. ${lead.name} · ${lead.phone ?? 'no phone'}`)
        await flowDynamic(`${leads.length} leads:\n${lines.join('\n')}\n\nReply with a number to draft the first message.`)
    })
    .addAnswer('Waiting for the lead number.', { capture: true }, async (ctx, { state, flowDynamic, fallBack }) => {
        const { leads } = state.getMyState() as { leads: Lead[] }
        const index = Number(ctx.body) - 1
        const lead = leads[index]
        if (!lead) return fallBack(`Write a number between 1 and ${leads.length}.`)
        await flowDynamic(
            `Draft for ${lead.name}:\nHi, I help clinics get more bookings on WhatsApp. Open to a 10 minute call this week?`
        )
    })
```

Buscas y luego `capture` el número del lead. El borrador usa el nombre del negocio que está en `state`, así el mensaje no es genérico. Enviarlo queda como paso aparte: lo revisas antes de que salga.

### Ask your sales data in the chat

- **Archivo:** `flows/analyst.flow.ts`
- **Documentación:** /add-functions#add-action

El cliente pregunta "¿cuánto vendimos en octubre?" y el bot responde con tus filas, citando los números que usó.

**Implementación en BuilderBot:**

```ts
import { EVENTS, addKeyword } from '@builderbot/bot'

// Replace with the query you actually want to expose. Never pass a raw SQL string from the chat.
const ROWS = [
    { month: 'october', customer: 'ACME', total: 1200 },
    { month: 'october', customer: 'North', total: 800 },
    { month: 'november', customer: 'ACME', total: 1500 },
]

export default addKeyword(EVENTS.WELCOME).addAction(async (ctx, { flowDynamic }) => {
    const table = ROWS.map((row) => `${row.month} | ${row.customer} | ${row.total}`).join('\n')
    const answer = await (async () => {
        const res = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
        },
        body: JSON.stringify({ model: 'gpt-4o-mini', messages: [
            { role: 'system', content: `Answer only from this table (month | customer | total). If it is not there, say so.\n${table}` },
            { role: 'user', content: ctx.body },
        ] }),
    })
    const data = await res.json()
    return data.choices?.[0]?.message?.content ?? 'I could not get an answer. Try again in a moment.'
    })()
    await flowDynamic(answer)
})
```

No le pases al modelo una conexión a la base de datos. Carga las filas que sí puedes enseñar, mételas en el prompt y dile que responda solo con esa tabla. El mismo flow sirve si la consulta la haces tú.

### Questions about a PDF the customer sends

- **Archivo:** `flows/pdf.flow.ts`
- **Documentación:** /events#received-document

El cliente envía un PDF y luego pregunta sobre él. El bot se niega a responder con algo que no esté en el archivo.

**Implementación en BuilderBot:**

```ts
import { readFile } from 'node:fs/promises'
import { PDFParse } from 'pdf-parse'
import { EVENTS, addKeyword } from '@builderbot/bot'

export default addKeyword(EVENTS.DOCUMENT)
    .addAction(async (ctx, { provider, state, flowDynamic }) => {
        const filePath = await provider.saveFile(ctx, { path: './tmp' })
        const parser = new PDFParse({ data: await readFile(filePath) })
        const { text } = await parser.getText()
        await parser.destroy()

        if (!text.trim()) return flowDynamic('I could not read text in that PDF.')
        await state.update({ doc: text.slice(0, 12000) })
        await flowDynamic('Got it. Ask me about the document.')
    })
    .addAnswer('Any other question?', { capture: true }, async (ctx, { state, flowDynamic }) => {
        const doc = state.get('doc') as string
        const answer = await (async () => {
            const res = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
        },
        body: JSON.stringify({ model: 'gpt-4o-mini', messages: [
                { role: 'system', content: `Answer only with this document. If it is not in the text, say you don't know.\n${doc}` },
                { role: 'user', content: ctx.body },
            ] }),
    })
    const data = await res.json()
    return data.choices?.[0]?.message?.content ?? 'I could not get an answer. Try again in a moment.'
        })()
        await flowDynamic(answer)
    })
```

`EVENTS.DOCUMENT` más `provider.saveFile` te dan el archivo. `pdf-parse` extrae el texto a `state`. Si pasa de unas páginas, trocéalo y recupera; meter el archivo entero en el prompt es la versión corta.

### Support bot that hands the chat to a person

- **Archivo:** `flows/support.flow.ts`
- **Documentación:** /showcases/forward-conversation-to-human

Responde la FAQ y, en cuanto el cliente pide una persona, el bot deja de hablarle y avisa a tu equipo.

**Implementación en BuilderBot:**

```ts
import { EVENTS, addKeyword } from '@builderbot/bot'

const HUMAN = /(human|agent|person|asesor|persona|atendente)/i
const FAQ = 'Returns: 30 days with the receipt. Shipping: 24 to 72 hours inside the country.'

const alertTeam = async (from: string, text: string) => {
    await fetch(process.env.SLACK_WEBHOOK_URL!, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ text: `${from} wants a person: ${text}` }),
    })
}

export const humanFlow = addKeyword(EVENTS.ACTION).addAnswer(
    'I am passing you to a person. Write your message and they will reply here.',
    { capture: true },
    async (ctx, { blacklist, flowDynamic }) => {
        await alertTeam(ctx.from, ctx.body)
        blacklist.add(ctx.from)
        await flowDynamic('Done. I will stay quiet in this chat until the team sends you back.')
    }
)

const supportFlow = addKeyword(EVENTS.WELCOME).addAction(async (ctx, { gotoFlow, flowDynamic }) => {
    if (HUMAN.test(ctx.body)) return gotoFlow(humanFlow)
    const answer = await (async () => {
        const res = await fetch('https://api.openai.com/v1/chat/completions', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
        },
        body: JSON.stringify({ model: 'gpt-4o-mini', messages: [
            { role: 'system', content: 'Answer only from this FAQ. If it is not covered, say you will pass them to a person. FAQ: ' + FAQ },
            { role: 'user', content: ctx.body },
        ] }),
    })
    const data = await res.json()
    return data.choices?.[0]?.message?.content ?? 'I could not get an answer. Try again in a moment.'
    })()
    await flowDynamic(answer)
})

export default [supportFlow, humanFlow]
```

Detecta el handoff antes de llamar al modelo, haz `gotoFlow` a un flow que avisa a tu equipo y luego `blacklist.add(ctx.from)`. Mientras el número está en mute el bot sigue respondiendo al resto. Escribe "unmute" desde el chat de admin para devolverle el bot.

### Book a meeting from the chat

- **Archivo:** `flows/meeting.flow.ts`
- **Documentación:** /methods#fall-back

Ofreces los huecos que de verdad tienes, aceptas solo uno de ellos y reservas. Un typo vuelve a preguntar en lugar de reservar la hora equivocada.

**Implementación en BuilderBot:**

```ts
import { addKeyword } from '@builderbot/bot'

const SLOTS = ['monday 10:00', 'tuesday 16:00', 'wednesday 09:30']

export default addKeyword(['meeting', 'cita', 'agenda'])
    .addAnswer(
        `I can do ${SLOTS.join(', ')}. Which one?`,
        { capture: true },
        async (ctx, { state, fallBack }) => {
            const picked = SLOTS.find((slot) => ctx.body.toLowerCase().includes(slot.split(' ')[0]))
            if (!picked) return fallBack('Write the day: monday, tuesday or wednesday.')
            await state.update({ picked })
        }
    )
    .addAnswer('Your email for the invite?', { capture: true }, async (ctx, { state, fallBack }) => {
        if (!ctx.body.includes('@')) return fallBack('That does not look like an email.')
        await state.update({ email: ctx.body.trim() })
    })
    .addAction(async (ctx, { state, flowDynamic }) => {
        const { picked, email } = state.getMyState()
        await fetch(process.env.CALENDAR_WEBHOOK_URL!, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ slot: picked, email, from: ctx.from }),
        })
        await flowDynamic(`Booked ${picked}. The invite goes to ${email}.`)
    })
```

Dale al modelo una lista real, no "sugiere unas horas". Empareja el día en minúsculas, `fallBack` cuando no coincide nada y solo entonces haz POST al calendario.

### One inbox for text, voice, images and PDFs

- **Archivo:** `flows/inbox.flow.ts`
- **Documentación:** /events

Cada tipo de mensaje tiene su evento, y el bot recuerda el último archivo para que el siguiente texto pueda referirse a él.

**Implementación en BuilderBot:**

```ts
import { EVENTS, addKeyword } from '@builderbot/bot'

const note = (label: string) => async (ctx: any, { provider, state, flowDynamic }: any) => {
    const file = await provider.saveFile(ctx, { path: './tmp' })
    await state.update({ last: `${label}: ${file}` })
    await flowDynamic(`Saved the ${label}. Ask me "what did I send?" any time.`)
}

const textFlow = addKeyword(EVENTS.WELCOME).addAction(async (ctx, { state, flowDynamic }) => {
    if (!/what did i send|qu[eé] envi|o que eu enviei/i.test(ctx.body)) {
        return flowDynamic('Send a voice note, an image or a PDF. I keep the last one.')
    }
    const last = state.get('last')
    await flowDynamic(last ? `Last file: ${last}` : 'Nothing yet.')
})

export default [
    textFlow,
    addKeyword(EVENTS.VOICE_NOTE).addAction(note('voice note')),
    addKeyword(EVENTS.MEDIA).addAction(note('image')),
    addKeyword(EVENTS.DOCUMENT).addAction(note('pdf')),
]

```

No trates una nota de voz como una imagen. `EVENTS.VOICE_NOTE`, `EVENTS.MEDIA` y `EVENTS.DOCUMENT` son flows distintos; todos escriben `state.last`, y `EVENTS.WELCOME` lo lee cuando el cliente pregunta "¿qué envié?".

## Qué tienen en común

- **Un archivo por plantilla.** Lo pones en `src/flows` y lo importas en `app.ts`. Sin nodos que conectar, sin pasos escondidos.
- **El camino infeliz está escrito.** Si la cantidad no es un número, el enlace no carga o el cliente pide una persona, el bot responde algo útil en lugar de quedarse mudo.
- **Todas acaban igual:** `addKeyword` + `addAnswer({ capture: true })` + `addAction`, los cuatro [métodos](/methods) que cubre esta documentación. Lo que cambia es el [state](/methods#state), los [eventos](/events) y la llamada a tu API.

## Convertir una tarjeta en un bot que corre

```bash (pnpm)
pnpm create builderbot@latest
```

```bash (npm)
npm create builderbot@latest
```

Elige `baileys` como provider y `memory` como base de datos, luego copia el flow de la tarjeta en `src/flows` e impórtalo en `app.ts`. Si necesitas persistencia, cambia `MemoryDB` por [Mongo, MySQL o Postgres](/databases) sin tocar el flow.

> **NOTE:**
> La tarjeta muestra la versión que llama a la red. La demo en vivo es el mismo flow con las llamadas sustituidas por datos fijos, y por eso contesta las mismas preguntas sin claves.

## ¿Tienes una plantilla que nos falta?

Si construiste algo que resuelve un problema real y quieres que aparezca aquí, abre un PR en el [repo de documentación](https://github.com/codigoencasa/documentation) o compártela en el Discord. Revisamos dos cosas: que funcione con la versión actual de `@builderbot/bot` y que explique el flow, no solo el objetivo.
