Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@oracle/bots-node-sdk

Package Overview
Dependencies
Maintainers
2
Versions
42
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@oracle/bots-node-sdk

Oracle Bots SDK for custom component development and webhook integrations

  • 2.3.3
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
68
increased by44.68%
Maintainers
2
Weekly downloads
 
Created
Source

Oracle Bots Node.js SDK

This SDK is the main developer resource for Oracle Bots integrations in a Node.js express environment. This package provides two primary solutions for custom implementations against the Oracle Bots platform: Running Custom Component Services and/or Webhook Channels.

  • Installation - Installation and usage information.
  • CLI - Developer tools and utilities for getting started.
  • Custom Component - Services to enrich a conversation flow with custom logic, API integrations, messages, and more.
  • Webhook - Integrate with custom messaging channels using incoming/outgoing webhook.
  • Documentation - Full SDK documentation.

npm version wercker status


Installation

npm install @oracle/bots-node-sdk

Most often, this package is installed as a dependency of an express application where any appropriate middleware is then applied.

The SDK also ships CLI tools with some quick start project generators.

CLI

This package includes several command line capabilties designed to facilitate custom development with the SDK itself. See complete documentation here

npx @oracle/bots-node-sdk --help

Basic Setup

const express = require('express');
const OracleBot = require('@oracle/bots-node-sdk');

const app = express();
OracleBot.init(app);
// implement custom bot services... (see below)

Custom Logging

If verbose logging details are desired, you may configure a logging utility of your choice, and initialize the SDK accordingly.

OracleBot.init(app, {
  logger: console,
});

Custom Components

Each state within a Bot flow calls a component to perform actions ranging from basic interactions like user input and outputting response text to some service-specific actions like fulfilling an order or booking a flight.

The platform has many built-in components to support basic actions like setting variables, allowing OAuth, and enabling user input. In cases where your bot design calls for unique actions outside of these functions, you’ll be writing Custom Components. These allow your bot to call REST APIs, implement business logic, transition state, customize messages, etc.

This package provides the necessary middleware and libraries for incorporating Custom Components into your Bot dialog.

QuickStart for Custom Components

Custom Component Service

The API for exposing custom components to your bot is established using the middleware included in this package.

Initializing the component middleware includes some basic configurations. Most important is the register option, which specifies component paths or component objects - telling the service where Custom Component sources are located within your project.

  • cwd string - Top level directory to which all other paths are relative. (__dirname is recommended).
  • register (string|object(s)|function)[] - Defines component registry from array of the paths to resolve.
    • String paths may also be directories, which are scanned recursively and added to the registry.
    • Multiple components may also be exported from a single file.
const express = require('express');
const OracleBot = require('@oracle/bots-node-sdk');

const app = express();
OracleBot.init(app);

// implement custom component api
OracleBot.Middleware.customComponent(app, {
  baseUrl: '/components',
  cwd: __dirname,
  register: [
    './path/to/a/component',
    './path/to/other/components',
    './path/to/a/directory',
  ]
});

Custom Component Code

Using the @oracle/bots-node-sdk for Custom Component development supports a flexible approach to authoring components. This means that many structures for the implementation of a Custom Component are possible. Whatever the approach, the fundamental interface is required as follows:

// interface for a custom component implementation
{
  metadata(): {name: string, properties?: {[name:string]: string}, supportedActions?: string[]};
  invoke(conversation: Conversation, done: () => {}): void;
}

One supported implementation is to use a simple object with metadata and invoke members:

// mycomponent.js
module.exports = {
  metadata: () => ({
    name: 'my.custom.component',
    properties: {},
    supportedActions: []
  }),
  invoke: (conversation, done) => {
    conversation.reply('hello').transition();
    done();
  }
}

You may also wish to define a component by exporting class(es) and optionally extending the ComponentAbstract class for additional convenience members. NOTE Component classes are instantiated as singletons.

// mycomponent.js
const { ComponentAbstract } = require('@oracle/bots-node-sdk/lib');

module.exports = class MyComponent extends ComponentAbstract {
  metadata() {
    return {
      name: 'my.custom.component',
      properties: {},
      supportedActions: []
    }
  }
  invoke(conversation, done) {
    conversation.reply('hello').transition();
    done();
  }
}

Webhook

The fundamental mechanism for sending and receiving messages with the Bot platform is through asynchronous inbound and outbound messaging. The platform supports several built-in channels natively, and webhook for any other messaging service or client.

Implementing webhook as a channel can differ greatly across clients. Generally each client uses a unique message format, and different mechanisms for sending or receiving messages. This package includes these necessary integration tools.

QuickStart for Webhook

Webhook Client

WebhookClient is a flexible library for integrating with webhook channels configured within your bot. Refer to the documentation and examples to further understand ways the webhook client may be implemented.

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());
});

TIP send() supports an optional channel as its second argument, thereby handling request-specific channel determination.

Webhook Utilities

While WebhookClient is designed to support the majority of possible integration types, there may be cases where further control is needed. For this reason, and to support the full spectrum of integration designs, a series of utilities are exposed directly for interfacing with the platform's webhook channel.

const { webhookUtil } = require('@oracle/bots-node-sdk/util');
// ...
webhookUtil.messageToBotWithProperties(url, secret, userId, messsage, extras, (err, result) => {

});

Message Formatting

The Oracle Bots platform supports several message formats, as defined by the MessageModel class.

The class provides several static methods used to create a stuctured object of a known Common Message Model message such as Text, Card, Attachment, Location, Postback or Raw type. It can be used within Custom Components, Webhook, or independently. In addition, MessageModel can be used in browsers. When used in browser, include the package joi-browser.

const { MessageModel } = require('@oracle/bots-node-sdk/lib');
// or
const OracleBot = require('@oracle/bots-node-sdk');
const { MessageModel } = OracleBot.Lib;

TIP: Use conversation.MessageModel() to access from within a Custom Component invoke method. Use webhook.MessageModel() to access from within a WebhookClient instance.

MethodPurposeUsage
textConversationMessageBasic textinbound, outbound
attachmentConversationMessageSupport media URLsinbound, outbound
cardConversationMessageCard presentationoutbound
postbackConversationMessageSubmit postback payloadsinbound
locationConversationMessageReceive location payloadinbound
rawConversationMessageFreeform payloadinbound, outbound

MessageModel Utilities

Additionally, a set of utilities for MessageModel are provided. Util.MessageModel functions help deriving string or speech representation of a Conversation Message Model payload. This is used primarily to output text or speech to voice or text-based channels like Alexa and SMS.

const { messageModelUtil } = require('@oracle/bots-node-sdk/util');
// ...
messageModelUtil.convertRespToText(message);

Unit Testing

The SDK also includes unit testing facilities, which can be utilized within your preferred test runner. Details may be found here.

Using TypeScript

This package includes types, and can therefore be used directly with TypeScript.

import { Lib } from '@oracle/bots-node-sdk';

class MyCustomComponent implements Lib.IComponent {
  public metadata(): Lib.IComponentMetadata {
    return { name: 'my.custom.component' }
  }
  public invoke(conversation: Lib.Conversation, done: () => void): void {
    // ...
  }
}

Contributing

@oracle/bots-node-sdk is an open source project. See CONTRIBUTING for details.

License

Copyright © 2018, Oracle and/or its affiliates. All rights reserved.

The Universal Permissive License (UPL), Version 1.0

Keywords

FAQs

Package last updated on 15 Apr 2020

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc