# Templates

> Templates completos do BuilderBot: um agente com ferramentas, vendas no WhatsApp com catálogo, perguntas sobre um PDF ou um link e suporte com passagem para uma pessoa. Um arquivo para colar, e roda no seu navegador.
>
> - **Canonical URL:** https://www.builderbot.app/pt/templates
> - **Documentation Index:** https://www.builderbot.app/llms.txt
> - **Full Corpus:** https://www.builderbot.app/llms-full.txt

Estes são os dez bots que as pessoas acabam construindo à mão. Um assistente que consulta um dado antes de responder, um bot de vendas com catálogo e total real, um bot que lê um PDF ou um link, e um bot de suporte que sabe quando passar o chat.

Cada um é um flow completo: o `state` que guarda, o passo que faz o trabalho e o que o bot diz quando o cliente responde algo que o caminho feliz não esperava. Clique em **Testar ao vivo** para falar com o mesmo flow no seu navegador — as chamadas de rede são substituídas por dados fixos, então você não precisa de chaves.

_Atualizado 2026-11-18._

### AI agent that can look things up

- **Arquivo:** `flows/agent.flow.ts`
- **Documentação:** /add-functions#add-action

Um chat com memória que pode buscar na web ou consultar um pedido antes de responder, em vez de inventar o dado.

**Implementação em 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)
})
```

Guarde os últimos turnos em `state`. O modelo responde, ou devolve `TOOL search …` / `TOOL order …`. Você executa essa chamada e pergunta de novo com o resultado. Uma volta basta para o WhatsApp.

### WhatsApp sales agent with a catalog

- **Arquivo:** `flows/sales.flow.ts`
- **Documentação:** /methods#state

Orça um preço, pergunta quantos assentos e só confirma o pedido quando a quantidade é um número real.

**Implementação em 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.`)
    })
```

Um catálogo no código substitui a corrente de nós wait. `capture` mantém cada resposta no mesmo flow, `fallBack` pergunta de novo se a quantidade não for um número e `state` leva a linha até o total.

### Assistant for text and voice notes

- **Arquivo:** `flows/assistant.flow.ts`
- **Documentação:** /events#received-voice-note

Uma nota de voz é transcrita e passa pelo mesmo flow do texto, então os lembretes caem numa lista só.

**Implementação em 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` é separado das imagens de propósito. Salve o arquivo, envie ao Whisper e passe a transcrição para a mesma função que lê `ctx.body`. Os lembretes vão para `state`, por contato.

### Summarize any link in the chat

- **Arquivo:** `flows/summarize.flow.ts`
- **Documentação:** /add-functions#regex

Você envia uma URL e recebe cinco pontos. Quando a página não carrega, o bot avisa em vez de ficar mudo.

**Implementação em 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)
})
```

Um keyword com regex captura o link sem um comando. Tire scripts e estilos antes do prompt, limite o texto e, se o fetch falhar, responda com o status HTTP.

### Find leads and draft the first message

- **Arquivo:** `flows/leads.flow.ts`
- **Documentação:** /methods#state

Você busca nicho e cidade, guarda a lista e redige a primeira mensagem de WhatsApp para o lead que escolher.

**Implementação em 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?`
        )
    })
```

Você busca e depois `capture` o número do lead. O rascunho usa o nome do negócio que está em `state`, então a mensagem não é genérica. O envio fica separado: você revisa antes de sair.

### Ask your sales data in the chat

- **Arquivo:** `flows/analyst.flow.ts`
- **Documentação:** /add-functions#add-action

O cliente pergunta "quanto vendemos em outubro?" e o bot responde com suas linhas, citando os números que usou.

**Implementação em 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)
})
```

Não passe ao modelo uma conexão com o banco. Carregue as linhas que você pode mostrar, coloque no prompt e diga para responder só com essa tabela. O mesmo flow serve se a consulta for sua.

### Questions about a PDF the customer sends

- **Arquivo:** `flows/pdf.flow.ts`
- **Documentação:** /events#received-document

O cliente envia um PDF e depois pergunta sobre ele. O bot se recusa a responder com algo que não esteja no arquivo.

**Implementação em 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` mais `provider.saveFile` entregam o arquivo. `pdf-parse` extrai o texto para `state`. Se passar de algumas páginas, fatie e recupere; colocar o arquivo inteiro no prompt é a versão curta.

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

- **Arquivo:** `flows/support.flow.ts`
- **Documentação:** /showcases/forward-conversation-to-human

Responde a FAQ e, quando o cliente pede uma pessoa, o bot para de falar com ele e avisa seu time.

**Implementação em 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]
```

Detecte o handoff antes de chamar o modelo, faça `gotoFlow` para um flow que avisa seu time e depois `blacklist.add(ctx.from)`. Enquanto o número está em mute o bot segue respondendo o resto. Escreva "unmute" no chat de admin para devolver o bot.

### Book a meeting from the chat

- **Arquivo:** `flows/meeting.flow.ts`
- **Documentação:** /methods#fall-back

Você oferece os horários que realmente tem, aceita só um deles e reserva. Um erro de digitação pergunta de novo em vez de reservar a hora errada.

**Implementação em 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}.`)
    })
```

Dê ao modelo uma lista real, não "sugira uns horários". Case o dia em minúsculas, `fallBack` quando nada coincidir e só então faça POST no calendário.

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

- **Arquivo:** `flows/inbox.flow.ts`
- **Documentação:** /events

Cada tipo de mensagem tem seu evento, e o bot lembra o último arquivo para o próximo texto poder se referir a ele.

**Implementação em 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')),
]

```

Não trate uma nota de voz como imagem. `EVENTS.VOICE_NOTE`, `EVENTS.MEDIA` e `EVENTS.DOCUMENT` são flows diferentes; todos escrevem `state.last`, e `EVENTS.WELCOME` lê isso quando o cliente pergunta "o que eu enviei?".

## O que eles têm em comum

- **Um arquivo por template.** Você coloca em `src/flows` e importa em `app.ts`. Sem nós para ligar, sem passos escondidos.
- **O caminho infeliz está escrito.** Se a quantidade não for um número, o link não carregar ou o cliente pedir uma pessoa, o bot responde algo útil em vez de ficar mudo.
- **Todos terminam igual:** `addKeyword` + `addAnswer({ capture: true })` + `addAction`, os quatro [métodos](/methods) que esta documentação cobre. O que muda é o [state](/methods#state), os [eventos](/events) e a chamada à sua API.

## Transformar um card em um bot rodando

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

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

Escolha `baileys` como provider e `memory` como banco de dados, depois copie o flow do card para `src/flows` e importe em `app.ts`. Se precisar de persistência, troque `MemoryDB` por [Mongo, MySQL ou Postgres](/databases) sem tocar no flow.

> **NOTE:**
> O card mostra a versão que chama a rede. A demo ao vivo é o mesmo flow com as chamadas substituídas por dados fixos, e por isso responde as mesmas perguntas sem chaves.

## Tem um template que falta aqui?

Se você construiu algo que resolve um problema real e quer que apareça aqui, abra um PR no [repositório da documentação](https://github.com/codigoencasa/documentation) ou compartilhe no Discord. Revisamos duas coisas: que funcione com a versão atual do `@builderbot/bot` e que explique o flow, não só o objetivo.
