### Building and Running the Webhook Starter (Shell) Source: https://github.com/oracle/bots-node-sdk/blob/master/examples/webhook/starter/README.md This sequence of shell commands demonstrates how to get the application running. It includes installing necessary Node.js dependencies using `npm install`, starting the server with `node index.js`, and sending a test message via `curl` to the local server endpoint. ```shell # install dependencies npm install # start server node index.js # send test message (will error without actual bot webhook channel configured) curl -H "Content-Type: application/json" -d @sample.req.json localhost:3000/test/message ``` -------------------------------- ### Initializing a New Project (Local CLI) Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/CLI.md Shows the steps to create a new project directory, initialize npm, install the SDK as a dev dependency, and then use the locally installed CLI to initialize the component package. ```shell mkdir bot-quickstart cd bot-quickstart npm init -y npm install --save-dev @oracle/bots-node-sdk $(npm bin)/bots-node-sdk init ``` -------------------------------- ### Starting the Development Service Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/ts/README.md Provides commands to start the local development service for the component package using npm start or the SDK CLI, including an option for debugging. ```shell npm start # or run with additional options npm run {{sdkBin}} -- service . # or run with debugger node --inspect $(npm bin)/{{sdkBin}} service . ``` -------------------------------- ### Starting Local Development Service (shell) Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/js/README.md Provides commands to start the local development service for the component package, including standard npm start, running with SDK CLI, and running with Node.js debugger. ```shell npm start # or run with additional options npm run {{sdkBin}} -- service . # or run with debugger node --inspect $(npm bin)/{{sdkBin}} service . ``` -------------------------------- ### Start Dev Server | Bots Node SDK | CLI Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/CLI.md Initiates a local development server for specified component packages or the current directory's package. Requires 'express' as a devDependency. Use 'npm start' for the dev dependency version. ```bash service [...packages] [options] ``` -------------------------------- ### Building and Running with Docker Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/ts/README.md Commands to build a Docker image for the component package and start the container using docker-compose, facilitating containerized deployment. ```shell npm run-script docker-build docker-compose up ``` -------------------------------- ### Making REST Calls with node-fetch (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md Provides examples of making asynchronous GET and POST requests using the node-fetch library. It shows how to handle the response status, parse JSON data, store data in context variables, and transition based on the outcome. ```JavaScript // Make a REST GET request const response = await fetch('http://some-backend-server-url'); if (response.status === 200) { const data = await response.json(); // Store the data in a context variable context.setVariable('myContextVar', data); context.transition('success'); } else { context.transition('failure'); } // Make a REST POST request let payload = ... const response = await fetch('http://some-backend-server-url',{ method: 'POST', body: payload}); if (response.status === 200) { context.transition('success'); } else { context.transition('failure'); } ``` -------------------------------- ### Initializing a New Project (Global CLI) Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/CLI.md Demonstrates how to use the `bots-node-sdk init` command to create a new component service package, either in the current directory or a specified path, assuming the SDK is installed globally. ```shell # Run in an empty directory bots-node-sdk init # or specify a specific path to create and populate the directory bots-node-sdk init my-project ``` -------------------------------- ### Testing Component Endpoints with Curl Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/ts/README.md Shows example curl commands to interact with the running local service, demonstrating how to retrieve component metadata and invoke custom components or entity event handlers. ```shell # get component metadata curl -X GET localhost:3000/components # invoke custom component curl -H "Content-Type: application/json" -d @./spec/test.cc.req.json localhost:3000/components/{{componentName}} # invoke entity event handler component curl -H "Content-Type: application/json" -d @./spec/test.eh.req.json localhost:3000/components/resolveentities/{{componentName}} ``` -------------------------------- ### Building and Running Docker Container (shell) Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/js/README.md Provides the shell commands to build the Docker image for the component package and start the container using docker-compose. ```shell npm run-script docker-build docker-compose up ``` -------------------------------- ### Testing Component Endpoints with Curl (shell) Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/js/README.md Shows example curl commands to interact with the running local component service, demonstrating how to retrieve metadata and invoke custom components or entity event handlers. ```shell # get component metadata curl -X GET localhost:3000/components # invoke custom component curl -H "Content-Type: application/json" -d @./spec/test.cc.req.json localhost:3000/components/{{componentName}} # invoke entity event handler component curl -H "Content-Type: application/json" -d @./spec/test.eh.req.json localhost:3000/components/resolveentities/{{componentName}} ``` -------------------------------- ### Adding an Entity Event Handler Component Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/CLI.md Provides an example of using the `bots-node-sdk init component` command to add a new component named `resolvePizza` of type `entityEventHandler` (`e`) to an existing project. ```shell bots-node-sdk init component resolvePizza e ``` -------------------------------- ### Debug Dev Server | Bots Node SDK | Windows CLI Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/CLI.md Starts the development server with Node.js debugger enabled on Windows. Directly references the SDK executable path in 'node_modules'. ```cmd node --inspect node_modules/@oracle/bots-node-sdk/bin/sdk.js service . ``` -------------------------------- ### Importing node-fetch for REST Calls Source: https://github.com/oracle/bots-node-sdk/blob/master/DATA_QUERY_EVENT_HANDLER.md Explains how to import the node-fetch library, recommended for making HTTP REST calls within event handlers, supporting Promises for asynchronous operations. Provides examples for both JavaScript and TypeScript. ```javascript const fetch = require("node-fetch"); ``` ```typescript import * as fetch from 'node-fetch'; ``` -------------------------------- ### Simple Component Test with MockConversation.any() in JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/testing/TESTING.md Provides a basic unit test example using Jest or similar framework. It demonstrates invoking the 'hello.world' component with a default empty mock conversation created via MockConversation.any() and asserts that no error occurred and replies were generated. ```javascript const Tester = require("@oracle/bots-node-sdk/testing"); const HelloWorldComponent = require('../components/hello.world'); describe('HelloWorldComponent', () => { it('should respond to a simple request', done => { const conv = Tester.MockConversation.any(); HelloWorldComponent.invoke(conv, (err) => { expect(err).toBeFalsy(); expect(conv.getReplies()).toBeDefined(); expect(conv.getReplies().length).toBeGreaterThan(0); done(); }); }); }); ``` -------------------------------- ### Making a REST GET Request with node-fetch Source: https://github.com/oracle/bots-node-sdk/blob/master/DATA_QUERY_EVENT_HANDLER.md Demonstrates how to perform an asynchronous HTTP GET request using the node-fetch library within an event handler. It shows how to await the response, check the HTTP status code (200), and parse the JSON body. ```javascript // Make a REST GET request const response = await fetch('http://some-backend-server-url'); if (response.status === 200) { const data = await response.json(); // Do something with the data... } ``` -------------------------------- ### Creating a Basic Attachment Message - JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_MODEL.md Provides a basic example of creating an attachment message using the `messageModel`. It shows how to use the `attachmentConversationMessage` function with the attachment type and URL. ```javascript const messageModel = context.getMessageModel(); let message = messageModel.attachmentConversationMessage(attachmentType, attachmentUrl); ``` -------------------------------- ### Debug Dev Server | Bots Node SDK | Linux/macOS CLI Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/CLI.md Starts the development server with Node.js debugger enabled on Linux/macOS. Locates the SDK executable using 'which' command. ```bash node --inspect $(which bots-node-sdk) service . ``` -------------------------------- ### Importing DataQuery Types in JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/DATA_QUERY_EVENT_HANDLER.md Provides a JavaScript example using require to import the types and interfaces needed for implementing data query event handlers from the Oracle Bots Node SDK. This helps IDEs provide code insight and completion for JavaScript handler files. ```JavaScript const { DataQueryContext, DataQueryEventHandler, DataQueryEventHandlers, DataQueryEventHandlerMetadata, ChangeUISettingsEvent, DataQueryUISettings, ChangeResponseDataEvent, ChangeBotMessagesEvent, NonRawMessagePayload, ChangeAttributeUISettingsEvent, ReadOnlyFieldMetadata, FormatAttributeEvent } = require ('@oracle/bots-node-sdk/lib'); ``` -------------------------------- ### Using Postback Keywords with Text Message (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_MODEL.md Provides an example of creating postback keywords that map user text input (like "1" or "small") to specific postback payloads containing variables. These keywords are then attached to a text message to enable keyword-based interaction on channels without buttons. Requires `context` and `messageModel`. ```JavaScript const messageModel = context.getMessageModel(); let keywords = []; keywords.push( messageModel.postbackKeyword(["1","first"], {"variables" : {"pizzaSize": "small"}})); keywords.push( messageModel.postbackKeyword(["2","second"], {"variables" : {"pizzaSize": "medium"}})); keywords.push( messageModel.postbackKeyword(["3","third"], {"variables" : {"pizzaSize": "large"}})); let textMessage = messageModel.textConversationMessage('What pizza size do you want?\n1. Small\n2. Medium\n3. Large', undefined, undefined, undefined, keywords); context.reply(textMessage); ``` -------------------------------- ### Accessing Component Property Value (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md A complete custom component example demonstrating how to define component properties in the metadata and retrieve their values using context.properties() within the invoke function. ```JavaScript module.exports = { metadata: { name: 'greeting', properties: { name: { required: true, type: 'string' } } }, invoke: async (context) => { // Retrieve the value of the 'name' component property. const { name } = context.properties() || ''; context.reply(`Hello ${name}`); } } ``` -------------------------------- ### Creating an Attachment Message with URL Actions - JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_MODEL.md Extends the attachment message example to include URL actions. It demonstrates creating URL action objects using `urlActionObject` and adding them to the `attachmentConversationMessage`. ```javascript const videosUrl="https://example.com/videos.html"; const tutorialsUrl = "https://example.com/tutorials.html"; var urlVideoAction =messageModel.urlActionObject('More Videos', undefined, videosUrl); var urlTutorialAction = messageModel.urlActionObject('More Tutorials', undefined, tutorialsUrl); let message = messageModel.attachmentConversationMessage(attachmentType, attachmentUrl, [urlVideoAction, urlTutorialAction]); ``` -------------------------------- ### Comprehensive Component Test with MockRequest and MockConversation in JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/testing/TESTING.md Presents a more detailed unit test example. It shows how to create a MockRequest with specific properties and variables, build a MockConversation from it, invoke the component, use a spy to track method calls (like 'variable'), and make assertions on the component's output and behavior. ```javascript const Tester = require("@oracle/bots-node-sdk/testing"); const HelloWorldComponent = require('../components/hello.world'); it('should respond to a request with params', done => { // create a conversation payload iwth properties and variables const properties = { name: 'Unit Tester' }; const variables = { hello: 'Howdy' }; const request = Tester.MockRequest(null, properties, variables); const conv = Tester.MockConversation.fromRequest(request); // stub/watch the variable method const varSpy = spyOn(conv, 'variable').and.callThrough(); // invoke the component HelloWorldComponent.invoke(conv, (err) => { expect(err).toBeUndefined(); expect(conv.getReplies()).toBeDefined(); // check that the spy was called (once as getter, once as setter) expect(varSpy).toHaveBeenCalledTimes(2); // make assertions on the responses ``` -------------------------------- ### Building Arguments and Creating TableForm Message (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_MODEL.md This example demonstrates how to build the arguments required for `tableFormConversationMessage` using helper functions like `tableHeaderColumn`, `tableColumn`, `tableRow`, `formField`, `form`, and `paginationInfo`. It then calls `tableFormConversationMessage` with the constructed arguments. ```javascript const people = [ {firstName: "Bob", lastName: "Dole"} ,{firstName: "John", lastName: "Doe"} ,{firstName: "Jane", lastName: "Doe"}] let headings = []; headings.push( messageModel.tableHeaderColumn("First Name")); let rows = []; let forms = []; for (let p of people) { // create row let columns = []; columns.push(messageModel.tableColumn(p.firstName)); rows.push(messageModel.tableRow(columns)); // create form let fields = []; fields.push(messageModel.formField("Last Name", p.lastName)); forms.push(messageModel.form("View details", fields)); } const paginationInfo = messageModel.paginationInfo(5,3,0, context.translate("systemConfiguration_paginationStatus",1,3,5)); let message = messageModel.tableFormConversationMessage(headings, rows, forms, 2, null, paginationInfo); ``` -------------------------------- ### Testing ResolveEntities Event Handler Component (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/testing/TESTING.md Provides unit tests for the 'resolveExpense' event handler component using the @oracle/bots-node-sdk/testing framework. It includes setup for the component shell and variables, and test cases for the 'publishMessage' and 'validate' handlers. ```javascript 'use strict'; const { ComponentRegistry, ComponentShell } = require("@oracle/bots-node-sdk/lib"); const Tester = require("@oracle/bots-node-sdk/testing"); const ResolveExpenseComponent = require('../components/resolveExpense'); describe('ResolveExpenseComponent', () => { // setup shell and expense composite bag variable for different tests let registry, shell, variables; beforeAll(() => { registry = ComponentRegistry.create(ResolveExpenseComponent); shell = ComponentShell(null, registry); let items = []; items.push(Tester.MockCompositeBagItem("Type","ENTITY","ExpenseType")); items.push(Tester.MockCompositeBagItem("Amount","ENTITY","CURRENCY")); items.push(Tester.MockCompositeBagItem("Date","ENTITY","DATE")); variables = {expense: Tester.MockCompositeBagEntityVariable("Expense",items)}; }); it('should prompt expense type', done => { // set up request with publishMessage event let events = [Tester.MockResolveEntitiesEvent('publishMessage')] let req = Tester.MockEventHandlerRequest('expense','Type','Hi','What do you want to expense?', events, variables); shell.invokeResolveEntitiesEventHandler('resolveExpense', req, (err, res) => { expect(err).toBeFalsy(); expect(res.messages).toBeDefined(); expect(res.messages.length).toBe(1); expect(res.messages[0].text).toBe('What do you want to expense?'); expect(res.validationResults).toEqual({}); expect(res.keepProcessing).toBeFalsy(); expect(res.cancel).toBeFalsy(); done(); }); }); it('should validate expense amount', done => { // set up request with validate amount event let amount = {entityName: 'CURRENCY',amount: 3, currency: 'dollar', totalCurrency: '3.0 dollar'}; let events = [Tester.MockResolveEntitiesEvent('validate',false,{newValue: amount},"Amount")] let req = Tester.MockEventHandlerRequest('expense','Type','$3','What is expense date?', events, variables); shell.invokeResolveEntitiesEventHandler('resolveExpense', req, (err, res) => { expect(err).toBeFalsy(); expect(res.messages).toBeUndefined(); expect(res.validationResults).toEqual({"Amount.validate": false}); expect(res.entityResolutionStatus.validationErrors).toEqual({'Amount': "Amounts below 5 dollar cannot be expensed. Enter a higher amount or type 'cancel'."}); expect(res.keepProcessing).toBeTrue(); expect(res.cancel).toBeFalsy(); done(); }); }); }); ``` -------------------------------- ### Example Quotes Data Structure (JSON) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md This JSON snippet shows the expected structure of the `Quotes.json` file used by the JavaScript code. It is an array of objects, where each object represents a quote and has two properties: `quote` (the quote text) and `origin` (the source or author of the quote). ```JSON [ { "quote": "The man who moves a mountain begins by carrying away small stones.", "origin": "Confucius" }, { "quote": "If you always do what you’ve always done, you’ll always get what you’ve always got.", "origin": "Henry Ford" }, ... ] ``` -------------------------------- ### Making REST Calls with node-fetch (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/ENTITY_EVENT_HANDLER.md Demonstrates how to perform asynchronous GET and POST requests using the `node-fetch` library within a bots-node-sdk event handler, including checking the response status and processing the results or adding messages. ```javascript // Make a REST GET request const response = await fetch('http://some-backend-server-url'); if (response.status === 200) { const data = await response.json(); // Do something with the data... } // Make a REST POST request let payload = ... const response = await fetch('http://some-backend-server-url',{ method: 'POST', body: payload}); if (response.status === 200) { context.addMessage('Transaction successful'); } else { context.addMessage('Transaction failed'); } } ``` -------------------------------- ### Format Attribute Value (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/DATA_QUERY_EVENT_HANDLER.md Demonstrates using the attribute-level `format` event to customize an attribute's display value. The example formats the 'hiredate' attribute value into a readable date string using `new Date(event.attributeValue).toDateString()`. ```JavaScript hiredate: { format: async (event: FormatAttributeEvent, context: DataQueryContext): Promise => { return new Date(event.attributeValue).toDateString(); } } ``` -------------------------------- ### Implementing DataQueryEventHandler in TypeScript Source: https://github.com/oracle/bots-node-sdk/blob/master/DATA_QUERY_EVENT_HANDLER.md Demonstrates how to create a custom data query event handler class in TypeScript by implementing the DataQueryEventHandler interface. It includes implementations for the required metadata and handlers methods, showing examples for entity-level events (changeUISettings, changeResponseData, changeBotMessages) and attribute-level events (changeUISettings, format). ```TypeScript import { DataQueryContext, DataQueryEventHandler, DataQueryEventHandlers, DataQueryEventHandlerMetadata, ChangeUISettingsEvent, DataQueryUISettings, ChangeResponseDataEvent, ChangeBotMessagesEvent, NonRawMessagePayload, ChangeAttributeUISettingsEvent, ReadOnlyFieldMetadata, FormatAttributeEvent } from '@oracle/bots-node-sdk/lib'; export class MySqlQueryEventHandler implements DataQueryEventHandler { public metadata(): DataQueryEventHandlerMetadata { return { name: 'mySqlQueryEventHandler', eventHandlerType: 'DataQuery' }; } public handlers(): DataQueryEventHandlers { return { entity: { /** * Handler to change overall UI settings * @param {ChangeUISettingsEvent} event * @param {DataQueryContext} context * @returns {DataQueryUISettings} the changed UI settings */ changeUISettings: async (event: ChangeUISettingsEvent, context: DataQueryContext): Promise => { return event.settings; }, /** * Handler to change the query result data * @param {ChangeResponseDataEvent} event * @param {DataQueryContext} context * @returns {any} the changed query result data */ changeResponseData: async (event: ChangeResponseDataEvent, context: DataQueryContext): Promise => { return context.getQueryResult(); }, /** * Handler to change the candidate bot messages that will be sent * @param {ChangeBotMessagesEvent} event * @param {DataQueryContext} context * @returns {NonRawMessagePayload[]} the changed bot messages */ changeBotMessages: async (event: ChangeBotMessagesEvent, context: DataQueryContext): Promise => { return event.messages; } }, attributes: { SomeAttributemName: { // TODO change to a valid attribute name /** * Handler to change UI settings for an attribute * @param {ChangeAttributeUISettingsEvent} event * @param {DataQueryContext} context * @returns {ReadOnlyFieldMetadata} the changed attribute UI settings */ changeUISettings: async (event: ChangeAttributeUISettingsEvent, context: DataQueryContext): Promise => { return event.settings; }, /** * Handler to change the formatting of an attribute value * @param {FormatAttributeEvent} event * @param {DataQueryContext} context * @returns {any} the formatted attribute value */ format: async (event: FormatAttributeEvent, context: DataQueryContext): Promise => { return event.attributeValue; } } // add more attributes and their handlers here } }; } } ``` -------------------------------- ### Initializing WebhookClient and Setting Up Routes - Node.js Source: https://github.com/oracle/bots-node-sdk/blob/master/WEBHOOK.md This snippet demonstrates how to set up an Express application, initialize the Oracle Bots Node SDK, create a WebhookClient instance using channel configuration, handle errors, and define routes for receiving messages from the bot and sending messages to the bot. It shows the basic structure for integrating a webhook channel. ```javascript const express = require('express'); const OracleBot = require('@oracle/bots-node-sdk'); const app = express(); OracleBot.init(app); // implement webhook const { WebhookClient, WebhookEvent } = OracleBot.Middleware; const channel = { url: process.env.BOT_WEBHOOK_URL, secret: process.env.BOT_WEBHOOK_SECRET }; const webhook = new WebhookClient({ channel: channel }); webhook.on(WebhookEvent.ERROR, console.error); // receive errors // receive bot messages app.post('/bot/message', webhook.receiver()); // receive bot messages webhook.on(WebhookEvent.MESSAGE_RECEIVED, message => { // format and send to messaging client... }); // send messages to bot (example) app.post('/user/message', (req, res) => { let message = {/* ... */}; // format according to MessageModel webhook.send(message) .then(() => res.send('ok'), e => res.status(400).end()); }); ``` -------------------------------- ### CLI Usage and Commands Overview Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/CLI.md Displays the general usage syntax for the bots-node-sdk CLI and lists the available top-level commands. ```text Usage: bots-node-sdk [command] [arguments][options] bots-node-sdk Options: -h --help Display help and usage information -v --version Print version information Commands: init Create and initialize a component package init component Add a component to a package service Start a service with one or more component packages pack Create a deployable component artifact ``` -------------------------------- ### Project Directory Structure (text) Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/js/README.md Illustrates the standard directory layout for an ODA Component Package, showing key files and directories like components, main.js, package.json, and Docker-related files. ```text . ├── .npmignore ├── components │ └── ... ├── main.js ├── package.json ├── Dockerfile ├── docker-compose.yml └── spec └── ... ``` -------------------------------- ### Project Directory Structure Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/ts/README.md Illustrates the standard directory layout for an ODA Component Package, highlighting key files and directories like src, package.json, Dockerfile, and spec. ```text . ├── .npmignore ├── src │ └── main.ts │ └── components │ └── ... ├── package.json ├── Dockerfile ├── docker-compose.yml ├── tsconfig.json └── spec └── ... ``` -------------------------------- ### Implementing a Simple Custom Component in JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/testing/TESTING.md Defines a basic custom component named 'hello.world' with a required 'name' property. The component reads a variable, creates a reply message using the variable and property, sets a new variable, and transitions the state. ```javascript module.exports = { metadata: () => ({ name: 'hello.world', properties: { name: {required: true, type: 'string'}}, supportedActions: [] }), invoke: (conversation, done) => { // read 'hello' variable const hi = conversation.variable('hello') || 'Hi'; // create a response conversation.reply(`${hi} ${conversation.properties().name}.`); // set a variable conversation.variable('greeted', true); // transition state conversation.transition(); done(); } }; ``` -------------------------------- ### Setting Webhook Configuration Environment Variables (Shell) Source: https://github.com/oracle/bots-node-sdk/blob/master/examples/webhook/starter/README.md These shell commands show how to set the `BOT_WEBHOOK_URL` and `BOT_WEBHOOK_SECRET` environment variables. These variables are used by the application to configure the Oracle Bot Webhook channel, although they can be left empty for basic testing. ```shell BOT_WEBHOOK_URL="https://..." BOT_WEBHOOK_SECRET="..." ``` -------------------------------- ### Packaging Component Package (shell) Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/js/README.md Details the commands used to package the component package into a .tgz file for deployment, including the standard npm pack and using the SDK CLI for validation and packaging. ```shell npm pack # or validate and package with the {{sdkName}} command line npm run {{sdkBin}} -- pack . ``` -------------------------------- ### Accessing a Context Variable (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md Demonstrates how to retrieve the value of a context variable using context.getVariable(), often after getting the variable name from component properties. Includes a check if the property is defined. ```JavaScript const { latitudeVariable } = context.properties(); if (latitudeVariable) { let _latitude = context.getVariable(latitudeVariable); // ... } else { throw new Error('State is missing latitudeVariable property.'); } ``` -------------------------------- ### Initialize Oracle Bots Node SDK Project with TypeScript (Short Option) Source: https://github.com/oracle/bots-node-sdk/blob/master/README.md This command provides a shorter alternative to initialize a new Oracle Bots Node SDK project named 'MyComponentService' using TypeScript. It uses the shorthand '-l t' option instead of the full '--language typescript'. ```text bots-node-sdk init MyComponentService -l t ``` -------------------------------- ### Packaging the Component for Deployment Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/templates/ccpackage/ts/README.md Commands to package the component package into a .tgz file using npm pack or the SDK CLI, suitable for deployment to the Embedded Container service. ```shell npm pack # or validate and package with the {{sdkName}} command line npm run {{sdkBin}} -- pack . ``` -------------------------------- ### Change Attribute Display Settings (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/DATA_QUERY_EVENT_HANDLER.md Uses the attribute-level `changeUISettings` event to modify how an attribute is displayed. The example hides the 'hiredate' attribute when the layout is 'tableForm' while ensuring it remains visible in the form layout by setting `event.settings.displayInTable` and `event.settings.displayInForm`. ```JavaScript hiredate: { changeUISettings: async (event: ChangeAttributeUISettingsEvent, context: DataQueryContext): Promise => { if (context.getLayout() === 'tableForm') { event.settings.displayInTable = false; event.settings.displayInForm = true; } return event.settings; } } ``` -------------------------------- ### Initialize Oracle Bots Node SDK Project with TypeScript Source: https://github.com/oracle/bots-node-sdk/blob/master/README.md This command initializes a new Oracle Bots Node SDK project named 'MyComponentService' and configures it to use TypeScript by explicitly specifying the '--language typescript' option. This sets up the project structure for TypeScript development. ```text bots-node-sdk init MyComponentService --language typescript ``` -------------------------------- ### Package Components | Bots Node SDK | CLI Source: https://github.com/oracle/bots-node-sdk/blob/master/bin/CLI.md Packages component packages into a .tgz file for various deployment targets (Express, Embedded, Mobile Hub). Supports dry run and service type options. ```bash pack [options] ``` -------------------------------- ### Importing node-fetch for REST Calls (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md Shows the standard Node.js require syntax to import the node-fetch library, which is recommended for making HTTP REST calls within custom components. ```JavaScript const fetch = require("node-fetch"); ``` -------------------------------- ### Processing User Message with TypeScript Casting in JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_FACTORY.md Shows how to retrieve the last user message and process different message types using instanceof checks, similar to the previous example, but includes TypeScript casting (as MessageType) for design-time validation and code completion. ```javascript if (context.getRequest().state === context.getRequest().previousState) { const um = context.getUserMessage(); if (um instanceof TextMessage) { const utm = um as TextMessage; const text = utm.getText(); // handle text } else if (um instanceof PostbackMessage) { const upm = um as PostbackMessage; const postback = upm.getPostback(); // handle postback payload ... } ``` -------------------------------- ### Creating a Card Message with Postback Actions - JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_MODEL.md Shows how to construct a card message using the `messageModel`. It demonstrates creating individual cards with `cardObject`, adding postback actions to cards, and finally assembling the message with `cardConversationMessage`. ```javascript const messageModel = context.getMessageModel(); let cards = []; cards.push(messageModel.cardObject('4 Dozen Oranges','4 dozen Mandarin oranges in a wooden crate.', undefined, undefined, [messageModel.postbackActionObject('Oranges', undefined, { action: 'oranges' })])); cards.push(messageModel.cardObject('Carton of Grapes', '10kg ripe grapes in a protected carton.', undefined, undefined, [messageModel.postbackActionObject('Grapes', undefined, { action: 'grapes' })])); let message = messageModel.cardConversationMessage('vertical', cards); ``` -------------------------------- ### Controlling Flow with keepTurn and transition (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md Demonstrates how to use context.reply, context.keepTurn(true), and context.transition("success") within an invoke function to send a reply, prevent waiting for user input, and transition to a specified action. ```JavaScript invoke: async (context) => { ... context.reply(payload); context.keepTurn(true); context.transition ("success"); } ``` -------------------------------- ### Importing Config Module Directly (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/config/README.md This snippet shows the direct method of requiring the `Config` module by specifying its path within the `@oracle/bots-node-sdk` package. This is a standard Node.js `require` call targeting the specific module file. ```javascript const Config = require('@oracle/bots-node-sdk/config'); ``` -------------------------------- ### Creating Summary Message in Composite Bag resolved Handler - JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/ENTITY_EVENT_HANDLER.md This code snippet shows how to generate a summary message when a composite bag entity has been successfully resolved. It uses `context.getDisplayValues()` to get a list of name-value pairs for all items in the composite bag. The `reduce` function is then used to format these pairs into a multi-line string, which is added to the conversation using `context.addMessage()`. ```javascript resolved: async (event, context) => { let msg = 'Got it. Here is a summary of your expense:'; msg += context.getDisplayValues().reduce((acc, curr) => `${acc}\n${curr.name}: ${curr.value}`, ''); context.addMessage(msg); } ``` -------------------------------- ### Implementing Basic Custom Component (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md This snippet shows the standard structure for a custom component in JavaScript, exporting `metadata` and `invoke`. The `invoke` function accesses component properties, performs simple logic (checking the day of the week), sends multiple messages using `context.reply()`, and controls the flow using `context.transition()`. It requires the `@oracle/bots-node-sdk` library. ```javascript module.exports = { metadata: { name: 'helloWorld', properties: { human: { required: true, type: 'string' } }, supportedActions: ['weekday', 'weekend'] }, /** * invoke method gets called when the custom component state is executed in the dialog flow * @param {CustomComponentContext} context */ invoke: async (context) => { // Retrieve the value of the 'human' component property. const { human } = context.properties(); // determine date const now = new Date(); const dayOfWeek = now.toLocaleDateString('en-US', { weekday: 'long' }); const isWeekend = [0, 6].indexOf(now.getDay()) > -1; // Send two messages, and transition based on the day of the week context.reply(`Greetings ${human}`) .reply(`Today is ${now.toLocaleDateString()}, a ${dayOfWeek}`) .transition(isWeekend ? 'weekend' : 'weekday'); } } ``` -------------------------------- ### Importing node-fetch for REST Calls (TypeScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md Shows the standard TypeScript import syntax to import the node-fetch library, which is recommended for making HTTP REST calls within custom components. ```TypeScript import fetch from 'node-fetch'; ``` -------------------------------- ### Updating Bag Items in Entity Validation Handler - JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/ENTITY_EVENT_HANDLER.md This example demonstrates how to use the `validate` event handler for a specific bag item (e.g., 'Receipt'). It checks the input type and value, and if valid (like a specific image URL), it uses `context.setItemValue()` to programmatically set the values of other bag items ('Amount', 'Date') based on the input. It also adds a confirmation message or a validation error using `context.addMessage()` or `context.addValidationError()`. ```javascript items: { Receipt: { validate:async (event, context) => { if (event.newValue.type==='image') { if (event.newValue.url==='https://upload.wikimedia.org/wikipedia/commons/0/0b/ReceiptSwiss.jpg') { let amount = {"entityName": "CURRENCY", "amount": 54.5,"currency":"chf","totalCurrency": "CHF 54.50 scanned from receipt"}; let date = {"entityName": "DATE", "date": 1185753600000,"originalString": "30 july 2007 scanned from receipt"}; context.setItemValue("Amount",amount); context.setItemValue("Date",date); context.addMessage(`Receipt scanned, amount set to CHF 54.50 and date set to 30 july 2007`); } } else { context.addValidationError("Receipt",`Receipt must be an image, cannot be ${event.newValue.type}`); } } ``` -------------------------------- ### Invoking REST API from Event Handler in Oracle Bots Node SDK (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/ENTITY_EVENT_HANDLER.md This example shows how to make an asynchronous REST API call from an entity 'resolved' event handler. It uses 'node-fetch' (or a similar promise-based HTTP library) with the 'await' keyword to send a POST request containing the resolved entity payload to an external endpoint. It checks the response status and adds a confirmation message if successful, including basic error logging. ```javascript entity: { resolved:async (event, context) => { try { let payload = context.getEntity(); // do some transformations on entity JSON payload if needed... const response = await fetch('http://expense-backend-server/expense',{ method: 'POST', body: payload}); if (response.status === 200) { context.addMessage(`Thank you for submitting your ${context.getItemValue('Type')} expense`); } } catch (error) { context.logger().info("Error invoking API: "+error); } } } ``` -------------------------------- ### Importing Testing Utilities (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/testing/TESTING.md This snippet demonstrates how to import the necessary classes, MockConversation and MockRequest, from the @oracle/bots-node-sdk/testing module for use in unit tests. ```javascript const { MockConversation, MockRequest } = require('@oracle/bots-node-sdk/testing'); ``` -------------------------------- ### Apache License 2.0 Boilerplate Text Source: https://github.com/oracle/bots-node-sdk/blob/master/THIRD_PARTY_LICENSES_DEV.txt Standard boilerplate notice recommended by the Apache License, Version 2.0, to be attached to files to indicate that the work is licensed under Apache 2.0. Users should replace the bracketed fields with their specific copyright year and name. ```Text Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` -------------------------------- ### Creating a Text Message with Postback Keywords Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_FACTORY.md Illustrates how to use postback keywords to map simple text input to a postback payload, useful for channels without button support. Shows creating a text message and adding keywords using the static `createKeyword` method. ```javascript const mf = context.getMessageFactory(); const message = mf.createTextMessage('What pizza size do you want?\n1. Small\n2. Medium\n3. Large') .addKeyword(mf.createKeyword({"variables" : {"pizzaSize": "small"}},["1","first"])) .addKeyword(mf.createKeyword({"variables" : {"pizzaSize": "medium"}},["2","medium"])) .addKeyword(mf.createKeyword({"variables" : {"pizzaSize": "large"}},["3","large"])); context.reply(message); ``` -------------------------------- ### Importing node-fetch with require (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/ENTITY_EVENT_HANDLER.md Imports the `node-fetch` library using the `require` syntax, typically used in Node.js environments, to enable making HTTP requests. ```javascript const fetch = require("node-fetch"); ``` -------------------------------- ### Initializing OracleBot SDK with Custom Logger - Node.js Source: https://github.com/oracle/bots-node-sdk/blob/master/WEBHOOK.md This snippet shows how to initialize the Oracle Bots Node SDK with a custom logger configuration. Providing a logger object allows for more verbose logging details during SDK operations, which can be useful for debugging. ```javascript OracleBot.init(app, { logger: console, }); ``` -------------------------------- ### Importing Util Module Directly (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/util/README.md This snippet shows how to import the Util module by requiring it directly from its specific path within the @oracle/bots-node-sdk package. ```javascript const Util = require('@oracle/bots-node-sdk/util'); ``` -------------------------------- ### Adding Slack Channel Extension for Date Picker (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_MODEL.md Illustrates creating a text message and then using `addChannelExtensions` to configure Slack to display a date picker UI element when the message is presented to the user. Requires an existing `messageModel` instance. ```JavaScript let textMessage = messageModel.textConversationMessage('What is the expense date'); messageModel.addChannelExtensions(textMessage, 'slack', {"showDatePicker": true}); ``` -------------------------------- ### Importing Config Module via Destructuring (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/config/README.md This snippet demonstrates importing the `Config` module using object destructuring from the main `@oracle/bots-node-sdk` package. This method assumes that the main package exports the `Config` module as a named export. ```javascript const { Config } = require('@oracle/bots-node-sdk'); ``` -------------------------------- ### Full MIT License Text Source: https://github.com/oracle/bots-node-sdk/blob/master/THIRD_PARTY_LICENSES_DEV.txt The complete text of the MIT License, a permissive free software license. This text is typically included verbatim in a LICENSE file distributed with software licensed under the MIT terms. ```Text Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ``` -------------------------------- ### Importing Util Module from SDK Root (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/util/README.md This snippet demonstrates how to import the Util module using object destructuring when requiring the main @oracle/bots-node-sdk package. ```javascript const { Util } = require('@oracle/bots-node-sdk'); ``` -------------------------------- ### Importing Lib from SDK Root (CommonJS Destructuring) Source: https://github.com/oracle/bots-node-sdk/blob/master/lib/README.md This snippet shows an alternative way to import the 'Lib' object directly from the root of the '@oracle/bots-node-sdk' package using CommonJS 'require' with object destructuring. This is often preferred for importing specific named exports. ```javascript const { Lib } = require('@oracle/bots-node-sdk'); ``` -------------------------------- ### Importing MessageModel Class (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_MODEL.md Demonstrates how to import the `MessageModel` class directly from the Oracle Bots Node SDK library for independent use outside of a custom component or webhook context. ```JavaScript const { MessageModel } = require('@oracle/bots-node-sdk/lib'); ``` -------------------------------- ### Creating a Mock Request Object in JavaScript Source: https://github.com/oracle/bots-node-sdk/blob/master/testing/TESTING.md Provides the function signature and description for the MockRequest constructor from the @oracle/bots-node-sdk/testing package. It is used to create mock request objects for component middleware handling, allowing specification of message payload, properties, variables, and channel type. ```javascript /** * Create a mock request for component middleware handling. * Individual properties and variables may be specified by modifying the result. * @function module:Testing.MockRequest * @param {*} [messagePayload] - message payload * @param {*} [properties] - conversation properties * @param {*} [variables] - conversation variables * @param {string} [type] - channel type */ function MockRequest(messagePayload = {}, properties = {}, variables = {}, type = 'test') { // ... } ``` -------------------------------- ### Creating a Text Message with Postback Action Buttons Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_FACTORY.md Explains how to create a text message and add action buttons to it using the `addAction` and `createPostbackAction` methods. ```javascript const mf = context.getMessageFactory(); const message = mf.createTextMessage('Do you want another quote?') .addAction(mf.createPostbackAction('Yes', { isNo: false })) .addAction(mf.createPostbackAction('No', { isNo: true })); ``` -------------------------------- ### Importing Lib from SDK Lib Module (CommonJS) Source: https://github.com/oracle/bots-node-sdk/blob/master/lib/README.md This snippet demonstrates how to import the entire 'lib' module using the CommonJS 'require' syntax and assign it to a variable named 'Lib'. This is a standard way to require modules in Node.js. ```javascript const Lib = require('@oracle/bots-node-sdk/lib'); ``` -------------------------------- ### Handle User Input and Prompt Again (JavaScript) Source: https://github.com/oracle/bots-node-sdk/blob/master/CUSTOM_COMPONENT.md This JavaScript code snippet shows the `invoke` function logic for a component that repeatedly prompts the user. It checks for a 'No' postback action to transition out of the loop. Otherwise, it displays a random quote and presents 'Yes'/'No' buttons using postback actions to continue or stop prompting. It explicitly manages the turn using `context.keepTurn`. ```JavaScript invoke: async (context) => { const quotes = require("./json/Quotes.json"); const quote = quotes[Math.floor(Math.random() * quotes.length)]; // Check if postback action is issued and postback is from this component rendering. // This ensures that the component only responds to its own postback actions. const um = context.getUserMessage() if (um instanceof PostbackMessage && um.getPostback() && um.getPostback()['system.state'] === context.getRequest().state && um.getPostback().isNo) { context.keepTurn(true); context.transition(); } else { // Show the quote of the day. context.reply(`'${quote.quote}'`); context.reply(`Quote by: ${quote.origin}`); // Create a single message with two buttons to request another quote or not. let actions = []; const mf = context.getMessageFactory(); const message = mf.createTextMessage('Do you want another quote?') .addAction(mf.createPostbackAction('Yes', { isNo: false })) .addAction(mf.createPostbackAction('No', { isNo: true })); context.reply(message); // Although reply() automatically sets keepTurn to false, it's good practice to explicitly set it so that it's // easier to see how you intend the component to behave. context.keepTurn(false); } } ``` -------------------------------- ### Creating a Text Message with Channel Extension (Slack Date Picker) Source: https://github.com/oracle/bots-node-sdk/blob/master/MESSAGE_FACTORY.md Shows how to create a text message and use `setChannelExtensionProperty` to configure a channel-specific feature, like displaying a date picker in Slack for a date prompt. Requires importing `ChannelType`. ```javascript // import ChannelType const { ChannelType } = require('@oracle/bots-node-sdk/typings/lib2'); const mf = context.getMessageFactory(); const textMessage = mf.createTextMessage('What is the expense date') .setChannelExtensionProperty(ChannelType.slack, 'showDatePicker', true); ```