1.9.3 • Published 8 months ago

flowai-js v1.9.3

Weekly downloads
279
License
-
Repository
github
Last release
8 months ago

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

Functions

EventAttachment

Trigger events

new EventAttachment(name, label)

ParamTypeDescription
namestringName of the event to trigger
labelstringOptional human readable label for the triggered event

Constructor

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

Properties

NameTypeDescription
messagestringHuman friendly message
typestringKind of error
innerExceptionExceptionInner exception
isFinalbooleanPrevent further execution

Exception

new Exception(message, type, innerException, isFinal)

ParamTypeDefaultDescription
messagestringmessage - Human friendly message
typestringKind of error
innerExceptionExceptionOptional inner exception
isFinalbooleanfalseIndicates if this exception prevents further execution

Constructor

FileAttachment

Send a file as attachment

new FileAttachment(data)

ParamTypeDescription
dataFile | ReadStreamFile or Blob in the browser, ReadStream in Nodejs

Constructor

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)

FlowAttachment

Trigger flows

new FlowAttachment(flowImmutableId)

ParamTypeDescription
flowImmutableIdstringImmutable flowId of the flow to trigger

Constructor

Example

const message = new Message({
  attachment: new FlowAttachment(flowImmutableId)
})

LiveClient

Live streaming websocket client extends EventEmitter

new LiveClient(opts)

ParamTypeDescription
optsobject | stringConfiguration options or shorthand for just clientId
opts.clientIdstringMandatory Client token
opts.storagestringOptional, 'session' for using sessionStorage, 'local' for localStorage or memory for a simple memory store
opts.endpointstringOptional, only for testing purposes
opts.originstringWhen running on Nodejs you MUST set the origin
opts.silentbooleanOptional, console.errors will not be shown
opts.ottstringOptional, console.errors will not be shown

Constructor

Example

// Node.js
const client = new LiveClient({
  clientId: 'MY CLIENT ID',
  origin: 'https://my.website'
})

// Web
const client = new LiveClient({
  clientId: 'MY CLIENT ID',
  storage: 'session'
})

// Lambda function
const client = new LiveClient({
  clientId: 'MY CLIENT ID',
  storage: 'memory'
})

liveClient.sessionId

ParamTypeDescription
valuestringChange the session ID

Session Id of the connection

liveClient.threadId

Default Thread Id to be used for any messages being send

Returns: string - Null if no connection is active

liveClient.threadId

ParamTypeDescription
valuestringChange the thread ID

Session Id of the connection

liveClient.secret

Secret

liveClient.secret

ParamTypeDescription
valuestringChange the Secret

Secret

liveClient.isConnected

Check if the connection is active

Returns: boolean - True if the connection is active
Example

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

liveClient.sessionId()

Session Id of the connection

Returns: string - Null if no connection is active

liveClient.start(threadId, sessionId)

ParamTypeDescription
threadIdstringOptional. When assigned, this is the default threadId for all messages that are send
sessionIdstringOptional. Must be unique for every connection

Start the client

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

Example

// Close the connection
client.stop()

liveClient.destroy()

Close the connection and completely reset the client

Example

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

liveClient.send(message)

ParamTypeDescription
messageobjectMessage you want to send

This method triggers a LiveClient.MESSAGE_SEND event

Returns: object - Message that was send
Example

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

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

client.send(message)

liveClient.merger(mergerKey, threadId, sessionId)

ParamTypeDescription
mergerKeystringUnique token representing merge Request
threadIdstringOptional. The threadId to merge
sessionIdstringOptional. The sessionId to assign to the thread

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.

liveClient.history(threadId)

ParamTypeDescription
threadIdstringOptional. Specify the threadId to retreive historic messages

Request 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)

ParamTypeDescription
threadIdstringOptional. Specify the thread that is noticed
instantlybooleanOptional. Instantly send notice. Default is false

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

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)

ParamTypeDescription
threadIdstringOptional. Specify the thread to check unnoticed messags for

Did we miss any messages?

liveClient.log(text)

ParamType
textstring

LiveClient.ERROR

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

LiveClient.CONNECTED

Event that triggers when client is connected with platform

LiveClient.RECONNECTING

Event that triggers when client tries to reconnect

LiveClient.DISCONNECTED

Event that triggers when the client gets disconnected

LiveClient.REPLY_RECEIVED

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

LiveClient.AGENT_TYPING_RECEIVED

Event that triggers when start busy typing received from the platform

LiveClient.MESSAGE_SEND

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

LiveClient.MESSAGE_DELIVERED

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

LiveClient.REQUESTING_HISTORY

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

LiveClient.NO_HISTORY

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

LiveClient.RECEIVED_HISTORY

Event that triggers when historic messages are received

LiveClient.CHECKED_UNNOTICED_MESSAGES

Event that triggers when there are unnoticed messages

LiveClient.INTERRUPTION_OCCURRED

Event that triggers when there are unnoticed messages

Message

Properties

NameTypeDescription
speechstringText representing the Message
originatorOriginatorOriginator
metaMetadataMeta data
attachmentAttachmentOptional attachment

Message you send to Flow.ai

new Message(opts)

ParamTypeDescription
optsObject
opts.traceIdnumberOptional unique integer you can match messages with
opts.threadIdstringOptional unique id specific to this chat
opts.speechstringText representing the Message
opts.originatorOriginatorOriginator
opts.metadataMetadataMeta data
opts.attachmentAttachmentAttachment (optional)

Constructor

Message.build(opts)

ParamType
optsobject
opts.threadIdstring
opts.traceIdstring
opts.speechstring
opts.originatorobject
opts.metadataobject
opts.attachmentobject

Factory method

Metadata

Properties

NameTypeDescription
languagestringLanguage the message is ib
timezonenumberUTC time offset in hours
paramsObjectParameters to send with the message
domainObjectBrowser or server environment variables like origin

Additional Message data

  • Metadata

    * [new Metadata(language, timezone, params)](#new_Metadata_new)
    
    * _instance_
        * ~~[.addContext()](#Metadata+addContext)

    ~~ static .build(metadata)

new Metadata(language, timezone, params)

ParamTypeDescription
languagestringSpecify the language of the message
timezonenumberSpecify the timezone of the message
paramsObjectAdditional data to be send

Constructor

metadata.addContext()

Deprecated

Metadata.build(metadata)

ParamType
metadataObject

Create a Metadata object from raw data

OpeningAttachment

Trigger opening events

new OpeningAttachment(name, label)

ParamTypeDescription
namestringName of the event to trigger
labelstringOptional human readable label for the triggered event

Constructor

Example

// Opening event without any label
const message = new Message({
  attachment: new OpeningAttachment('BUY')
})

Example

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

OpeningFlowAttachment

Trigger flow as opening events

new OpeningFlowAttachment(flowImmutableId, label)

ParamTypeDescription
flowImmutableIdstringFlowImmutableId of the flow to trigger
labelstringOptional human readable label for the triggered event

Constructor

Example

// Opening event without any label
const message = new Message({
  attachment: new OpeningFlowAttachment(flowImmutableId)
})

Originator

Properties

NameTypeDescription
namestringName of a person or system originating the Message, default is Anonymous
rolestringThe role of the person. You cannot set this, default is external
profileObjectContains profile info
profile.fullNamestringFirst and surname combined
profile.firstNamestringFirst name of the person
profile.lastNamestringLast name of the person
profile.emailstringE-mail address
profile.descriptionstringDescription of this user
profile.picturestringProfile picture (url)
profile.localestringISO code describing language and country (en-US)
profile.timezonenumberHours from GMT
profile.locationstringLocation of the user
profile.genderstringM for male, F for female or U for unknown / other
metadataobjectOptional object with custom metadata

Originator of a Message

new Originator(opts)

ParamTypeDescription
optsObject
opts.namestringName of a person or system originating the Message, default is Anonymous
opts.rolestringThe role of the person. You cannot set this, default is external
opts.profileObjectContains profile info
opts.profile.fullNamestringFirst and surname combined
opts.profile.firstNamestringFirst name of the person
opts.profile.lastNamestringLast name of the person
opts.profile.emailstringE-mail address
opts.profile.descriptionstringDescription of this user
opts.profile.picturestringProfile picture (url)
opts.profile.localestringISO code describing language and country (en-US)
opts.profile.timezonenumberHours from GMT
opts.profile.locationstringLocation of the user
opts.profile.genderstringM for male, F for female or U for unknown / other
opts.metadataobjectOptional object with custom metadata

Reply

Properties

NameTypeDescription
threadIdstringUnique id specific to this chat
originatorOriginatorOriginator
messagesArray.<ReplyMessage>List of messages
messages[].fallbackstringTextual representation of any responses
messages[].replyTostringOptional replying to query
messages[].contextsarrayOptional List of context names
messages[].paramsarrayOptional key value pair of parameters
messages[].intentsarrayOptional list of intent names determined
messages[].responsesArray.<Response>List of response templates
messages[].responses[].typestringTemplate type
messages[].responses[].payloadObjectTemplate payload
messages[].responses[].delayNumberNumber of seconds the response is delayed

Reply you receive from Flow.ai

new Reply()

Constructor

StepAttachment

Trigger steps

new StepAttachment(stepId)

ParamTypeDescription
stepIdstringImmutable stepId of the step to trigger

Constructor

Example

const message = new Message({
  attachment: new StepAttachment(stepId)
})

_setCookie(name, value)

ParamType
namestring
valuestring

_getCookie(name)

ParamType
namestring
1.9.3

8 months ago

1.9.2-beta

11 months ago

1.9.2-beta-4

11 months ago

1.9.2-beta-1

11 months ago

1.9.2-beta-3

11 months ago

1.9.2-beta-2

11 months ago

1.9.2-beta-5-temp

11 months ago

1.9.1-pre

11 months ago

1.9.0

1 year ago

1.8.9

2 years ago

1.8.8

2 years ago

1.8.7

2 years ago

1.8.6

3 years ago

1.8.5

4 years ago

1.8.4

4 years ago

1.8.3

4 years ago

1.8.2

4 years ago

1.8.1

4 years ago

1.8.0

4 years ago

1.6.13

4 years ago

1.7.0

4 years ago

1.6.12

4 years ago

1.6.11

4 years ago

1.6.10

4 years ago

1.6.9

4 years ago

1.6.8

4 years ago

1.6.7

4 years ago

1.6.6

4 years ago

1.6.5

4 years ago

1.6.4

4 years ago

1.6.3

4 years ago

1.6.2

5 years ago

1.6.1

5 years ago

1.6.0

6 years ago

1.5.12

6 years ago

1.5.11

6 years ago

1.5.10

6 years ago

1.5.9

6 years ago

1.5.8

6 years ago

1.5.7

6 years ago

1.5.6

6 years ago

1.5.5

6 years ago

1.5.4

6 years ago

1.5.3

6 years ago

1.5.2

6 years ago

1.5.1

6 years ago

1.5.0

6 years ago

1.4.10

6 years ago

1.4.9

6 years ago

1.4.8

6 years ago

1.4.7

6 years ago

1.4.6

6 years ago

1.4.5

6 years ago

1.4.4

6 years ago

1.4.3

6 years ago

1.4.2

6 years ago

1.4.1

6 years ago

1.4.0

6 years ago

1.3.9

6 years ago

1.3.8

7 years ago

1.3.7

7 years ago

1.3.6

7 years ago

1.3.5

7 years ago

1.3.4

7 years ago

1.3.3

7 years ago

1.3.2

7 years ago

1.3.1

7 years ago

1.3.0

7 years ago

1.2.8

7 years ago

1.2.7

7 years ago

1.2.6

7 years ago

1.2.5

7 years ago

1.2.4

7 years ago

1.2.3

7 years ago

1.2.2

7 years ago

1.2.1

7 years ago

1.2.0

7 years ago

1.1.6

7 years ago

1.1.5

7 years ago

1.1.4

7 years ago

1.1.3

7 years ago

1.1.2

7 years ago

1.1.1

7 years ago

1.1.0

7 years ago

1.0.7

7 years ago

1.0.5

7 years ago

1.0.4

7 years ago

1.0.3

7 years ago

1.0.2

7 years ago

1.0.1

7 years ago

1.0.0

7 years ago

0.0.8

7 years ago

0.0.7

7 years ago

0.0.6

7 years ago

0.0.5

7 years ago

0.0.4

7 years ago

0.0.3

7 years ago

0.0.2

7 years ago

0.0.1

7 years ago