# Conectar con Grokbot (/grok)



## Qué vas a armar [#qué-vas-a-armar]

Un bot pequeño que hace cuatro cosas:

1. Recibe en tu webhook los mensajes que llegan a Pontiun.
2. Valida el header `Authorization`.
3. Le pide la respuesta a Grok.
4. La envía de vuelta por la API de Pontiun.

```text
Contacto → Meta → Pontiun ──POST + Authorization──▶ tu bot ──▶ Grok (xAI)
                     ▲                                 │
                     └──── POST /api/meta/…/send ◀─────┘
```

Grok no recibe webhooks directamente, así que tu bot hace de puente.

## Antes de empezar [#antes-de-empezar]

* Una conexión activa en **Conexiones** (Messenger, Instagram o WhatsApp).
* Una API key de Pontiun (`pk_live_…`), creada en **Ajustes → API keys**.
* Una API key de xAI, creada en [console.x.ai](https://console.x.ai).
* Un servidor con URL `https` pública. Para probar en local sirve `ngrok http 3000`.
* Node.js 18 o superior.

## 1. El bot [#1-el-bot]

Guarda este archivo como `bot.mjs`. No necesita dependencias.

```js title="bot.mjs"
import { createServer } from "node:http"
import { timingSafeEqual } from "node:crypto"

const { PONTIUN_API_KEY, XAI_API_KEY, BOT_TOKEN } = process.env
const XAI_MODEL = process.env.XAI_MODEL ?? "grok-4.7"

const SEND_PATH = {
  messenger: "/api/meta/send",
  instagram: "/api/meta/instagram/send",
  whatsapp: "/api/meta/whatsapp/send",
}
// Messenger y WhatsApp cuentan caracteres; Instagram, bytes UTF-8.
const LIMIT = { messenger: 2000, instagram: 1000, whatsapp: 4096 }

const seen = new Set()

createServer(async (req, res) => {
  if (req.method !== "POST" || req.url !== "/pontiun") {
    return res.writeHead(404).end()
  }
  if (!sameToken(req.headers.authorization, `Bearer ${BOT_TOKEN}`)) {
    return res.writeHead(401).end()
  }

  let body = ""
  for await (const chunk of req) body += chunk
  // Pontiun espera un 2xx en menos de 5 s. Contesta primero y trabaja después.
  res.writeHead(200).end()

  try {
    const event = JSON.parse(body)
    const eventId = req.headers["resender-event-id"] ?? event.message?.id
    if (event.type !== "message" || !event.message.text) return
    if (seen.has(eventId)) return // un reintento del mismo evento
    seen.add(eventId)

    const reply = await askGrok(event.message.text)
    await sendReply(event, reply, eventId)
  } catch (error) {
    console.error(error)
  }
}).listen(process.env.PORT ?? 3000)

async function askGrok(text) {
  const res = await fetch("https://api.x.ai/v1/responses", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${XAI_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      model: XAI_MODEL,
      input: [
        {
          role: "system",
          content:
            "Eres el asistente de atención de la tienda. Responde en español, breve y amable.",
        },
        { role: "user", content: text },
      ],
    }),
  })
  if (!res.ok) throw new Error(`xAI ${res.status}: ${await res.text()}`)
  const data = await res.json()
  return data.output
    .filter((item) => item.type === "message")
    .flatMap((item) => item.content)
    .map((part) => part.text ?? "")
    .join("")
}

async function sendReply(event, reply, eventId) {
  const channel = event.page.channel
  const res = await fetch(`https://pontiun.com${SEND_PATH[channel]}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${PONTIUN_API_KEY}`,
      "Content-Type": "application/json",
      // Obligatoria en WhatsApp. En los tres canales evita mandar dos veces la misma respuesta.
      "Idempotency-Key": `grok-${eventId}`,
    },
    body: JSON.stringify({
      conversationId: event.conversation.id,
      reply: fit(reply, LIMIT[channel]),
    }),
  })
  if (!res.ok) throw new Error(`Pontiun ${res.status}: ${await res.text()}`)
}

function fit(text, limit) {
  let out = text.slice(0, limit)
  while (Buffer.byteLength(out) > limit) out = out.slice(0, -1)
  return out
}

function sameToken(received = "", expected) {
  const a = Buffer.from(received)
  const b = Buffer.from(expected)
  return a.length === b.length && timingSafeEqual(a, b)
}
```

Arráncalo con tus tres secretos. `BOT_TOKEN` lo inventas tú: es la clave que Pontiun le va a mandar a tu bot.

```bash
export PONTIUN_API_KEY=pk_live_<secreto>
export XAI_API_KEY=xai-<secreto>
export BOT_TOKEN=$(openssl rand -hex 24)
node bot.mjs
```

<Callout title="Necesita un servidor que siga vivo">
  El bot responde `200` y después llama a Grok. Una función serverless que se congela al devolver la respuesta cortaría ese trabajo a la mitad. Usa un proceso que quede corriendo, como Railway, Render, Fly.io o un VPS.
</Callout>

## 2. Configúralo en Pontiun [#2-configúralo-en-pontiun]

1. Abre **Conexiones** y despliega la configuración de tu conexión.
2. En **Webhook URL** pega `https://tu-bot.example.com/pontiun` y pulsa **Guardar**. Si aparece el secreto de firma (`whsec_…`), guárdalo; este tutorial no lo usa.
3. En **Headers personalizados**, escribe `Authorization` como nombre y `Bearer <tu BOT_TOKEN>` como valor. Pulsa **Agregar**.

El valor queda guardado cifrado y no se vuelve a mostrar. Para cambiarlo, agrégalo otra vez con el mismo nombre.

Si prefieres hacerlo por API, todo cabe en un solo [PATCH](/api/updateConnectionWebhook):

```bash
curl -X PATCH https://pontiun.com/api/meta/connections/<connection-id> \
  -H "Authorization: Bearer pk_live_<secreto>" \
  -H "Content-Type: application/json" \
  -d '{
    "webhookUrl": "https://tu-bot.example.com/pontiun",
    "webhookHeaders": { "Authorization": "Bearer <tu BOT_TOKEN>" }
  }'
```

El `connection-id` lo obtienes con [Listar conexiones](/api/listConnections) o del campo `page.id` de cualquier evento.

## 3. Pruébalo [#3-pruébalo]

Escribe a tu página, cuenta o número desde otro perfil. En unos segundos debería llegarte la respuesta de Grok. En **Logs** de Pontiun ves cada entrega al webhook con su código HTTP.

## Si algo falla [#si-algo-falla]

| Síntoma                        | Causa                                                    | Qué hacer                                                                          |
| ------------------------------ | -------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| La entrega al webhook da `401` | El header no coincide con `BOT_TOKEN`                    | Vuelve a agregar `Authorization` en la conexión. El valor lleva `Bearer ` delante. |
| La entrega da timeout          | El bot espera a Grok antes de contestar                  | Responde `200` primero, como en el ejemplo.                                        |
| El envío da `409` en WhatsApp  | Pasaron más de 24 h desde el último mensaje del contacto | Usa una [plantilla](/api/sendWhatsappTemplate).                                    |
| El envío da `400` en Instagram | El texto supera los 1000 bytes                           | `fit()` lo recorta. También puedes pedirle a Grok respuestas más cortas.           |

Un `4xx` de tu webhook no se reintenta: los mensajes que fallaron mientras el header estaba mal no vuelven a llegar.

<Cards>
  <Card title="Cambiar el webhook de una conexión" href="/api/updateConnectionWebhook" description="URL y headers propios por API." />

  <Card title="Evento de Messenger" href="/api/messengerEvents" description="Payload, cabeceras y reintentos." />

  <Card title="Enviar mensaje de WhatsApp" href="/api/sendWhatsappMessage" description="Idempotency-Key y ventana de 24 horas." />
</Cards>
