### Install and Verify Jelou CLI Source: https://docs.jelou.ai/guides/functions/quickstart Installs the Jelou Command Line Interface globally using npm and verifies the installation by checking the CLI version. ```bash npm install -g @jelou/cli jelou --version ``` -------------------------------- ### Memory V2 Quick Start Example (JavaScript) Source: https://docs.jelou.ai/changelog Demonstrates the basic usage of the Memory V2 API for storing different data types. It shows how to set primitive values, JSON objects with a Time-To-Live (TTL), and files with specified expiry times and MIME types. This example requires the `$memory` object to be available in the environment. ```javascript // Primitivos $memory.set('idioma', 'es'); // JSON con TTL de 1 hora $memory.setJson('perfil', { nombre: 'María' }, 3600); // Archivos con TTL de 1 día await $memory.setFile('foto', base64Data, 86400, 'image/jpeg'); ``` -------------------------------- ### Run Jelou Function Locally Source: https://docs.jelou.ai/guides/functions/quickstart Starts the Jelou development server locally. The server automatically reloads when changes are made to the function files. ```bash jelou dev # ▸ Listening on http://localhost:3000 # ▸ Watching for changes... ``` -------------------------------- ### TypeScript: Using set/get vs setJson/getJson for session memory Source: https://docs.jelou.ai/guides/functions/memoria This TypeScript example demonstrates the difference between `set()`/`get()` for simple values and `setJson()`/`getJson()` for JSON objects in `ctx.memory`. `set()` and `get()` are suitable for strings, numbers, and booleans, while `setJson()` and `getJson()` handle complex data structures. ```typescript await ctx.memory.set("paso", "confirmacion", 3600); const paso = await ctx.memory.get("paso", "inicio"); await ctx.memory.setJson("carrito", { items: [], total: 0 }, 86400); const carrito = await ctx.memory.getJson("carrito", { items: [], total: 0 }); ``` -------------------------------- ### Key Rotation Example Source: https://docs.jelou.ai/guides/functions/autenticacion Demonstrates how to implement key rotation for your Jelou AI functions by configuring the function to accept multiple secrets simultaneously during the transition period. ```APIDOC ## POST /mi-funcion.fn.jelou.ai (with Key Rotation) ### Description This example shows how to configure your function to accept both an old and a new API token during a key rotation process. This allows clients to migrate to the new token at their own pace. ### Method POST ### Endpoint /mi-funcion.fn.jelou.ai ### Parameters #### Query Parameters None #### Request Body - **id** (string) - Required - An identifier passed to the function. ### Request Example ```bash curl -X POST https://mi-funcion.fn.jelou.ai \ -H "Authorization: Bearer nuevo-token-v2" \ -H "Content-Type: application/json" \ -d '{"id": "some-id"}' ``` ### Configuration Example ```typescript import { define, z } from "@jelou/functions"; export default define({ description: "API with key rotation", input: z.object({ id: z.string() }), auth: { secret: ["API_TOKEN", "API_TOKEN_OLD"] }, handler: async (input, ctx) => { return { id: input.id }; }, }); ``` ### Secret Management Example ```bash jelou secrets set mi-funcion API_TOKEN=nuevo-token-v2 jelou secrets set mi-funcion API_TOKEN_OLD=token-anterior-v1 ``` ### Response #### Success Response (200) - **id** (string) - The identifier returned by the function. #### Response Example ```json { "id": "some-id" } ``` ``` -------------------------------- ### Configure Secrets for Jelou Function Source: https://docs.jelou.ai/guides/functions/quickstart Sets environment-specific secrets for a Jelou Function before deployment. This example sets the `CRM_API_KEY` secret for the `consultar-cliente` function. ```bash jelou secrets set consultar-cliente CRM_API_KEY=YOUR_CRM_API_KEY # ✓ Set 1 secret ``` -------------------------------- ### Example Configuration for Pregunta Node Source: https://docs.jelou.ai/guides/nodos/pregunta This example demonstrates a basic configuration for the Pregunta node, setting the question text and the variable name to store the user's response. The user's answer will be accessible via the defined memory variable. ```text Texto: ¿Cuál es tu nombre? Guardar respuesta como: nombreUsuario ``` -------------------------------- ### Testing Authentication Contexts and Requests (TypeScript) Source: https://docs.jelou.ai/guides/functions/autenticacion Provides example tests for Jelou AI Functions using mock utilities. It demonstrates how to create mock authentication contexts and requests to verify that handlers receive authentication information correctly when tokens are valid or absent. ```typescript import { assertEquals } from "jsr:@std/assert"; import { createMockAuthContext, createMockAuthRequest, createMockContext, createMockRequest, } from "@jelou/functions/testing"; Deno.test("handler recibe auth cuando token es válido", async () => { const ctx = createMockAuthContext(); const req = createMockAuthRequest("mi-token-secreto", { query: "test" }); const result = await fn.handler({ query: "test" }, ctx, req); assertEquals(result.authenticated, true); }); Deno.test("handler sin auth retorna ctx.auth null", async () => { const ctx = createMockContext({ auth: null }); const req = createMockRequest({ query: "test" }); const result = await fn.handler({ query: "test" }, ctx, req); assertEquals(result.authenticated, undefined); }); ``` -------------------------------- ### Authenticate with Jelou CLI Source: https://docs.jelou.ai/guides/functions/quickstart Logs into the Jelou CLI using a personal access token. It also shows how to authenticate non-interactively in CI environments. ```bash jelou login # Paste your access token: **** # ✓ Logged in jelou login --token jfn_pat_tu_token ``` -------------------------------- ### Deploy Jelou Function to Production Source: https://docs.jelou.ai/guides/functions/quickstart Deploys the Jelou Function to the production environment. It confirms the deployment and provides the production URL for the function. ```bash jelou deploy # ▸ Files: index.ts (1.2 KB), jelou.json (98 B), deno.json (65 B) # ? Deploy consultar-cliente? (Y/n) y # ✓ Deployed to https://consultar-cliente.fn.jelou.ai ``` -------------------------------- ### Using the API Key Source: https://docs.jelou.ai/guides/datum/api-keys Instructions and examples for including your API key in HTTP requests to the Jelou.ai API. ```APIDOC ## Using the API Key ### Description To use the Jelou.ai API, include your API key in the `X-Api-Key` header of your HTTP requests. ### Method GET ### Endpoint `https://tu-instancia.jelou.cloud/api/collections/tu_coleccion/records` ### Parameters #### Request Headers * **X-Api-Key** (string) - Required - Your unique API key. * **Accept** (string) - Required - Specifies the desired response format, typically `application/json`. ### Request Example (cURL) ```bash curl -s -X GET 'https://tu-instancia.jelou.cloud/api/collections/tu_coleccion/records' \ -H 'X-Api-Key: YOUR_API_KEY' \ -H 'Accept: application/json' ``` ### Request Example (JavaScript) ```javascript const response = await fetch('https://tu-instancia.jelou.cloud/api/collections/tu_coleccion/records', { headers: { 'X-Api-Key': 'YOUR_API_KEY', 'Accept': 'application/json' } }); const data = await response.json(); ``` ### Request Example (Python) ```python import requests response = requests.get( 'https://tu-instancia.jelou.cloud/api/collections/tu_coleccion/records', headers={ 'X-Api-Key': 'YOUR_API_KEY', 'Accept': 'application/json' } ) data = response.json() ``` ### Response #### Success Response (200) * **data** (object) - The response data from the API. * **totalItems** (integer) - The total number of items returned. * **totalPages** (integer) - The total number of pages available. * **currentPage** (integer) - The current page number. * **perPage** (integer) - The number of items per page. * **field** (string) - Description of the field. #### Response Example ```json { "data": [ { "id": "record-id", "collectionId": "collection-id", "collectionName": "tu_coleccion", "created": "2023-10-27 10:00:00.123Z", "updated": "2023-10-27 10:00:00.123Z", "field": "example value" } ], "totalItems": 1, "totalPages": 1, "currentPage": 1, "perPage": 50 } ``` ``` -------------------------------- ### API Response Examples (JSON) Source: https://docs.jelou.ai/api/campanas/envio-masivo Illustrates successful and error responses from the Jelou.ai API for campaign sending. ```json { "message": ["Campaign has been created."], "status": "success" } ``` ```json { "message": ["Invalid CSV format"], "status": "failed" } ``` ```json { "message": "Authentication failed" } ``` ```json { "message": ["Template not found or not approved"], "status": "failed" } ``` -------------------------------- ### Dynamic Button Source Data - JSON Example Source: https://docs.jelou.ai/guides/nodos/botones Provides an example of the JSON structure for dynamic button source data. This array of objects represents options that can be dynamically rendered as buttons, each with its own properties. ```json [ { "id": "dep1", "nombre": "Ventas", "correo": "ventas@empresa.com" }, { "id": "dep2", "nombre": "Soporte", "correo": "soporte@empresa.com" }, { "id": "dep3", "nombre": "Facturación", "correo": "facturacion@empresa.com" } ] ``` -------------------------------- ### Text Input Example for Pregunta Node Source: https://docs.jelou.ai/guides/nodos/pregunta This example shows how to configure the 'Texto' field in the Pregunta node to send a personalized message to the user, including a variable. The message is displayed to the user, and the node waits for their input. ```text Hola {{$user.names}}, ¿cuál es tu correo electrónico? ``` -------------------------------- ### Search Contacts API Endpoint (Bash) Source: https://docs.jelou.ai/guides/functions/ejemplo-multi-tool This example shows how to search for contacts using the `/buscar-contactos` endpoint with a `curl` GET request. It supports query parameters for searching by name or email (`q`) and limiting the results (`limit`). The response is a JSON object containing a list of matching contacts and the total count. ```bash curl "http://localhost:3000/buscar-contactos?q=maria&limit=5" ``` -------------------------------- ### Example Dynamic Options Data Structure - JSON Source: https://docs.jelou.ai/guides/nodos/lista Provides an example JSON structure for dynamic options in the 'Lista' node. This data format is used as a source for populating the list when the dynamic mode is enabled. ```json [ { "id": "s1", "nombre": "Ventas", "agentes": 5, "horario": "L-V 8:00-18:00" }, { "id": "s2", "nombre": "Soporte Técnico", "agentes": 3, "horario": "L-V 9:00-17:00" }, { "id": "s3", "nombre": "Facturación", "agentes": 2, "horario": "L-V 8:00-16:00" } ] ``` -------------------------------- ### Verify Jelou Function in Production Source: https://docs.jelou.ai/guides/functions/quickstart Tests the deployed Jelou Function in production by sending a curl request to its public URL. It also shows how to monitor real-time logs for the deployed function. ```bash curl -X POST https://consultar-cliente.fn.jelou.ai \ -H "Content-Type: application/json" \ -d '{"telefono": "593987654321"}' jelou logs consultar-cliente ``` -------------------------------- ### Test Jelou Function with curl Source: https://docs.jelou.ai/guides/functions/quickstart Sends a POST request to the locally running Jelou Function using curl to test its functionality. It shows the expected JSON response. ```bash curl -X POST http://localhost:3000 \ -H "Content-Type: application/json" \ -d '{"telefono": "593987654321"}' ``` -------------------------------- ### Get All Databases - API Request Source: https://docs.jelou.ai/api/Datum/Obtener-informacin-de-las-bases-de-datos This snippet shows how to make a GET request to the Datum API to retrieve a list of all available databases. It includes the endpoint URL and an example of a successful JSON response. ```HTTP GET https://api.jelou.ai/v2/databases ``` -------------------------------- ### Jelou AI Batch Upsert API Response Examples Source: https://docs.jelou.ai/guides/integraciones/e-commerce/api-productos/upsert These JSON examples illustrate the expected responses from the Jelou AI batch product upsert API. The success response indicates the batch process has started, while the validation error response highlights missing required fields. ```json { "message": "Batch upsert process initiated successfully", "count": 3, "jobs": 3 } ``` ```json { "message": "The resources field is required.", "errors": { "resources": ["The resources field is required."] } } ``` -------------------------------- ### Initialize a New Jelou Function Project Source: https://docs.jelou.ai/guides/functions/quickstart Creates a new project directory for a Jelou Function, initializes it with `jelou init`, and prompts for function details like slug and description. It outlines the generated project files. ```bash mkdir consultar-cliente && cd consultar-cliente jelou init # ? Function slug: consultar-cliente # ? Description: Busca información de clientes para el bot de WhatsApp # ? Create new or link existing? Create new # ✓ Created consultar-cliente ``` -------------------------------- ### Configuración Manual del Servidor MCP para Cursor Source: https://docs.jelou.ai/guides/datum/mcp Instrucciones para la instalación manual del servidor MCP en Cursor. Este método implica agregar un archivo JSON a la configuración de Cursor para especificar la URL del servidor MCP. ```json { "datum": { "url": "https://datum.jelou.cloud/TU_ID_UNICO/mcp" } } ``` -------------------------------- ### Preprocesar Lógica Condicional con Código (JavaScript) Source: https://docs.jelou.ai/guides/agentes-ia/prompting Utiliza lógica condicional en un nodo de tipo código (JavaScript) para preprocesar instrucciones antes de enviarlas a un AI Agent. Esto ayuda a mantener los prompts limpios y enfocados, reduciendo la carga cognitiva del modelo. ```javascript let promptCondicional = "Haz tal cosa primero"; if($memory.get("variable")){ promptCondicional = "Mejor haz esto"; } $memory.set("promptCondicional", promptCondicional); ``` -------------------------------- ### Testing API Endpoints Source: https://docs.jelou.ai/guides/functions/autenticacion Provides examples of how to test API endpoints using mock authentication contexts and requests. This includes testing scenarios with valid and invalid authentication. ```APIDOC ## Testing API Handlers ### Description This section details how to test your API handlers using the provided mocking utilities. It covers creating mock contexts and requests to simulate different authentication scenarios. ### Method N/A (Testing utility) ### Endpoint N/A (Testing utility) ### Parameters N/A ### Request Example (Testing valid auth) ```typescript Deno.test("handler receives auth when token is valid", async () => { const ctx = createMockAuthContext(); const req = createMockAuthRequest("my-secret-token", { query: "test" }); const result = await fn.handler({ query: "test" }, ctx, req); assertEquals(result.authenticated, true); }); ``` ### Request Example (Testing no auth) ```typescript Deno.test("handler without auth returns ctx.auth null", async () => { const ctx = createMockContext({ auth: null }); const req = createMockRequest({ query: "test" }); const result = await fn.handler({ query: "test" }, ctx, req); assertEquals(result.authenticated, undefined); }); ``` ### Response N/A (Testing utility) ``` -------------------------------- ### Create Text Message Template with Quick Reply Buttons using Bash Source: https://docs.jelou.ai/api/campanas/crear-plantilla This example shows how to create a text message template with quick reply buttons. These buttons allow users to respond with predefined options. The template includes placeholders and specifies the `QUICK_REPLY` interactive action. ```bash curl --request POST \ --url 'https://api.jelou.ai/v1/bots/BOT_ID/templates?sendToAprove=true' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "displayName": "plantilla_quick_reply", \ "template": "Gracias por tu pedido, {{1}}! Tu número de confirmación es {{2}}. Usa los botones para contactarnos.", \ "example": "Gracias por tu pedido, María! Tu número de confirmación es 57893. Usa los botones para contactarnos.", \ "elementName": "plantilla_quick_reply", \ "params": [ \ {"param": "1", "label": "cliente", "example": "María"}, \ {"param": "2", "label": "orden", "example": "57893"} \ ], \ "paramsNumber": 2, \ "type": "HSM", \ "language": "es", \ "category": "UTILITY", \ "interactiveAction": "QUICK_REPLY", \ "buttons": [ \ {"text": "Contactar Soporte", "type": "QUICK_REPLY"}, \ {"text": "Contactar Ventas", "type": "QUICK_REPLY"} \ ] \ }' ``` -------------------------------- ### User Authentication API Source: https://docs.jelou.ai/guides/functions/autenticacion This API endpoint demonstrates how to enable and use Bearer token authentication for your Jelou AI functions. It shows the setup process, secret configuration, and how to make authenticated requests. ```APIDOC ## POST /mi-funcion.fn.jelou.ai ### Description This endpoint allows for authenticated requests to your Jelou AI function using a Bearer token. If authentication is enabled and a valid token is not provided, the request will be rejected. ### Method POST ### Endpoint /mi-funcion.fn.jelou.ai ### Parameters #### Query Parameters None #### Request Body - **query** (string) - Required - The query string for the function. ### Request Example ```json { "query": "test" } ``` ### Response #### Success Response (200) - **results** (array) - The results from the function. - **authenticated** (boolean) - Indicates if the request was authenticated. #### Response Example ```json { "results": [], "authenticated": true } ``` #### Error Response (401) - **error** (string) - "Unauthorized" #### Error Response Example ```json { "error": "Unauthorized" } ``` ``` -------------------------------- ### Enviar Mensaje con Botones de URL Dinámica de WhatsApp con API Source: https://docs.jelou.ai/api/campanas/envio-individual Envía un mensaje de WhatsApp con botones de acción de URL dinámica. Incluye parámetros para la URL y el tipo de botón. Requiere el ID del bot, credenciales, nombre del elemento, parámetros y número de destino. La precisión en los nombres es crítica. ```bash curl --request POST \ --url 'https://api.jelou.ai/v2/whatsapp/BOT_ID/hsm' \ --header 'Accept-Language: es' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "destinations": ["PHONE_NUMBER"], \ "parameters": ["PARAMETER_1"], \ "elementName": "ELEMENT_NAME", \ "buttonParameters": [ \ { \ "type": "URL", \ "payload": {"param": "PARAM_URL"} \ } \ ] \ }' ``` -------------------------------- ### Get Specific Database Information - API Request Source: https://docs.jelou.ai/api/Datum/Obtener-informacin-de-las-bases-de-datos This snippet demonstrates how to fetch details for a single database using its unique ID. It includes the endpoint structure with a placeholder for the database ID and an example of a successful JSON response. ```HTTP GET https://api.jelou.ai/v2/databases/DATABASE_ID ``` -------------------------------- ### Local Testing with Curl (Bash) Source: https://docs.jelou.ai/guides/functions/ejemplo-api-proxy Demonstrates how to test the API proxy locally using a curl command. This example shows how to pass parameters and query fields to the proxied API endpoint. ```bash curl "http://localhost:3000/users/42?fields=address,orders" ``` -------------------------------- ### Call Authenticated Function (Curl) Source: https://docs.jelou.ai/guides/functions/autenticacion This example demonstrates how to make a POST request to a protected Jelou AI function using `curl`. It includes the necessary `Authorization` header with the Bearer token and the `Content-Type` header. The response indicates successful authentication or an unauthorized error. ```bash curl -X POST https://mi-funcion.fn.jelou.ai \ -H "Authorization: Bearer mi-token-secreto" \ -H "Content-Type: application/json" \ -d '{"query": "test"}' ``` -------------------------------- ### Enviar Mensaje con Video de WhatsApp con API Source: https://docs.jelou.ai/api/campanas/envio-individual Envía un mensaje de WhatsApp que incluye un video. Se especifica la URL del medio y el tipo 'video'. Requiere el ID del bot, credenciales, nombre del elemento, parámetros y número de destino. La coincidencia exacta de nombres es fundamental. ```bash curl --request POST \ --url 'https://api.jelou.ai/v2/whatsapp/BOT_ID/hsm' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "parameters": ["PARAMETER_1", "PARAMETER_2"], \ "mediaUrl": "https://cdn.ejemplo.com/video.mp4", \ "type": "video", \ "destinations": ["PHONE_NUMBER"], \ "elementName": "ELEMENT_NAME" \ }' ``` -------------------------------- ### Fetch Bot Chat History (Bash) Source: https://docs.jelou.ai/api/conversaciones/historial This example demonstrates how to retrieve a bot's chat history using a basic GET request. It includes parameters for limiting the number of messages and specifying the page number. Authentication is handled via an Authorization header. ```bash curl --request GET \ --url 'https://api.jelou.ai/v1/external/messages/history/BOT_ID?limit=10&page=1' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' ``` ```bash curl --request GET \ --url 'https://api.jelou.ai/v1/external/messages/history/BOT_ID?limit=20&page=1&startAt=2025-01-01T00:00:00.000Z&endAt=2025-01-31T23:59:59.000Z' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' ``` ```bash curl --request GET \ --url 'https://api.jelou.ai/v1/external/messages/history/BOT_ID?limit=10&page=1&clientId=CLIENT_ID' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' ``` -------------------------------- ### Enviar Mensaje con Botones Quick Reply de WhatsApp con API Source: https://docs.jelou.ai/api/campanas/envio-individual Envía un mensaje de WhatsApp con botones de respuesta rápida (Quick Reply). Se definen múltiples botones con sus tipos y cargas útiles. Requiere el ID del bot, credenciales, nombre del elemento, parámetros y número de destino. La coincidencia exacta de nombres es indispensable. ```bash curl --request POST \ --url 'https://api.jelou.ai/v2/whatsapp/BOT_ID/hsm' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "elementName": "ELEMENT_NAME", \ "language": "es", \ "type": "text", \ "parameters": ["param1", "param2"], \ "destinations": ["PHONE_NUMBER"], \ "buttonParameters": [ \ { \ "type": "QUICK_REPLY", \ "payload": {"type": "edge", "action": "BTN1", "skillId": "1"} \ }, \ { \ "type": "QUICK_REPLY", \ "payload": {"type": "edge", "action": "BTN2", "skillId": "2"} \ }, \ { \ "type": "QUICK_REPLY", \ "payload": {"type": "edge", "action": "BTN3", "skillId": "3"} \ } \ ] \ }' ``` -------------------------------- ### Get Bot Skills Response - JSON Source: https://docs.jelou.ai/api/envia-mensajes/configura-skill Example successful response (200 OK) when fetching bot skills. It includes a list of skills, each with its unique identifier, name, description, type, creation/update timestamps, and active state. This data is crucial for managing and referencing skills. ```json { "message": ["Skills retrieved successfully!"], "statusMessage": "success", "status": 1, "data": [ { "id": 1, "name": "Skill Principal", "description": "Skill de bienvenida", "type": "BRAIN", "createdAt": "2024-10-24T11:18:05.000Z", "updatedAt": "2024-10-24T11:18:05.000Z", "state": true, "default": true }, { "id": 2, "name": "Skill Ventas", "description": "Flujo de ventas", "type": "BRAIN", "createdAt": "2024-10-24T11:13:32.000Z", "updatedAt": "2024-10-24T11:17:44.000Z", "state": true, "default": false } ] } ``` -------------------------------- ### Create Document Message Template using Bash Source: https://docs.jelou.ai/api/campanas/crear-plantilla This example demonstrates how to create a document message template. It includes a placeholder for the customer's name and is intended for sending documents. The template type is `DOCUMENT` and the category is `UTILITY`. ```bash curl --request POST \ --url 'https://api.jelou.ai/v1/bots/BOT_ID/templates?sendToAprove=true' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "displayName": "plantilla_documento", \ "template": "Hola {{1}}. Adjuntamos tu documento solicitado.", \ "example": "Hola María. Adjuntamos tu documento solicitado.", \ "elementName": "plantilla_documento", \ "params": [ \ {"param": "1", "label": "cliente", "example": "María"} \ ], \ "paramsNumber": 1 \ }' ``` -------------------------------- ### Get Branch Details Source: https://docs.jelou.ai/guides/integraciones/e-commerce/api-sucursales/obtener Retrieves the details of a specific branch, with an option to include associated products. ```APIDOC ## GET /apps/{app_id}/branches/{branch_id} ### Description Obtén los detalles de una sucursal específica. Puedes incluir los productos de la sucursal en la respuesta. ### Method GET ### Endpoint `/apps/{app_id}/branches/{branch_id}` ### Parameters #### Path Parameters - **app_id** (string) - Required - ID de tu tienda en Jelou Shop. - **branch_id** (string) - Required - ID de la sucursal. #### Query Parameters - **include** (string) - Optional - Usa `products` para incluir los productos de la sucursal en la respuesta. ### Request Example ```bash cURL curl "https://ecommerce.jelou.ai/apps/{app_id}/branches/1?include=products" \ -H "Authorization: Bearer " ``` ### Response #### Success Response (200) - **branch_id** (string) - The ID of the branch. - **name** (string) - The name of the branch. - **products** (array) - An array of products associated with the branch (only if `include=products` is used). - **product_id** (string) - The ID of the product. - **product_name** (string) - The name of the product. #### Response Example ```json { "branch_id": "1", "name": "Main Branch", "products": [ { "product_id": "prod_abc", "product_name": "Example Product" } ] } ``` ``` -------------------------------- ### Create Image Message Template using Bash Source: https://docs.jelou.ai/api/campanas/crear-plantilla This example shows how to create an image message template. It includes a placeholder for the customer's name and a URL for the image to be sent. The template type is `IMAGE` and the category is `MARKETING`. ```bash curl --request POST \ --url 'https://api.jelou.ai/v1/bots/BOT_ID/templates?sendToAprove=true' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "displayName": "plantilla_imagen", \ "template": "Hola {{1}}. Te invitamos a conocer nuestras promociones.", \ "example": "Hola María. Te invitamos a conocer nuestras promociones.", \ "elementName": "plantilla_imagen", \ "params": [ \ {"param": "1", "label": "cliente", "example": "María"} \ ], \ "paramsNumber": 1, \ "type": "IMAGE", \ "language": "es", \ "category": "MARKETING", \ "mediaUrl": "https://cdn.ejemplo.com/imagen.jpeg", \ "interactiveAction": "NONE" \ }' ``` -------------------------------- ### Cron Expression Format and Examples (Text) Source: https://docs.jelou.ai/guides/functions/cron Understand the standard 5-field cron expression format and common examples. The format includes minute, hour, day of the month, month, and day of the week. Examples cover daily, weekly, bi-hourly, and monthly schedules. ```text ┌───────────── minuto (0-59) │ ┌───────────── hora (0-23) │ │ ┌───────────── día del mes (1-31) │ │ │ ┌───────────── mes (1-12) │ │ │ │ ┌───────────── día de la semana (0-7, 0 y 7 = domingo) │ │ │ │ │ * * * * * Ejemplos comunes: * `0 9 * * *` | Todos los días a las 9:00 AM * `0 9 * * 1-5` | Lunes a viernes a las 9:00 AM * `*/30 * * * *` | Cada 30 minutos * `0 0 1 * *` | Primer día de cada mes a medianoche * `0 */2 * * *` | Cada 2 horas * `30 14 * * 3` | Miércoles a las 2:30 PM ``` -------------------------------- ### Consumir API de Jelou AI con cURL (Envío Masivo/1-1) Source: https://docs.jelou.ai/api/campanas/envio-individual Ejemplo de cómo consumir la API de Jelou AI para enviar mensajes masivos o individuales utilizando cURL. Requiere un cliente HTTPS y autenticación básica. Los datos de entrada incluyen el ID del bot, número de destino, parámetros y nombre de la plantilla. ```bash curl --request POST \ --url 'https://api.jelou.ai/v2/whatsapp/BOT_ID/hsm' \ --header 'Accept-Language: es' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ "destinations": ["PHONE_NUMBER"], "parameters": [], "elementName": "your_template_name" }' ``` -------------------------------- ### GET /v1/bots/{botId}/templates Source: https://docs.jelou.ai/api/campanas/obtener-plantillas Retrieves all HSM templates configured in your bot. You can filter by name, status, or category. ```APIDOC ## GET /v1/bots/{botId}/templates ### Description Retrieves all HSM templates configured in your bot. You can filter by name, status, or category. ### Method GET ### Endpoint /v1/bots/{botId}/templates ### Parameters #### Path Parameters - **botId** (string) - Required - Unique ID of the bot. Example: `123456789` #### Query Parameters - **query** (string) - Optional - Search templates by `elementName` - **status** (string) - Optional - Filter templates by status. Possible values: `PENDING`, `REJECTED`, `APPROVED` - **category** (string) - Optional - Filter templates by category. Possible values: `UTILITY`, `MARKETING`, `AUTHENTICATION` ### Response #### Success Response (200) - **data** (array) - An array of template objects. - **template** (string) - The template message content. - **displayName** (string) - The display name of the template. - **elementName** (string) - The unique identifier for the template. - **params** (array) - An array of parameters used in the template. - **label** (string) - The label for the parameter. - **param** (string) - The parameter identifier. - **paramsNumber** (integer) - The number of parameters in the template. - **isVisible** (boolean) - Whether the template is visible. - **language** (string) - The language of the template. - **status** (string) - The status of the template (`PENDING`, `REJECTED`, `APPROVED`). - **category** (string) - The category of the template (`UTILITY`, `MARKETING`, `AUTHENTICATION`). - **createdAt** (string) - The timestamp when the template was created. - **updatedAt** (string) - The timestamp when the template was last updated. #### Error Response (401) - **message** (string) - Error message indicating authentication failure. #### Error Response (404) - **message** (array) - An array of error messages, e.g., `["The Bot could not be found at the moment."]`. - **statusMessage** (string) - The status of the error, e.g., `"failed"`. - **error** (object) - An object containing error details. - **code** (string) - The error code, e.g., `"E1019"`. - **key** (string) - The error key, e.g., `"BOT_NOT_FOUND"`. ### Request Example ```json { "example": "request body" } ``` ### Response Example #### Success Response (200) ```json { "data": [ { "template": "¡Hola! Somos *Jelou*. \nTe damos la bienvenida _{{1}}_.", "displayName": "Bienvenida", "elementName": "bienvenida_cliente", "params": [ {"label": "Nombre del cliente", "param": "1"} ], "paramsNumber": 1, "isVisible": true, "language": "ES", "status": "APPROVED", "category": "UTILITY", "createdAt": "2021-01-28T15:08:38.492Z", "updatedAt": "2021-01-28T15:08:38.492Z" } ] } ``` #### Error Response (401) ```json { "message": "Authentication failed" } ``` #### Error Response (404) ```json { "message": ["The Bot could not be found at the moment."], "statusMessage": "failed", "error": { "code": "E1019", "key": "BOT_NOT_FOUND" } } ``` ``` -------------------------------- ### Get Current Date and Time Source: https://docs.jelou.ai/guides/agentes-ia/tools-nativas Retrieves the current date and time. It allows specifying a timezone to get the accurate local time. This function is useful for time-sensitive operations or context-aware responses. ```json { "timezone": "America/Mexico_City" } ``` -------------------------------- ### Create Text Message Template using Bash Source: https://docs.jelou.ai/api/campanas/crear-plantilla This example demonstrates how to create a simple text message template using the Jelou AI API. It requires a bot ID and authentication credentials. The template includes placeholders for dynamic content. ```bash curl --request POST \ --url 'https://api.jelou.ai/v1/bots/BOT_ID/templates?sendToAprove=true' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "displayName": "plantilla_texto_utility", \ "template": "Gracias por tu pedido, {{1}}! Tu número de confirmación es {{2}}. Si tienes alguna pregunta, contacta a soporte.", \ "example": "Gracias por tu pedido, María! Tu número de confirmación es 71936. Si tienes alguna pregunta, contacta a soporte.", \ "elementName": "plantilla_texto_utility", \ "params": [ \ {"param": "1", "label": "cliente", "example": "María"}, \ {"param": "2", "label": "orden", "example": "71936"} \ ], \ "paramsNumber": 2, \ "type": "HSM", \ "language": "es", \ "category": "UTILITY", \ "interactiveAction": "NONE" \ }' ``` -------------------------------- ### Example User Data Structure (JSON) Source: https://docs.jelou.ai/guides/variables/user Provides an example of the typical JSON structure for user data, including 'id' and 'names'. The available data may vary depending on the communication channel. ```json { "id": "PHONE_NUMBER", "names": "Juan Pérez" } ``` -------------------------------- ### Referenciar Lógica Procesada en AI Agent (Texto) Source: https://docs.jelou.ai/guides/agentes-ia/prompting En un AI Agent, se hace referencia a una variable procesada previamente en un nodo de código. Esto permite que el agente siga instrucciones dinámicas basadas en la lógica condicional ejecutada. ```text Sigue estas instrucciones: {{$memory.promptCondicional}} ``` -------------------------------- ### MCP Endpoint Response Example Source: https://docs.jelou.ai/guides/functions/mcp Provides an example of the JSON response when querying the `/mcp` endpoint, listing available tools. It also shows a successful 200 response after invoking a function via the main endpoint. ```json { "tools": [ { "name": "consultar-saldo", "description": "Consulta el saldo de un cliente por número de teléfono", "inputSchema": { "type": "object", "properties": { "telefono": { "type": "string", "minLength": 10, "description": "Número de teléfono con código de país" } }, "required": ["telefono"] } } ] } ``` ```json { "nombre": "María García", "saldo": 150.00, "moneda": "USD" } ``` -------------------------------- ### GET /v1/external/bots/{botId}/notifications Source: https://docs.jelou.ai/api/campanas/notificaciones Retrieves previously sent notifications, allowing you to get the status of messages sent through the notification system. You can filter by message ID, campaign ID, element name, and date range. ```APIDOC ## GET /v1/external/bots/{botId}/notifications ### Description This endpoint allows you to retrieve notifications that were previously sent. It provides detailed status information for individual or bulk messages, including delivery, read, and reply statuses. ### Method GET ### Endpoint `/v1/external/bots/{botId}/notifications` ### Parameters #### Path Parameters - **botId** (string) - Required - The unique identifier for the bot. #### Query Parameters - **messageId** (string) - Optional - The ID of a specific message to retrieve. - **campaignId** (string) - Optional - The ID of the campaign associated with the notifications. - **elementName** (string) - Optional - The name of the message template or element. - **from** (date) - Optional - The start date for filtering notifications (YYYY-MM-DD). - **to** (date) - Optional - The end date for filtering notifications (YYYY-MM-DD). - **limit** (number) - Optional - The maximum number of notifications to return per page. Maximum value is 50. - **page** (number) - Optional - The page number for pagination. Defaults to 1. ### Request Example ```bash curl --request GET \ --url 'https://api.jelou.ai/v1/external/bots/BOT_ID/notifications?limit=50&from=2024-01-01&to=2024-12-31&page=1' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' ``` ### Response #### Success Response (200) - **sentStatus** (string) - The delivery status of the message template. - **createdAt** (string) - The date and time when the message was sent. - **deliveryChannelAt** (string) - The date and time when the message was delivered to the channel (e.g., WhatsApp). - **deliveryUserAt** (string) - The date and time when the message was received by the user. - **readAt** (string) - The date and time when the user read the message. - **destination** (string) - The recipient's phone number. - **elementName** (string) - The name of the template used for the message. - **id** (string) - The unique identifier for the message. - **error** (string) - The reason for delivery failure, if applicable. - **reply** (object) - The user's reply to the message, available when the status is `REPLY`. #### Response Example ```json { "notifications": [ { "sentStatus": "DELIVERED_USER", "createdAt": "2024-05-15T10:00:00Z", "deliveryChannelAt": "2024-05-15T10:00:05Z", "deliveryUserAt": "2024-05-15T10:01:10Z", "readAt": "2024-05-15T10:05:00Z", "destination": "+1234567890", "elementName": "welcome_message", "id": "msg_abc123", "error": null, "reply": null } ] } ``` ### Message Statuses - `DELIVERED_CHANNEL`: The message was received by the channel (e.g., WhatsApp). - `DELIVERED_USER`: The message was received by the end-user. - `READ`: The user has read the message. - `REPLY`: The user has replied to the message. - `CREATED`: The message was received by Jelou. - `FAILED`: The message could not be delivered. ### Read Status - `true`: The user has read the message. - `false`: The user has not read the message. ``` -------------------------------- ### Enviar Mensaje con Botones de URL Estática de WhatsApp con API Source: https://docs.jelou.ai/api/campanas/envio-individual Envía un mensaje de WhatsApp con botones de acción de URL estática. Requiere el ID del bot, credenciales, nombre del elemento, parámetros y número de destino. La exactitud en los nombres de plantilla y botones es esencial. ```bash curl --request POST \ --url 'https://api.jelou.ai/v2/whatsapp/BOT_ID/hsm' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "parameters": ["PARAMETER_1"], \ "destinations": ["PHONE_NUMBER"], \ "elementName": "ELEMENT_NAME" \ }' ``` -------------------------------- ### Create First Skill: Question Node (TXT) Source: https://docs.jelou.ai/guides/getting-started/tu-primer-skill This snippet demonstrates the content for a 'question' node in Jelou AI's skill builder. It defines the prompt to ask the user and specifies a variable to store the user's response. The response is saved as 'nombre'. ```txt Soy tu primer skill. ¿Cuál es tu nombre? ``` -------------------------------- ### Retrieve All HSM Templates (GET Request) Source: https://docs.jelou.ai/api/campanas/obtener-plantillas This endpoint retrieves a list of all HSM templates configured for a specific bot. You can filter the results by template name, status (PENDING, REJECTED, APPROVED), or category (UTILITY, MARKETING, AUTHENTICATION). The botId is a required path parameter. ```HTTP GET /v1/bots/{botId}/templates ``` -------------------------------- ### Enviar Mensaje con Imagen de WhatsApp con API Source: https://docs.jelou.ai/api/campanas/envio-individual Envía un mensaje de WhatsApp que incluye una imagen. Se especifica la URL del medio y el tipo 'image'. Requiere el ID del bot, credenciales, nombre del elemento, parámetros y número de destino. La precisión en los nombres es crucial. ```bash curl --request POST \ --url 'https://api.jelou.ai/v2/whatsapp/BOT_ID/hsm' \ --header 'Authorization: Basic {{Base64EncodedUsername:Password}}' \ --header 'Content-Type: application/json' \ --data '{ \ "parameters": ["PARAMETER_1", "PARAMETER_2"], \ "mediaUrl": "https://cdn.ejemplo.com/imagen.jpeg", \ "type": "image", \ "destinations": ["PHONE_NUMBER"], \ "elementName": "ELEMENT_NAME" \ }' ``` -------------------------------- ### Liveness Success Output Source: https://docs.jelou.ai/guides/integraciones/identidad/agente-prueba-de-vida Represents a successful completion of the liveness check. The success information can be retrieved using a memory get command. ```javascript $memory.get("response_liveness_success") ```