Flow.ai JavaScript SDK
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
dist FLOW-338 Updated packages and version Sep 14, 2018
example/node Added file uploading to the API Apr 24, 2018
lib
media
src
test
.babelrc
.eslintignore
.eslintrc
.gitignore
.jsdoc
.npmignore
README.md
package-lock.json
package.json
webpack.config.js FLOW-253 Upgraded build stuff Aug 3, 2018

README.md

The flow.ai Javascript SDK

Access the flow.ai platform from your Node.js or javascript app. This library lets you build on the flow.ai Webclient API.

What can you do?

  • A simple way to connect with flow.ai
  • Auto reconnect and event binding
  • Send and receive messages
  • Trigger actions and interact with AI bots

Usage

Installation

Run npm install --save flowai-js

Simple Node.js example

const {
  LiveClient,
  Message,
  Originator
} = require("flowai-js")

// Create a new live client
const client = new LiveClient({
  clientId: 'YOUR CLIENT ID HERE',
  origin: 'https://my.site'
})

// Fired whenever the client connects
client.on(LiveClient.CONNECTED, () => {

  console.log('--> Connected')

  // Create the originator of the message
  const originator = new Originator({
    name: "Boss"
  })

  // Create a Message
  const message = new Message({
    // Thread Id limits the message just to John
    threadId: 'john',
    // The text to send
    speech: "Behold, I'm pure awesomeness!",
    // Person or system sending the message
    originator
  })

  // Send
  client.send(message)
})

// Start the connection
client.start()

Advanced Node.js example

In this example you'll notice all events that are available

const {
  LiveClient,
  Message,
  Originator
} = require("flowai-js")

// Create a new live client
const client = new LiveClient({
  // Unique clientId copy & paste from Flow.ai dashboard
  clientId: 'YOUR CLIENT ID HERE',

  // When limiting to whitelisted domains, specify this
  origin: 'https://my.site'
})

client.on(LiveClient.CONNECTED, () => {
  const originator = new Originator({
    name: "Boss"
  })

  const message = new Message({
    // Thread Id limits the message just to John
    threadId: 'john',
    // Use the traceId to identify message
    // being marked as delivered
    traceId: 1,
    speech: "Behold, I'm pure awesomeness!",
    originator
  })

  client.send(message)
})

client.on(LiveClient.MESSAGE_DELIVERED, message => {
  // The message we have send has been delivered
  // check the traceId to see what message has been
  // delivered since it's an async method
})

client.on(LiveClient.REPLY_RECEIVED, message => {
  // Called when a bot or human operator
  // sends a message or reply
  if(message.threadId === 'john') {
    // Incoming message for John
  } else {
    // Incoming message for another user
  }
})

client.on(LiveClient.ERROR, err => {
  // This handler will be fired whenever an error
  // occurs during the connection
  console.error('Something bad happened', err)
})

client.on(LiveClient.DISCONNECTED, () => {
  // The client has been disconnected
})

client.on(LiveClient.MESSAGE_SEND, message => {
  // Called whenever the client sends a message
})

client.on(LiveClient.RECONNECTING, () => {
  // Called when the client tries to reconnect
})

client.start()

Simple browser example

Using the library within the browser is pretty much the same as the Node.js examples.

There is one notable difference, all classes live inside a Flowai object.

Include the script

<script src="flowai-js.min.js"></script>

Usage

var client = new Flowai.LiveClient('YOUR CLIENT ID HERE');
client.on(LiveClient.CONNECTED, function(){
  var originator = new Flowai.Originator({ fullName: "John Doo" });

  var message = new Flowai.Message({
    threadId: 'john',
    traceId: 1,
    speech: "Behold, I'm pure awesomeness!",
    originator
  });

  client.send(message);
})

client.start();

Notes on using with webpack

The library can be easily used with webpack. You'll probably receive an error though involving fs.

Add the following to your webpack config file:

node: {
  fs: 'empty'
},

Identifying messages

The SDK is pretty flexible with regard to how messages are delivered and grouped. To do this we use two unique keys: sessionId and threadId.

ThreadId

threadId

A threadId is a unique key representing a channel, room, or user. If you have a single connection running for multiple clients, all using the same threadId, they will all receive the same messages.

Unique sessionIds

sessionId

The sessionId is used to identify connections from different devices like browsers or Node.js servers. Each connection is partly identified on our end using this key.

Unique sessions and threadids

Full API Reference

Classes

EventAttachment

Trigger events

Exception

Exception

FileAttachment

Send a file as attachment

LiveClient

Live streaming websocket client extends EventEmitter

Message
Metadata

Additional Message data

Originator

Originator of a Message

Reply

Reply you receive from Flow.ai

Members

build

Message you send to Flow.ai

EventAttachment

Trigger events

Kind: global class

new EventAttachment(name, [label])

Constructor

Param Type Description
name string Name of the event to trigger
[label] string Optional human readable label for the triggered event

Example

// Event without any label
const message = new Message({
  attachment: new EventAttachment('BUY')
})

Example

// Event with label to display user
const message = new Message({
  attachment: new EventAttachment('BUY', 'Buy dress')
})

Exception

Exception

Kind: global class
Properties

Name Type Description
message string Human friendly message
type string Kind of error
innerException Exception Inner exception
isFinal boolean Prevent further execution

new Exception(message, type, innerException, isFinal)

Constructor

Param Type Default Description
message string message - Human friendly message
type string Kind of error
innerException Exception Optional inner exception
isFinal boolean false Indicates if this exception prevents further execution

FileAttachment

Send a file as attachment

Kind: global class

new FileAttachment(data)

Constructor

Param Type Description
data File | ReadStream File or Blob in the browser, ReadStream in Nodejs

Example

// Web example

var originator = new Originator({
  name: 'Jane'
})

var file = fileInputElement.files[0]

const message = new Message({
  attachment: new FileAttachment(file)
})

client.send(message)

Example

// Nodejs example
import { createReadStream } from 'fs'

const originator = new Originator({
  name: 'Jane'
})

// Load ReadStream from file on disk
const data = fs.createReadStream('/foo/bar.jpg')

const message = new Message({
  attachment: new FileAttachment(data)
})

client.send(message)

LiveClient

Live streaming websocket client extends EventEmitter

Kind: global class

new LiveClient(opts)

Constructor

Param Type Description
opts object | string Configuration options or shorthand for just clientId
opts.clientId string Mandatory Client token
opts.storage string Optional, 'session' or 'local' for using sessionStorage or localStorage
opts.endpoint string Optional, only for testing purposes
opts.origin string When running on Nodejs you MUST set the origin

liveClient.sessionId

Session Id of the connection

Kind: instance property of LiveClient

Param Type Description
value string Change the session ID

liveClient.threadId ⇒ string

Default Thread Id to be used for any messages being send

Kind: instance property of LiveClient
Returns: string - Null if no connection is active

liveClient.threadId

Session Id of the connection

Kind: instance property of LiveClient

Param Type Description
value string Change the thread ID

liveClient.isConnected ⇒ boolean

Check if the connection is active

Kind: instance property of LiveClient
Returns: boolean - True if the connection is active
Example

if(client.isConnected) {
  // Do something awesome
}

liveClient.sessionId() ⇒ string

Session Id of the connection

Kind: instance method of LiveClient
Returns: string - Null if no connection is active

liveClient.start(threadId, sessionId)

Start the client

Kind: instance method of LiveClient

Param Type Description
threadId string Optional. When assigned, this is the default threadId for all messages that are send
sessionId string Optional. Must be unique for every connection

Example

// Start, will generate thread and sessionId
client.start()

Example

// Start with your own custom threadId
client.start('UNIQUE THREADID FOR USER')

liveClient.stop()

Use this method to temp disconnect a client

Kind: instance method of LiveClient
Example

// Close the connection
client.stop()

liveClient.destroy()

Close the connection and completely reset the client

Kind: instance method of LiveClient
Example

// Close the connection and reset the client
client.destroy()

liveClient.send(message) ⇒ object

This method triggers a LiveClient.MESSAGE_SEND event

Kind: instance method of LiveClient
Returns: object - Message that was send

Param Type Description
message object Message you want to send

Example

const originator = new Originator({
  name: "Jane"
})

const message = new Message({
 speech: "Hi!",
 originator
})

client.send(message)

liveClient.merger(mergerKey, threadId, sessionId)

Merge two threads from different channels. This methods is not yet publicy supported since we don't have a way yet to provide a mergerKey.

Kind: instance method of LiveClient

Param Type Description
mergerKey string Unique token representing merge Request
threadId string Optional. The threadId to merge
sessionId string Optional. The sessionId to assign to the thread

liveClient.history(threadId)

Request historic messages

Kind: instance method of LiveClient

Param Type Description
threadId string Optional. Specify the threadId to retreive historic messages

Example

// Load any messages if there is a threadId
// usefull when using with JS in the browser
client.history()

// Load messages using a custom threadId
client.history('MY CUSTOM THREAD ID')

liveClient.noticed(threadId, instantly)

Call to mark a thread as noticed. The library automatically throttles the number of calls

Kind: instance method of LiveClient

Param Type Description
threadId string Optional. Specify the thread that is noticed
instantly boolean Optional. Instantly send notice. Default is false

Example

// Call that the client has seen all messages for the auto clientId
client.noticed()

// Mark messages based on a custom threadId
client.noticed('MY CUSTOM THREAD ID')

liveClient.checkUnnoticed(threadId)

Did we miss any messages?

Kind: instance method of LiveClient

Param Type Description
threadId string Optional. Specify the thread to check unnoticed messags for

LiveClient.ERROR : string

Event that triggers when an error is received from the flow.ai platform

Kind: static constant of LiveClient

LiveClient.CONNECTED : string

Event that triggers when client is connected with platform

Kind: static constant of LiveClient

LiveClient.RECONNECTING : string

Event that triggers when client tries to reconnect

Kind: static constant of LiveClient

LiveClient.DISCONNECTED : string

Event that triggers when the client gets disconnected

Kind: static constant of LiveClient

LiveClient.REPLY_RECEIVED : string

Event that triggers when a new message is received from the platform

Kind: static constant of LiveClient

LiveClient.MESSAGE_SEND : string

Event that triggers when the client is sending a message to the platform

Kind: static constant of LiveClient

LiveClient.MESSAGE_DELIVERED : string

Event that triggers when the send message has been received by the platform

Kind: static constant of LiveClient

LiveClient.REQUESTING_HISTORY : string

Event that triggers when a request is made to load historic messages

Kind: static constant of LiveClient

LiveClient.NO_HISTORY : string

Event that triggers when a request is made to load historic messages

Kind: static constant of LiveClient

LiveClient.RECEIVED_HISTORY : string

Event that triggers when historic messages are received

Kind: static constant of LiveClient

LiveClient.CHECKED_UNNOTICED_MESSAGES : string

Event that triggers when there are unnoticed messages

Kind: static constant of LiveClient

Message

Kind: global class

new Message(opts)

Constructor

Param Type Description
opts Object
opts.traceId number Optional unique integer you can match messages with
opts.threadId string Optional unique id specific to this chat
opts.speech string Text representing the Message
opts.originator Originator Originator
opts.metadata Metadata Meta data
opts.attachment Attachment Attachment (optional)

Message.build(opts) ⇒ Message

Factory method

Kind: static method of Message

Param Type
opts object
opts.threadId string
opts.traceId string
opts.speech string
opts.originator object
opts.metadata object
opts.attachment object

Metadata

Additional Message data

Kind: global class
Properties

Name Type Description
language string Language the message is ib
timezone number UTC time offset in hours
params Object Parameters to send with the message
domain Object Browser or server environment variables like origin

new Metadata(language, timezone, params)

Constructor

Param Type Description
language string Specify the language of the message
timezone number Specify the timezone of the message
params Object Additional data to be send

metadata.addContext()

Deprecated

Kind: instance method of Metadata

Metadata.build(metadata) ⇒ Metadata

Create a Metadata object from raw data

Kind: static method of Metadata

Param Type
metadata Object

Originator

Originator of a Message

Kind: global class
Properties

Name Type Description
name string Name of a person or system originating the Message, default is Anonymous
role string The role of the person. You cannot set this, default is external
profile Object Contains profile info
profile.fullName string First and surname combined
profile.firstName string First name of the person
profile.lastName string Last name of the person
profile.email string E-mail address
profile.description string Description of this user
profile.picture string Profile picture (url)
profile.locale string ISO code describing language and country (en-US)
profile.timezone number Hours from GMT
profile.location string Location of the user
profile.gender string M for male, F for female or U for unknown / other
metadata object Optional object with custom metadata

new Originator(opts)

Param Type Description
opts Object
opts.name string Name of a person or system originating the Message, default is Anonymous
opts.role string The role of the person. You cannot set this, default is external
opts.profile Object Contains profile info
opts.profile.fullName string First and surname combined
opts.profile.firstName string First name of the person
opts.profile.lastName string Last name of the person
opts.profile.email string E-mail address
opts.profile.description string Description of this user
opts.profile.picture string Profile picture (url)
opts.profile.locale string ISO code describing language and country (en-US)
opts.profile.timezone number Hours from GMT
opts.profile.location string Location of the user
opts.profile.gender string M for male, F for female or U for unknown / other
opts.metadata object Optional object with custom metadata

Reply

Reply you receive from Flow.ai

Kind: global class
Properties

Name Type Description
threadId string Unique id specific to this chat
originator Originator Originator
messages Array.<ReplyMessage> List of messages
messages[].fallback string Textual representation of any responses
messages[].replyTo string Optional replying to query
messages[].contexts array Optional List of context names
messages[].params array Optional key value pair of parameters
messages[].intents array Optional list of intent names determined
messages[].responses Array.<Response> List of response templates
messages[].responses[].type string Template type
messages[].responses[].payload Object Template payload
messages[].responses[].delay Number Number of seconds the response is delayed

new Reply()

Constructor

build

Message you send to Flow.ai

Kind: global variable
Properties

Name Type Description
speech string Text representing the Message
originator Originator Originator
meta Metadata Meta data
attachment Attachment Optional attachment