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

kommo-openai-service

v1.0.0

Published

Servicio reutilizable para integrar OpenAI con Kommo CRM

Downloads

13

Readme

Kommo OpenAI Service

Paquete npm reutilizable para integrar OpenAI con Kommo CRM. Diseñado para ser flexible y configurable según las necesidades de cada proyecto.

Instalación

npm install kommo-openai-service

Características

  • ✅ Integración con OpenAI Responses API
  • ✅ Gestión automática de tokens de Kommo
  • ✅ Conversión de Markdown a formato WhatsApp
  • ✅ Gestión de conversaciones con contexto
  • ✅ Actualización de campos personalizados en Kommo
  • ✅ Lanzamiento automático de salesbots
  • ✅ Configuración flexible de field IDs y bot IDs
  • ✅ Procesamiento de formularios

Configuración

Configuración Básica

require('dotenv').config();
const { KommoOpenAIService } = require('kommo-openai-service');

// Funciones de autenticación (debes implementarlas según tu proyecto)
const { authenticate, readTokenFromDB } = require('./tu-auth-service');

// Crear instancia del servicio
const service = new KommoOpenAIService({
  openaiApiKey: process.env.OPENAI_API_KEY,
  getToken: async () => {
    const domain = process.env.SUBDOMINIO;
    const tokenData = await readTokenFromDB(domain);
    return tokenData.access_token;
  },
  authenticate: authenticate
});

Configuración Personalizada

Puedes personalizar los field IDs, bot IDs y otras configuraciones:

const service = new KommoOpenAIService({
  openaiApiKey: process.env.OPENAI_API_KEY,
  getToken: getTokenFunction,
  authenticate: authenticateFunction,
  config: {
    fieldIds: {
      actionId: 4147726,           // Tu field_id para action_id
      iaTextResponse: 4147714,     // Tu field_id para respuesta IA
      conversationId: 4147600,     // Tu field_id para conversation_id
      clientMessage: 4147720,      // Tu field_id para mensaje del cliente
      
      // Campos de formulario (opcional)
      formNombre: 4203830,
      formPuntoVenta: 4203832,
      formUbicacion: 4203834,
      formProbadoProductos: 4203836,
    },
    salesbot: {
      botId: 102014,              // Tu bot_id
      entityType: 2               // 2 = Lead
    },
    kommo: {
      subdomain: process.env.SUBDOMINIO,
      apiVersion: 'v4'
    },
    openai: {
      model: 'gpt-4o',
      maxOutputTokens: 2048,
      promptVersion: '13'
    }
  }
});

Uso

Procesar Request de Webhook

async function handleWebhook(req, res) {
  try {
    // Extraer datos del request
    const data = await service.processRequestData(req);
    
    if (!data) {
      return res.status(400).json({ error: 'Invalid request data' });
    }

    console.log('Datos procesados:', {
      lead_id: data.lead_id,
      conversation_id: data.conversation_id,
      msj_client: data.msj_client
    });

    res.status(200).json({ success: true });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Internal server error' });
  }
}

Actualizar Campo Personalizado

async function updateLeadWithAIResponse(leadId, message, conversationId) {
  try {
    const result = await service.updateLeadCustomField(
      leadId,
      message,
      conversationId
    );
    
    console.log('Lead actualizado:', result);
    // También lanza automáticamente el salesbot
  } catch (error) {
    console.error('Error actualizando lead:', error);
  }
}

Lanzar Salesbot Manualmente

async function launchBot(leadId) {
  const token = await service.getToken();
  const subdomain = process.env.SUBDOMINIO;
  
  const result = await service.launchSalesbot(leadId, token, subdomain);
  console.log('Bot lanzado:', result);
}

Actualizar Action ID

// Transferir a asesor
await service.updateActionId('ASESOR', leadId);

// Marcar como proveedor
await service.updateActionId('PROVEEDOR', leadId);

Procesar Formulario de Venta

async function processForm(leadId) {
  const formData = {
    nombre: 'Juan Pérez',
    tiene_punto_venta: 'Sí',
    ubicacion: 'Ciudad de México',
    ha_probado_productos: 'No',
    timestamp: new Date().toISOString()
  };

  const result = await service.processFormVenta(formData, leadId);
  console.log('Formulario procesado:', result);
}

Gestión de Conversaciones

// Crear nueva conversación
const conversationId = await service.createdConversation();
console.log('Nueva conversación:', conversationId);

// Eliminar conversación
await service.deletedConversation(conversationId);

Utilidades

Transformar Markdown a WhatsApp

const { transformMarkdownToWhatsApp } = require('kommo-openai-service');

const markdown = '**Hola** _mundo_';
const whatsapp = transformMarkdownToWhatsApp(markdown);
console.log(whatsapp); // *Hola* _mundo_

Extraer Texto de Respuesta

const { extractTextFromResponse } = require('kommo-openai-service');

const response = await openai.responses.create({...});
const text = extractTextFromResponse(response);

Ejemplo Completo

require('dotenv').config();
const express = require('express');
const { KommoOpenAIService } = require('kommo-openai-service');
const { authenticate, readTokenFromDB } = require('./auth');

const app = express();
app.use(express.json());

// Inicializar servicio
const aiService = new KommoOpenAIService({
  openaiApiKey: process.env.OPENAI_API_KEY,
  getToken: async () => {
    const tokenData = await readTokenFromDB(process.env.SUBDOMINIO);
    return tokenData.access_token;
  },
  authenticate: authenticate,
  config: {
    fieldIds: {
      actionId: 4147726,
      iaTextResponse: 4147714,
      conversationId: 4147600,
      clientMessage: 4147720
    },
    salesbot: {
      botId: 102014
    },
    kommo: {
      subdomain: process.env.SUBDOMINIO
    }
  }
});

// Endpoint para webhook
app.post('/webhook/kommo', async (req, res) => {
  try {
    const data = await aiService.processRequestData(req);
    
    if (data) {
      // Aquí puedes procesar el mensaje con OpenAI
      // y luego actualizar el lead con la respuesta
      
      // Ejemplo:
      // const aiResponse = await procesarConOpenAI(data.msj_client);
      // await aiService.updateLeadCustomField(
      //   data.lead_id,
      //   aiResponse,
      //   data.conversation_id
      // );
    }
    
    res.status(200).json({ success: true });
  } catch (error) {
    console.error('Error:', error);
    res.status(500).json({ error: 'Error procesando webhook' });
  }
});

app.listen(3000, () => {
  console.log('Servidor ejecutándose en puerto 3000');
});

Configuración de Variables de Entorno

Crea un archivo .env con:

OPENAI_API_KEY=tu_openai_api_key
SUBDOMINIO=tu_subdominio_kommo
PROMPT_ID_IDENTIFICAR=tu_prompt_id
OPENAI_MODEL=gpt-4o

API Reference

Constructor

new KommoOpenAIService(options)

Parámetros:

  • openaiApiKey (string, requerido): API key de OpenAI
  • getToken (function, requerido): Función que retorna el token de Kommo
  • authenticate (function, requerido): Función para autenticar/refrescar token
  • config (object, opcional): Configuración personalizada

Métodos Principales

processRequestData(request)

Procesa datos de un webhook de Kommo.

Retorna: Promise<{msj_client, lead_id, conversation_id}>

updateLeadCustomField(lead_id, value, conversation_id)

Actualiza campo personalizado en un lead con la respuesta de la IA.

Retorna: Promise<{success, message}>

launchSalesbot(idLead, token, subdominio)

Lanza el salesbot configurado en Kommo.

Retorna: Promise<{success, data}>

updateActionId(action_id, lead_id)

Actualiza el campo action_id de un lead (ej: ASESOR, PROVEEDOR).

Retorna: Promise<{success, message}>

processFormVenta(formData, lead_id)

Procesa y guarda datos de un formulario de venta.

Retorna: Promise<{success, message, data}>

createdConversation()

Crea una nueva conversación y retorna su ID.

Retorna: Promise<string>

deletedConversation(conversation_id)

Elimina una conversación existente.

Retorna: Promise<void>

Soporte

Para soporte o preguntas, crea un issue en el repositorio.

Licencia

MIT