### Email Provider Quick Start Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md A basic example demonstrating how to set up and use the email provider with BuilderBot. ```APIDOC ## Quick Start ```typescript import { createBot, createProvider, createFlow, addKeyword } from '@builderbot/bot' import { EmailProvider } from '@builderbot/provider-email' const emailProvider = createProvider(EmailProvider, { imap: { host: 'imap.gmail.com', port: 993, secure: true, auth: { user: 'your-email@gmail.com', pass: 'your-app-password' } }, smtp: { host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: 'your-email@gmail.com', pass: 'your-app-password' } } }) const welcomeFlow = addKeyword(['hello', 'hi']) .addAnswer('Hello! I received your email.') .addAction(async (ctx, { provider }) => { console.log('Email from:', ctx.from) console.log('Subject:', ctx.subject) console.log('Body:', ctx.body) console.log('Is reply:', ctx.isReply) }) const main = async () => { await createBot({ flow: createFlow([welcomeFlow]), provider: emailProvider, database: new MemoryDB() // Assuming MemoryDB is imported }) } main() ``` ``` -------------------------------- ### Install GoHighLevel Provider Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Install the GoHighLevel provider for BuilderBot using pnpm or npm. ```bash pnpm add @builderbot/provider-gohighlevel # or npm install @builderbot/provider-gohighlevel ``` -------------------------------- ### Install @builderbot/plugin-chatwoot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Install the plugin using pnpm. ```bash pnpm add @builderbot/plugin-chatwoot ``` -------------------------------- ### Complete BuilderBot GoHighLevel Example Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md This example demonstrates how to set up a BuilderBot with the GoHighLevel provider, including environment variable configuration, flow definition for greetings and user interactions, and event listeners for bot readiness and notices. Ensure all required environment variables like GHL_CLIENT_ID, GHL_CLIENT_SECRET, and GHL_LOCATION_ID are set. ```typescript import { createBot, createProvider, createFlow, addKeyword, EVENTS } from '@builderbot/bot' import { GoHighLevelProvider } from '@builderbot/provider-gohighlevel' import { MemoryDB } from '@builderbot/bot' // Environment variables const config = { clientId: process.env.GHL_CLIENT_ID, clientSecret: process.env.GHL_CLIENT_SECRET, locationId: process.env.GHL_LOCATION_ID, channelType: 'WhatsApp' as const, redirectUri: process.env.GHL_REDIRECT_URI, webhookSecret: process.env.GHL_WEBHOOK_SECRET, port: 3000, } // Create provider const provider = createProvider(GoHighLevelProvider, config) // Flows const welcomeFlow = addKeyword(['hello', 'hi', 'hola']) .addAnswer('Welcome to our service!') .addAnswer('How can I help you today?', { buttons: [ { body: 'Sales' }, { body: 'Support' }, { body: 'Information' }, ] }) const salesFlow = addKeyword(['sales', '1']) .addAnswer('Our sales team will contact you shortly!') const supportFlow = addKeyword(['support', '2']) .addAnswer('Please describe your issue and we will help you.') const mediaFlow = addKeyword([EVENTS.MEDIA]) .addAction(async (ctx, { provider, flowDynamic }) => { const filePath = await provider.saveFile(ctx, { path: './uploads' }) await flowDynamic(`File received and saved: ${filePath}`) }) // Main const main = async () => { const bot = await createBot({ flow: createFlow([welcomeFlow, salesFlow, supportFlow, mediaFlow]), provider, database: new MemoryDB(), }) // Event listeners provider.on('ready', () => { console.log('GoHighLevel bot is ready!') }) provider.on('notice', ({ title, instructions }) => { console.log(`[${title}]`) instructions.forEach(i => console.log(` - ${i}`)) }) console.log(`Server running on port ${config.port}`) } main().catch(console.error) ``` -------------------------------- ### Install @builderbot/manager Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/manager/README.md Install the package using pnpm. This is the first step to using the bot manager. ```bash pnpm add @builderbot/manager ``` -------------------------------- ### Examples of Package-Scoped Commands Source: https://github.com/codigoencasa/builderbot/blob/builderbot/AGENTS.md Illustrative examples of running build and test commands for specific packages using the '--filter' flag. ```bash pnpm --filter @builderbot/bot build ``` ```bash pnpm --filter @builderbot/manager test ``` ```bash pnpm --filter @builderbot/provider-gupshup test ``` -------------------------------- ### Install Email Provider Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md Install the email provider package using npm or pnpm. ```bash npm install @builderbot/provider-email # or pnpm add @builderbot/provider-email ``` -------------------------------- ### Minimal GoHighLevel Bot Setup Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Initialize a BuilderBot with the GoHighLevel provider using minimal configuration. Ensure environment variables are set. ```typescript import { createBot, createProvider, createFlow, addKeyword } from '@builderbot/bot' import { GoHighLevelProvider } from '@builderbot/provider-gohighlevel' import { MemoryDB } from '@builderbot/bot' // Create the provider const provider = createProvider(GoHighLevelProvider, { clientId: process.env.GHL_CLIENT_ID, clientSecret: process.env.GHL_CLIENT_SECRET, locationId: process.env.GHL_LOCATION_ID, channelType: 'WhatsApp', redirectUri: process.env.GHL_REDIRECT_URI, }) // Create a simple flow const welcomeFlow = addKeyword(['hello', 'hi']) .addAnswer('Welcome! How can I help you today?') // Create and start the bot const main = async () => { await createBot({ flow: createFlow([welcomeFlow]), provider, database: new MemoryDB(), }) console.log('Bot is running!') } main() ``` -------------------------------- ### Quick Start: Initialize Bot Manager and API Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/manager/README.md Initialize the BotManager and the BotManagerApi. The manager requires a sessions directory, and the API can be configured with a port and an optional API key. Register a flow before starting the API. ```typescript import { BotManager, BotManagerApi } from '@builderbot/manager' import { addKeyword } from '@builderbot/bot' // Create the manager const manager = new BotManager({ sessionsDir: './sessions' }) // Create the API server const api = new BotManagerApi(manager, { port: 3000, apiKey: 'your-secret-key' // optional }) // Register a flow const greetingFlow = addKeyword(['hola', 'hello']) .addAnswer('¡Hola! Bienvenido') .addAnswer('¿En qué puedo ayudarte?') api.registerFlow('greeting', 'Greeting Flow', greetingFlow) // Start the API api.start() ``` -------------------------------- ### Email Provider Installation Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md Install the email provider package using npm or pnpm. ```APIDOC ## Installation ```bash npm install @builderbot/provider-email # or pnpm add @builderbot/provider-email ``` ``` -------------------------------- ### Install Gupshup Provider Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gupshup/README.md Install the Gupshup provider package using npm. This is the first step to integrate Gupshup with BuilderBot. ```bash npm install @builderbot/provider-gupshup ``` -------------------------------- ### GoHighLevel Bot Setup with Pre-existing Tokens Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Initialize the GoHighLevel provider using existing access and refresh tokens, useful for resuming sessions. ```typescript const provider = createProvider(GoHighLevelProvider, { clientId: process.env.GHL_CLIENT_ID, clientSecret: process.env.GHL_CLIENT_SECRET, locationId: process.env.GHL_LOCATION_ID, channelType: 'WhatsApp', accessToken: 'your_existing_access_token', refreshToken: 'your_existing_refresh_token', }) ``` -------------------------------- ### Create a New BuilderBot Project Source: https://github.com/codigoencasa/builderbot/blob/builderbot/README.md Use this command to initialize a new BuilderBot project. Ensure you have Node.js installed. ```bash npm create builderbot@latest ``` -------------------------------- ### Instagram Provider Installation Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-instagram/README.md Install the Instagram provider package using npm. ```APIDOC ## Installation ```bash npm install @builderbot/provider-instagram ``` ``` -------------------------------- ### Webhook Setup Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-instagram/README.md Instructions for setting up the webhook in your Facebook App. ```APIDOC ## Webhook Setup 1. In your Facebook App dashboard, go to Instagram > Settings 2. Add a webhook URL: `https://your-domain.com/webhook` 3. Enter your verify token 4. Subscribe to the following events: - `messages` - `messaging_postbacks` - `comments` (required for listening to post comments) ``` -------------------------------- ### Install Instagram Provider Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-instagram/README.md Install the Instagram provider package using npm. This is the first step to integrating Instagram messaging with BuilderBot. ```bash npm install @builderbot/provider-instagram ``` -------------------------------- ### GoHighLevel Bot Setup with Webhook Verification Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Configure the GoHighLevel provider with a webhook secret for HMAC SHA256 verification, recommended for production environments. ```typescript const provider = createProvider(GoHighLevelProvider, { clientId: process.env.GHL_CLIENT_ID, clientSecret: process.env.GHL_CLIENT_SECRET, locationId: process.env.GHL_LOCATION_ID, channelType: 'WhatsApp', redirectUri: process.env.GHL_REDIRECT_URI, webhookSecret: process.env.GHL_WEBHOOK_SECRET, // HMAC SHA256 verification }) ``` -------------------------------- ### Install Facebook Messenger Provider Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-facebook-messenger/README.md Install the Facebook Messenger provider package using npm. This is the first step to integrating BuilderBot with Facebook Messenger. ```bash npm install @builderbot/provider-facebook-messenger ``` -------------------------------- ### BuilderBot Flow Callback Examples Source: https://github.com/codigoencasa/builderbot/blob/builderbot/AGENTS.md Illustrates the correct usage of flow control functions within BuilderBot callbacks. Avoid mixing 'endFlow' and 'flowDynamic' in the same context. ```javascript return gotoFlow(...) return endFlow(...) return fallBack(...) await flowDynamic(...) await state.update(...) ``` -------------------------------- ### Facebook Messenger Webhook Setup Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-facebook-messenger/README.md Instructions for setting up the webhook in your Facebook App dashboard. ```markdown ## Webhook Setup 1. In your Facebook App dashboard, go to Messenger > Settings 2. Add a webhook URL: `https://your-domain.com/webhook` 3. Enter your verify token 4. Subscribe to the following events: - `messages` - `messaging_postbacks` - `messaging_optins` ``` -------------------------------- ### Get bot QR code via API Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/manager/README.md Use curl to send a GET request to the /api/bots/:tenantId/qr endpoint to retrieve the QR code for a specific bot. This is necessary to connect the bot to WhatsApp. ```bash curl http://localhost:3000/api/bots/my-bot/qr \ -H "X-API-Key: your-secret-key" ``` -------------------------------- ### Configure Instagram Provider to Listen to Comments Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-instagram/README.md Set `listenMode` to 'comment' or 'both' to receive comments on your posts. This example shows how to initialize the provider and set up a flow that handles responses differently for DMs and comments. ```typescript const provider = createProvider(InstagramProvider, { accessToken: 'YOUR_ACCESS_TOKEN', igAccountId: 'YOUR_INSTAGRAM_ACCOUNT_ID', verifyToken: 'YOUR_VERIFY_TOKEN', listenMode: 'both', // Listen to DMs and comments }) // Flow that responds to "info" from both DMs and comments const infoFlow = addKeyword('info') .addAction(async (ctx, { provider }) => { if (ctx.comment) { // It's a comment - send private DM based on comment await provider.sendPrivateReply(ctx.comment.id, 'Thanks for your interest!') } else { // It's a DM - reply to the DM directly await provider.sendMessage(ctx.from, 'Thanks for your interest!') } }) ``` -------------------------------- ### Manually Handle Chatwoot Webhook Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md If using a custom HTTP server, manually handle incoming Chatwoot webhooks by calling `handleWebhook`. This is useful for integrating with existing server setups. ```typescript myServer.post('/v1/chatwoot', async (req, res) => { await chatwoot.handleWebhook(bot, req.body) res.end(JSON.stringify({ status: 'ok' })) }) ``` -------------------------------- ### GoHighLevel Environment Variables Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Set up your GoHighLevel credentials and configuration in a .env file for the provider. ```env # Required GHL_CLIENT_ID=your_client_id_here GHL_CLIENT_SECRET=your_client_secret_here GHL_LOCATION_ID=your_location_id_here # Optional GHL_REDIRECT_URI=http://localhost:3000/oauth/callback GHL_WEBHOOK_SECRET=your_webhook_secret_for_hmac_verification GHL_CHANNEL_TYPE=WhatsApp ``` -------------------------------- ### Initialize Email Provider and Bot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md Set up the EmailProvider with IMAP and SMTP configurations and integrate it with a BuilderBot flow. ```typescript import { createBot, createProvider, createFlow, addKeyword } from '@builderbot/bot' import { EmailProvider } from '@builderbot/provider-email' const emailProvider = createProvider(EmailProvider, { imap: { host: 'imap.gmail.com', port: 993, secure: true, auth: { user: 'your-email@gmail.com', pass: 'your-app-password' } }, smtp: { host: 'smtp.gmail.com', port: 465, secure: true, auth: { user: 'your-email@gmail.com', pass: 'your-app-password' } } }) const welcomeFlow = addKeyword(['hello', 'hi']) .addAnswer('Hello! I received your email.') .addAction(async (ctx, { provider }) => { console.log('Email from:', ctx.from) console.log('Subject:', ctx.subject) console.log('Body:', ctx.body) console.log('Is reply:', ctx.isReply) }) const main = async () => { await createBot({ flow: createFlow([welcomeFlow]), provider: emailProvider, database: new MemoryDB() }) } main() ``` -------------------------------- ### Initialize Chatwoot Plugin and Attach to Bot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Set up the Chatwoot plugin with your credentials and automatically register webhooks and HTTP routes. Ensure your webhook URL is publicly accessible. ```typescript import { createBot, createFlow, addKeyword } from '@builderbot/bot' import { BaileysProvider } from '@builderbot/provider-baileys' import { createChatwootPlugin } from '@builderbot/plugin-chatwoot' const chatwoot = createChatwootPlugin({ token: 'YOUR_TOKEN', url: 'https://app.chatwoot.com', accountId: 1, webhookUrl: 'https://your-bot.example.com/v1/chatwoot', }) const bot = await createBot({ flow: createFlow([...]), provider: createProvider(BaileysProvider, { name: 'bot' }), database: new MemoryDB(), }) // Registers the Chatwoot account webhook AND the /v1/chatwoot HTTP route automatically await chatwoot.attach(bot) ``` -------------------------------- ### Run Repository Build Commands Source: https://github.com/codigoencasa/builderbot/blob/builderbot/AGENTS.md Execute common build, lint, and test commands from the repository root. Ensure Node and pnpm versions meet the specified requirements. ```bash pnpm install pnpm run clean.lib pnpm run build pnpm run build:full pnpm run lint:check pnpm run lint:fix pnpm run format:check pnpm run format:write pnpm test pnpm run test:coverage ``` -------------------------------- ### Get Email Attachments Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md Retrieve a list of all attachments associated with an email context using the getAttachments method. ```typescript const attachments = provider.getAttachments(ctx) ``` -------------------------------- ### Get Email Thread ID Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md Retrieve the thread ID for an email to track conversations using the getThreadId method. ```typescript const threadId = provider.getThreadId(ctx) ``` -------------------------------- ### Automatic Webhook Registration Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Automatically registers the Chatwoot webhook and wires the HTTP route on the provider's server when the bot starts. ```APIDOC ## POST /v1/chatwoot (Webhook Endpoint) ### Description This endpoint is automatically registered by the `chatwoot.attach(bot)` method to receive webhook events from Chatwoot. ### Method POST ### Endpoint /v1/chatwoot ### Request Body Chatwoot sends various event payloads. The plugin processes specific events like `conversation_updated` and `message_created`. ### Response Example ```json { "status": "ok" } ``` ``` -------------------------------- ### GoHighLevel Webhook Configuration Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Configure your GoHighLevel sub-account to send incoming messages to your bot's webhook endpoint. Use ngrok for local development. ```bash ngrok http 3000 # Use the ngrok URL: https://abc123.ngrok.io/webhook ``` -------------------------------- ### Manual Webhook Handling Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Provides instructions for manually registering and handling the webhook if using a custom HTTP server. ```APIDOC ## POST /v1/chatwoot (Manual Webhook Handling) ### Description If you are using a custom HTTP server, you can manually register and handle Chatwoot webhook events using the `chatwoot.handleWebhook` method. ### Method POST ### Endpoint /v1/chatwoot ### Parameters #### Request Body - **bot** (object) - Required - The BuilderBot instance. - **req.body** (object) - Required - The incoming webhook payload from Chatwoot. ### Request Example ```javascript myServer.post('/v1/chatwoot', async (req, res) => { await chatwoot.handleWebhook(bot, req.body) res.end(JSON.stringify({ status: 'ok' })) }) ``` ### Response #### Success Response (200) Returns a JSON object indicating the status of the webhook processing. - **status** (string) - Indicates 'ok' if processed successfully. ``` -------------------------------- ### Configure Chatwoot Plugin using Environment Variables Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Load Chatwoot configuration from environment variables for better security and flexibility. Recommended for sensitive credentials. ```dotenv CHATWOOT_TOKEN=your-access-token CHATWOOT_URL=https://app.chatwoot.com CHATWOOT_ACCOUNT_ID=1 CHATWOOT_WEBHOOK_URL=https://your-bot.example.com/v1/chatwoot ``` ```typescript const chatwoot = createChatwootPlugin({ token: process.env.CHATWOOT_TOKEN!, url: process.env.CHATWOOT_URL!, accountId: Number(process.env.CHATWOOT_ACCOUNT_ID), webhookUrl: process.env.CHATWOOT_WEBHOOK_URL, }) ``` -------------------------------- ### Initialize Chatwoot Plugin and Attach to Bot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Initialize the Chatwoot plugin with your Chatwoot credentials and attach it to the bot. This sets up bidirectional message syncing and agent reply forwarding. ```typescript import { createBot, createProvider, createFlow, MemoryDB } from '@builderbot/bot' import { BaileysProvider } from '@builderbot/provider-baileys' import { createChatwootPlugin } from '@builderbot/plugin-chatwoot' const chatwoot = createChatwootPlugin({ token: 'YOUR_CHATWOOT_USER_TOKEN', url: 'https://app.chatwoot.com', accountId: 1, // Optional but recommended: enables agent → WhatsApp replies webhookUrl: 'https://your-bot.example.com/v1/chatwoot', }) const bot = await createBot({ flow: createFlow([...]), provider: createProvider(BaileysProvider), database: new MemoryDB(), }) // One call wires everything up — including the webhook HTTP route await chatwoot.attach(bot) ``` -------------------------------- ### Send Media with BuilderBot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Send media files to users by providing a URL in the `media` option of the `addAnswer` method. This is useful for sending images or other media content. ```typescript const sendMediaFlow = addKeyword('send photo') .addAnswer('Here is your image!', { media: 'https://example.com/image.jpg' }) ``` -------------------------------- ### Send Local Files with BuilderBot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Send local files as media by referencing their path in the `media` option of the `addAnswer` method. Ensure the file path is correct relative to your project. ```typescript const sendLocalFile = addKeyword('send document') .addAnswer('Here is the document!', { media: './files/document.pdf' }) ``` -------------------------------- ### Chatwoot Plugin Initialization and Attachment Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Functions for creating and attaching the Chatwoot plugin to a BuilderBot instance. ```APIDOC ## `createChatwootPlugin(config)` ### Description Creates the plugin instance. ### Method `createChatwootPlugin` ### Parameters #### Request Body - **config** (object) - Required - Configuration object for the Chatwoot plugin. ### Response Returns a `ChatwootPlugin` instance. ## `chatwoot.attach(bot)` ### Description Wires the plugin into the bot. Must be called once after `createBot`. ### Method `chatwoot.attach ### Parameters #### Path Parameters - **bot** (object) - Required - The BuilderBot instance to attach the plugin to. ### Notes - Validates Chatwoot credentials (`checkAccount`) - Finds or creates the API-channel inbox - Registers the account webhook in Chatwoot if `webhookUrl` is configured - Auto-registers the HTTP route on `provider.server` if `webhookUrl` is configured - Listens to `send_message` and `provider.message` events ``` -------------------------------- ### Initialize Gupshup Provider Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gupshup/README.md Configure and create an instance of the Gupshup provider for BuilderBot. Ensure you replace placeholder values with your actual API key, app name, and phone number. Log settings can be customized. ```typescript import { createProvider } from '@builderbot/bot' import { GupshupProvider } from '@builderbot/provider-gupshup' const adapterProvider = createProvider(GupshupProvider, { apiKey: 'YOUR_API_KEY', srcName: 'YOUR_APP_NAME', phoneNumber: 'YOUR_SOURCE_NUMBER', logs: { inbound: false, status: 'failed', outboundErrors: true, rawOnFailed: false, }, }) ``` -------------------------------- ### Run Package-Scoped Build Commands Source: https://github.com/codigoencasa/builderbot/blob/builderbot/AGENTS.md Execute build or test commands for a specific package within the monorepo. Replace '' with the target package identifier. ```bash pnpm --filter build ``` ```bash pnpm --filter test ``` ```bash pnpm --filter test:coverage ``` -------------------------------- ### Create a bot via API Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/manager/README.md Use curl to send a POST request to the /api/bots endpoint to create a new bot. Specify the tenantId, name, flowIds, and port in the JSON payload. ```bash curl -X POST http://localhost:3000/api/bots \ -H "Content-Type: application/json" \ -H "X-API-Key: your-secret-key" \ -d '{ "tenantId": "my-bot", "name": "My WhatsApp Bot", "flowIds": ["greeting"], "port": 3008 }' ``` -------------------------------- ### Initialize Instagram Bot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-instagram/README.md Initialize the BuilderBot with the Instagram provider. Ensure you replace placeholders with your actual access token, account ID, and verify token. The port can be configured if needed. ```typescript import { createBot, createProvider, createFlow } from '@builderbot/bot' import { InstagramProvider } from '@builderbot/provider-instagram' const main = async () => { const provider = createProvider(InstagramProvider, { accessToken: 'YOUR_ACCESS_TOKEN', igAccountId: 'YOUR_INSTAGRAM_ACCOUNT_ID', verifyToken: 'YOUR_VERIFY_TOKEN', version: 'v19.0', // optional, defaults to v19.0 port: 3000, // optional, defaults to 3000 }) await createBot({ flow: createFlow([]), provider, database: // your database adapter }) } main() ``` -------------------------------- ### Available Methods Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-instagram/README.md List of available methods for interacting with the Instagram Provider. ```APIDOC ## Available Methods ### sendMessage(userId, message, options?) Send a text message to a user. ### sendImage(userId, imageUrl) Send an image attachment. ### sendVideo(userId, videoUrl) Send a video attachment. ### sendAudio(userId, audioUrl) Send an audio attachment. ### sendFile(userId, fileUrl) Send a file attachment. ### sendQuickReplies(userId, text, quickReplies) Send quick reply buttons. ```typescript await provider.sendQuickReplies('user_id', 'Quick options:', [ { content_type: 'text', title: 'Yes', payload: 'YES' }, { content_type: 'text', title: 'No', payload: 'NO' } ]) ``` ### saveFile(ctx, options?) Save a file from a received message. ### replyComment(commentId, message) Reply publicly to a comment (visible on the post). ```typescript await provider.replyComment(ctx.comment.id, 'Thanks for your comment!') ``` ### sendPrivateReply(commentId, message) Send a private DM to a user who commented on your post. ```typescript await provider.sendPrivateReply(ctx.comment.id, 'Thanks for your interest!') ``` ``` -------------------------------- ### Environment Variables Configuration Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Recommended approach for managing sensitive configuration values using environment variables. ```APIDOC ## Environment Variables Configuration ### Description It is recommended to store sensitive information such as API tokens and URLs in environment variables rather than hardcoding them directly in the code. ### Example `.env` file ```env CHATWOOT_TOKEN=your-access-token CHATWOOT_URL=https://app.chatwoot.com CHATWOOT_ACCOUNT_ID=1 CHATWOOT_WEBHOOK_URL=https://your-bot.example.com/v1/chatwoot ``` ### Example Usage in Code ```javascript import { createChatwootPlugin } from '@builderbot/plugin-chatwoot' const chatwoot = createChatwootPlugin({ token: process.env.CHATWOOT_TOKEN!, url: process.env.CHATWOOT_URL!, accountId: Number(process.env.CHATWOOT_ACCOUNT_ID), webhookUrl: process.env.CHATWOOT_WEBHOOK_URL, }) ``` ``` -------------------------------- ### Configure GoHighLevel OAuth2 Scopes Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Enable the necessary OAuth2 scopes in your GoHighLevel app settings for the provider to function correctly. ```text conversations.readonly conversations.write conversations/message.readonly conversations/message.write ``` -------------------------------- ### Email Provider Configuration Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md Details on configuring the EmailProvider, including IMAP and SMTP settings. ```APIDOC ## Configuration ### IEmailProviderArgs | Property | Type | Required | Default | Description | |----------|------|----------|---------|-------------| | `imap` | `ImapConfig` | Yes | - | IMAP server configuration | | `smtp` | `SmtpConfig` | Yes | - | SMTP server configuration | | `mailbox` | `string` | No | `'INBOX'` | Mailbox to monitor | | `markAsRead` | `boolean` | No | `true` | Mark emails as read after processing | | `fromEmail` | `string` | No | SMTP user | From address for outgoing emails | | `fromName` | `string` | No | - | Display name for outgoing emails | ### ImapConfig / SmtpConfig | Property | Type | Required | Description | |----------|------|----------|-------------|| | `host` | `string` | Yes | Server hostname | | `port` | `number` | Yes | Server port | | `secure` | `boolean` | No | Use SSL/TLS (default: true) | | `auth.user` | `string` | Yes | Username | | `auth.pass` | `string` | Yes | Password or app password | ``` -------------------------------- ### Configuration Options Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-instagram/README.md Details of the configuration options available for the Instagram Provider. ```APIDOC ## Configuration Options | Option | Type | Required | Default | |---|---|---|---| | `accessToken` | string | Yes | - | | `igAccountId` | string | Yes | - | | `verifyToken` | string | Yes | - | | `version` | string | No | `v19.0` | | `port` | number | No | `3000` | | `name` | string | No | `instagram-bot` | | `listenMode` | string | No | `message` | ``` -------------------------------- ### Send Media Programmatically with BuilderBot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Send media files to contacts using the `sendMessage` method by providing a URL in the `media` option. This allows for sending images, videos, or other media types. ```typescript // Send media await provider.sendMessage('contact_phone_number', 'Check this out!', { media: 'https://example.com/image.png' }) ``` -------------------------------- ### Handle Bot Events Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/manager/README.md Listen for various bot lifecycle events using the manager.on() method. This allows you to react to events like bot creation, connection, QR code generation, disconnection, and errors. ```typescript manager.on('bot:created', (tenantId, data) => { console.log(`Bot ${tenantId} created`) }) manager.on('bot:connected', (tenantId) => { console.log(`Bot ${tenantId} connected to WhatsApp`) }) manager.on('bot:qr', (tenantId, data) => { console.log(`QR for ${tenantId}:`, data.qr) }) manager.on('bot:disconnected', (tenantId) => { console.log(`Bot ${tenantId} disconnected`) }) manager.on('bot:error', (tenantId, data) => { console.error(`Error in bot ${tenantId}:`, data.error) }) ``` -------------------------------- ### Documentation API Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/manager/README.md Provides access to the auto-generated Swagger UI for API documentation. ```APIDOC ## GET /docs ### Description Access the Swagger UI for interactive API documentation. ### Method GET ### Endpoint /docs ### Response #### Success Response (200) - The Swagger UI interface will be rendered in the browser. ``` -------------------------------- ### Run a Single UVU Test File Source: https://github.com/codigoencasa/builderbot/blob/builderbot/AGENTS.md Execute a specific test file using UVU with a narrowed directory and anchored regex for precise targeting. The '-r tsm' flag is used for TypeScript execution. ```bash pnpm --filter @builderbot/manager exec uvu -r tsm ./__tests__ "^api\.test\.ts$" ``` ```bash pnpm --filter @builderbot/bot exec uvu -r tsm ./__tests__/units "^state\.test\.ts$" ``` ```bash pnpm --filter @builderbot/cli exec uvu -r tsm ./_test_ "^check\.test\.ts$" ``` -------------------------------- ### Initialize Facebook Messenger Bot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-facebook-messenger/README.md Initialize the BuilderBot with the Facebook Messenger provider. Ensure you replace placeholder tokens and IDs with your actual credentials. The provider requires an access token, page ID, and verify token. ```typescript import { createBot, createProvider, createFlow } from '@builderbot/bot' import { FacebookMessengerProvider } from '@builderbot/provider-facebook-messenger' const main = async () => { const provider = createProvider(FacebookMessengerProvider, { accessToken: 'YOUR_PAGE_ACCESS_TOKEN', pageId: 'YOUR_PAGE_ID', verifyToken: 'YOUR_VERIFY_TOKEN', version: 'v19.0', // optional, defaults to v19.0 port: 3000, // optional, defaults to 3000 }) await createBot({ flow: createFlow([]), provider, database: // your database adapter }) } main() ``` -------------------------------- ### Chatwoot Plugin Configuration Options Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Configure the Chatwoot plugin with essential details like API token, Chatwoot URL, account ID, and optional inbox name and webhook URL for agent replies. ```typescript const chatwoot = createChatwootPlugin({ /** User or Agent API access token from Chatwoot → Profile → Access Token */ token: 'xxxxxxxxxxxxxxxxxxxxxxxx', /** Base URL of your Chatwoot instance */ url: 'https://app.chatwoot.com', /** Numeric account ID visible in the Chatwoot URL */ accountId: 1, /** Optional: custom inbox name (default: 'BuilderBot Inbox') */ inboxName: 'WhatsApp Bot', /** * Optional: public URL where Chatwoot will POST webhook events. * When provided, the plugin registers (or reuses) the webhook on startup. * Required for agent replies to reach WhatsApp. */ webhookUrl: 'https://your-bot.example.com/v1/chatwoot', }) ``` -------------------------------- ### Run a Single Jest Test File Source: https://github.com/codigoencasa/builderbot/blob/builderbot/AGENTS.md Execute a specific test file using Jest with the '--runInBand' option for sequential execution. Useful for debugging. ```bash pnpm --filter @builderbot/provider-gupshup exec jest __tests__/core.test.ts --runInBand ``` -------------------------------- ### Instagram Provider Configuration and Usage Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-instagram/README.md Set up and use the Instagram provider with your BuilderBot application. ```APIDOC ## Configuration Before using this provider, you need to: 1. Create a Facebook App at [Facebook Developers](https://developers.facebook.com/) 2. Add the Instagram product to your app 3. Connect your Instagram Business or Creator account 4. Generate an Access Token 5. Set up a webhook with your verify token ## Usage ```typescript import { createBot, createProvider, createFlow } from '@builderbot/bot' import { InstagramProvider } from '@builderbot/provider-instagram' const main = async () => { const provider = createProvider(InstagramProvider, { accessToken: 'YOUR_ACCESS_TOKEN', igAccountId: 'YOUR_INSTAGRAM_ACCOUNT_ID', verifyToken: 'YOUR_VERIFY_TOKEN', version: 'v19.0', // optional, defaults to v19.0 port: 3000, // optional, defaults to 3000 }) await createBot({ flow: createFlow([]), provider, database: // your database adapter }) } main() ``` ``` -------------------------------- ### Outlook/Office 365 IMAP and SMTP Configuration Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md Configuration for Outlook/Office 365. Note that SMTP uses STARTTLS and does not require 'secure: true' for the port. ```typescript { imap: { host: 'outlook.office365.com', port: 993, secure: true, auth: { user: 'your-email@outlook.com', pass: 'your-password' } }, smtp: { host: 'smtp.office365.com', port: 587, secure: false, // Use STARTTLS auth: { user: 'your-email@outlook.com', pass: 'your-password' } } } ``` -------------------------------- ### API Methods - Replying and Handling Emails Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-email/README.md Methods for replying to emails and managing attachments and conversation context. ```APIDOC ### reply(ctx, message, options?) Reply to an existing email thread. ```typescript .addAction(async (ctx, { provider }) => { await provider.reply(ctx, 'Thank you for your message!') }) ``` ### saveFile(ctx, options?) Save an email attachment to disk. ```typescript .addAction(async (ctx, { provider }) => { if (ctx.attachments?.length) { const filePath = await provider.saveFile(ctx, { path: './downloads', attachmentIndex: 0 }) console.log('Saved to:', filePath) } }) ``` ### getAttachments(ctx) Get all attachments from an email. ```typescript const attachments = provider.getAttachments(ctx) ``` ### isReply(ctx) Check if the email is a reply. ```typescript if (provider.isReply(ctx)) { console.log('This is a reply to:', ctx.inReplyTo) } ``` ### getThreadId(ctx) Get the thread ID for conversation tracking. ```typescript const threadId = provider.getThreadId(ctx) ``` ``` -------------------------------- ### Bots API Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/manager/README.md Manage individual bot instances, including creation, retrieval, updates, and operational commands. ```APIDOC ## GET /api/bots ### Description List all registered bots. ### Method GET ### Endpoint /api/bots ### Response #### Success Response (200) - **bots** (array) - An array of bot summary objects. - **tenantId** (string) - The unique identifier for the bot tenant. - **name** (string) - The name of the bot. - **port** (number) - The port the bot is running on. ``` ```APIDOC ## POST /api/bots ### Description Create a new bot instance. ### Method POST ### Endpoint /api/bots ### Parameters #### Request Body - **tenantId** (string) - Required - Unique identifier for the bot tenant. - **name** (string) - Required - Name of the bot. - **flowIds** (array) - Required - An array of flow IDs to associate with the bot. - **port** (number) - Required - The port number for the bot's API. ### Request Example ```json { "tenantId": "my-bot", "name": "My WhatsApp Bot", "flowIds": ["greeting"], "port": 3008 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **bot** (object) - The created bot object. ``` ```APIDOC ## GET /api/bots/:tenantId ### Description Get details of a specific bot by its tenant ID. ### Method GET ### Endpoint /api/bots/:tenantId ### Parameters #### Path Parameters - **tenantId** (string) - Required - The tenant ID of the bot to retrieve. ### Response #### Success Response (200) - **bot** (object) - The bot details. - **tenantId** (string) - The unique identifier for the bot tenant. - **name** (string) - The name of the bot. - **flowIds** (array) - An array of flow IDs associated with the bot. - **port** (number) - The port the bot is running on. ``` ```APIDOC ## PUT /api/bots/:tenantId ### Description Update an existing bot's configuration. ### Method PUT ### Endpoint /api/bots/:tenantId ### Parameters #### Path Parameters - **tenantId** (string) - Required - The tenant ID of the bot to update. #### Request Body - **name** (string) - Optional - The new name for the bot. - **flowIds** (array) - Optional - An array of new flow IDs to associate with the bot. - **port** (number) - Optional - The new port number for the bot's API. ### Response #### Success Response (200) - **message** (string) - Confirmation message. - **bot** (object) - The updated bot object. ``` ```APIDOC ## DELETE /api/bots/:tenantId ### Description Delete a bot instance by its tenant ID. ### Method DELETE ### Endpoint /api/bots/:tenantId ### Parameters #### Path Parameters - **tenantId** (string) - Required - The tenant ID of the bot to delete. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` ```APIDOC ## GET /api/bots/:tenantId/qr ### Description Retrieve the QR code for a specific bot to connect to WhatsApp. ### Method GET ### Endpoint /api/bots/:tenantId/qr ### Parameters #### Path Parameters - **tenantId** (string) - Required - The tenant ID of the bot. ### Response #### Success Response (200) - **qr** (string) - The QR code image data or URL. ``` ```APIDOC ## POST /api/bots/:tenantId/restart ### Description Restart a specific bot instance. ### Method POST ### Endpoint /api/bots/:tenantId/restart ### Parameters #### Path Parameters - **tenantId** (string) - Required - The tenant ID of the bot to restart. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` ```APIDOC ## POST /api/bots/:tenantId/stop ### Description Stop a specific bot instance. ### Method POST ### Endpoint /api/bots/:tenantId/stop ### Parameters #### Path Parameters - **tenantId** (string) - Required - The tenant ID of the bot to stop. ### Response #### Success Response (200) - **message** (string) - Confirmation message. ``` -------------------------------- ### Send Buttons with Media Header Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-meta/INTERACTIVE_MESSAGES.md Employ `sendButtonsMedia` to send reply buttons with an image or video as the header. This enhances visual appeal for product promotions or announcements. Specify the media type ('image' or 'video') and provide the media link. ```typescript // Con imagen await provider.sendButtonsMedia( '5491112345678', 'image', [{ body: 'Comprar' }, { body: 'Ver más' }], 'Producto destacado de la semana', 'https://example.com/producto.jpg' ) // Con video await provider.sendButtonsMedia( '5491112345678', 'video', [{ body: 'Me interesa' }], 'Mira nuestro nuevo producto', 'https://example.com/demo.mp4' ) ``` ```json { "messaging_product": "whatsapp", "recipient_type": "individual", "to": "5491112345678", "type": "interactive", "interactive": { "type": "button", "header": { "type": "image", "image": { "link": "https://example.com/producto.jpg" } }, "body": { "text": "Producto destacado de la semana" }, "action": { "buttons": [ { "type": "reply", "reply": { "id": "btn-0", "title": "Comprar" } }, { "type": "reply", "reply": { "id": "btn-1", "title": "Ver más" } } ] } } } ``` -------------------------------- ### Chatwoot API Direct Access Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/plugins/chatwoot/README.md Demonstrates how to access the Chatwoot API directly through the plugin for advanced operations. ```APIDOC ## Accessing Chatwoot API Directly ### Description The `chatwoot.getApi()` method provides direct access to the Chatwoot API, allowing you to perform operations like creating contacts and sending messages programmatically. ### Methods - **`findOrCreateContact(phoneNumber, name)`**: Finds an existing contact or creates a new one. - **`sendMessage(conversationId, message, type, mediaUrl?)`**: Sends a message to a specific conversation, optionally including media. ### Request Example ```javascript const api = chatwoot.getApi() // Create a contact manually const contact = await api.findOrCreateContact('+5215511223344', 'John Doe') // Send a message to an existing conversation await api.sendMessage(conversationId, 'Hello from the API!', 'outgoing') // Send a message with a media attachment from a URL await api.sendMessage(conversationId, 'See attached', 'outgoing', 'https://example.com/image.png') // Send a message with a media attachment from a local file path await api.sendMessage(conversationId, 'See attached', 'outgoing', '/tmp/photo.jpg') ``` ``` -------------------------------- ### Create a dynamic flow via API Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/manager/README.md Use curl to send a POST request to the /api/flows endpoint to create a new dynamic flow. Include the flow details in the JSON payload and set the appropriate headers. ```bash curl -X POST http://localhost:3000/api/flows \ -H "Content-Type: application/json" \ -H "X-API-Key: your-secret-key" \ -d '{ "id": "greeting", "name": "Greeting Flow", "keyword": ["hola", "hello"], "steps": [ { "answer": "¡Hola! Bienvenido", "delay": 500 }, { "answer": "¿En qué puedo ayudarte?" } ] }' ``` -------------------------------- ### Send Message with Buttons Programmatically with BuilderBot Source: https://github.com/codigoencasa/builderbot/blob/builderbot/packages/provider-gohighlevel/README.md Send a message with interactive buttons using the `sendMessage` method. Buttons are rendered as a numbered list and can be used for user selection. ```typescript // Send with buttons (rendered as numbered list) await provider.sendMessage('contact_phone_number', 'Choose an option:', { buttons: [ { body: 'Option 1' }, { body: 'Option 2' }, { body: 'Option 3' }, ] }) ```