npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@alexiiispc/botflow

v0.5.3

Published

SDK oficial de BotFlow para crear chatbots e integrar funciones backend desde Node.js.

Downloads

1,438

Readme

BotFlow SDK

SDK oficial para crear chatbots y conectar funciones backend con BotFlow desde Node.js.

Instalación

npm install @alexiiispc/botflow

Requiere Node.js 20 o posterior.

Plan necesario

El dashboard incluye 1 chatbot visual gratis. Para generar credenciales, conectar funciones o crear chatbots desde código se necesita el plan Pro (S/ 49 al mes), que incluye hasta 10 chatbots. El propietario de la plataforma también puede conceder acceso manual al SDK sin activar una suscripción.

El precio y el cupo se configuran en el servidor con PRO_PLAN_PRICE_PEN y PRO_PLAN_BOT_LIMIT, por lo que pueden cambiar sin publicar otra versión de la librería.

Configuración

Genera una credencial desde Funciones en el dashboard y guárdala como variable de entorno. Las credenciales nunca deben incluirse en el navegador ni en el repositorio.

BOTFLOW_TOKEN=bf_live_TU_CREDENCIAL
import { createBot } from '@alexiiispc/botflow';

const bot = createBot({
  token: process.env.BOTFLOW_TOKEN,
  apiUrl: 'https://botflow.alexispc.site/api'
});

Registrar una función

bot.function('buscarCliente', {
  name: 'Buscar cliente',
  description: 'Consulta un cliente por documento',
  parameters: {
    dni: { type: 'string', required: true }
  },
  async handler({ dni }, context) {
    const cliente = await consultarCliente(dni);
    context.setVariable('clienteEncontrado', Boolean(cliente));
    const canal = context.getVariable('canal') || 'web';
    return { success: true, data: cliente };
  }
});

await bot.start();

El proceso debe permanecer activo para recibir ejecuciones. En producción puedes administrarlo con PM2, systemd o el servicio de procesos de tu proveedor.

Crear un chatbot desde código

bot.chatbot('soporte-web', {
  projectId: process.env.BOTFLOW_PROJECT_ID,
  name: 'Soporte web',
  webhook: {
    payloadVariable: 'evento_whatsapp',
    sessionPath: 'data.key.remoteJid',
    sessionVariable: 'whatsapp_id',
    response: {
      enabled: true,
      method: 'POST',
      url: 'https://evolution.ejemplo.com/message/sendText/mi-instancia',
      headers: { apikey: process.env.EVOLUTION_API_KEY },
      body: {
        number: '{{response.sessionId}}',
        text: '{{response.fallbackText}}',
        messageType: '{{response.messageType}}',
        buttons: '{{response.buttons}}'
      }
    }
  }
}, (flow) => {
  flow
    .start()
    .message('bienvenida', 'Hola, ¿cómo te llamas?')
    .question('nombre', 'Escribe tu nombre.', { variable: 'nombre' })
    .image('producto', 'https://cdn.ejemplo.com/producto.jpg', {
      alt: 'Fotografía del producto',
      caption: 'Este producto es para {{variables.nombre}}.'
    })
    .video('tutorial', 'https://cdn.ejemplo.com/tutorial.mp4', {
      poster: 'https://cdn.ejemplo.com/portada.jpg',
      caption: 'Mira este tutorial breve.'
    })
    .file('manual', 'https://cdn.ejemplo.com/manual.pdf', {
      fileName: 'Manual.pdf',
      mimeType: 'application/pdf',
      caption: 'Descarga el manual completo.'
    })
    .end('despedida', 'Gracias, {{variables.nombre}}.');
});

await bot.start();

const deployment = bot.getDeployment('soporte-web');
console.log(deployment.botId);

Webhook entrante por defecto

En bot.chatbot() usa webhook.payloadVariable, webhook.sessionPath y webhook.sessionVariable para publicar esta configuración junto con el flujo.

Cada bot publicado dispone de POST /api/v1/public/bots/{botId}/webhook sin agregar un nodo. Desde el editor se configura la variable del payload, la ruta del JSON usada como ID de sesión y la variable que guarda ese ID. webhookListener() se mantiene solamente para compatibilidad con flujos existentes.

Devolución webhook automática

Activa webhook.response.enabled para enviar automáticamente los mensajes producidos por el flujo cuando la entrada fue un webhook. Se configuran una sola vez el método, URL, timeout, query parameters, headers y body; no necesitas repetir un nodo HTTP en cada rama.

Esta devolución es exclusiva de entradas recibidas por /webhook: no se ejecuta para el widget web, mensajes de página ni botones. En flujos visuales se configura desde los dos acordeones y no requiere nodo adicional. En chatbots code-first debes declararla en webhook.response como en el ejemplo anterior.

Contexto automático disponible en URL, headers y body, sin guardar cada mensaje en una variable:

  • {{response}}: objeto completo de la respuesta automática.
  • {{response.text}}: último texto generado por el bot.
  • {{response.fallbackText}}: texto principal y, cuando corresponde, opciones numeradas para canales sin botones nativos.
  • {{response.messageType}}: tipo del último mensaje (text, buttons, image, video o file).
  • {{response.buttons}}: opciones del último mensaje de botones como objetos { id, label, value }.
  • {{response.messages}}: todos los mensajes generados en la ejecución.
  • {{response.count}}: cantidad de mensajes generados.
  • {{response.sessionId}}: identificador de la sesión entrante.
  • {{response.conversationId}}: identificador de la conversación.
  • {{response.status}}: estado final del flujo.
  • {{response.input}}: payload recibido por el webhook.
  • cualquier variable normal del flujo.

El alias anterior variables.webhook_response continúa disponible por compatibilidad.

Webhook de escucha (compatibilidad)

bot.chatbot('webhook-simple-loop', {
  projectId: process.env.BOTFLOW_PROJECT_ID,
  name: 'Webhook simple loop'
}, (flow) => {
  flow
    .start()
    .webhookListener('escucha_webhook', {
      variable: 'payload_webhook'
    })
    .message('respuesta', 'Recibí: {{variables.payload_webhook.message}}');
});

El bot se crea o actualiza dentro del proyecto indicado. El servidor valida el plan y el cupo tanto al conectar como al desplegar. Si no existe acceso, bot.start() rechaza la conexión con el código CODE_PLAN_REQUIRED.

try {
  await bot.start();
} catch (error) {
  if (error.code === 'CODE_PLAN_REQUIRED') {
    console.error('Activa el plan Pro o solicita autorización para usar el SDK.');
  }
  throw error;
}

API principal

  • createBot(options): crea el cliente.
  • bot.function(key, definition): registra una función backend.
  • bot.chatbot(key, options, configure): define y publica un flujo mediante código.
  • flow.webhookListener(key, options): espera un webhook entrante y guarda su payload en una variable.
  • flow.image(key, url, options): envía una imagen con texto alternativo y descripción.
  • flow.video(key, url, options): envía un video con portada opcional.
  • flow.file(key, url, options): comparte un archivo descargable.
  • flow.connect(source, target, { branch }): crea una conexión manual; usa branch: true o branch: false al salir de una condición.
  • bot.start(): conecta, autentica y sincroniza el proceso.
  • bot.getDeployment(key): devuelve el identificador del bot actualizado.
  • bot.stop(): cierra la conexión de forma controlada.

context.getVariable() y context.setVariable() funcionan dentro de los handlers y sus valores se devuelven al flujo en el resultado de la función. Eso permite guardar estados intermedios sin depender de variables globales.

Los métodos que crean bloques aceptan autoConnect: false dentro de options cuando necesitas evitar la conexión automática con el bloque anterior. Esto es especialmente útil para construir las dos ramas de una condición:

flow
  .start()
  .condition('es_cliente', {
    variable: 'cliente_activo',
    operator: 'equals',
    value: true
  });

flow.message('ruta_si', 'Bienvenido de nuevo.', { autoConnect: false });
flow.message('ruta_no', 'Vamos a crear tu cuenta.', { autoConnect: false });
flow.connect('es_cliente', 'ruta_si', { branch: true });
flow.connect('es_cliente', 'ruta_no', { branch: false });

La documentación completa está disponible dentro del dashboard de BotFlow.