amio-chatbot-builder-js
Amio Chatbot Builder is a simple bot framework that simulates a state machine chatbot. You can easily add NLP and analytics features though. We, are using it on our own chatbot projects. Just like Amio, the framework aims to be platform agnostic. Check out all the supported platforms.
Let us know how to improve this library. We'll be more than happy if you report any issues or even create pull requests. ;-)
Installation
npm install amio-chatbot-builder --save
You will want to send and receive messages. For this purpose install amio-sdk-js.
npm install amio-sdk-js --save
Usage
Prerequisities
- Setup NodeJs - we prefer to use it with Express (use generator)
- Setup Amio webhooks
Basic setup
You can copy/paste this setup.
1. Create state
// file echo.state.jsconst State = Stateconst AmioApi = AmioApi const amioApi = accessToken: 'get access token from https://app.amio.io/administration/settings/api' { super this } async { const data = webhook const payload = datacontent ? datacontentpayload : datapostbackpayload await this } async { await amioApimessages } moduleexports = EchoState
2. Setup chatbot
// file my-chatbot.jsconst Chatbot = Chatbotconst EchoState = { super const echoState = this this } moduleexports = // make it singleton (not obligatory ;)
3. React to webhooks
After setting up Amio webhooks you can pass the webhook events to your chatbot.
// file router.jsconst express = const router = expressconst chatbot = const WebhookRouter = WebhookRouter const amioWebhookRouter = secretToken: 'get secret at https://app.amio.io/administration/channels/{{CHANNEL_ID}}/webhook' amioWebhookRouteramioWebhookRouter// you can react to other webhook events too router moduleexports = router
Chatbot
Chatbot represents a state machine. The most important methods you'll be using are chatbot.runNextState()
and chatbot.runPostback()
.
You can set it up using either inheritance or composition:
//Inheritance { super this // ... } // Compositionconst chatbot = chatbot// ...
Method | Params | Description |
---|---|---|
addInterceptor | interceptor | Registers a new interceptor at the end of the interceptor chain. |
addPostback | key state |
Registers a state that will be invoked after postback with a specific key is received |
runNextState | webhook | How it works: 1. Iterate all interceptors` before() .2. Keep executing states while state.execute() returns a state.3. Iterate all interceptors` after() .Warning - If an interceptor returns false, go directly to step 3. |
runPostback | webhook | Picks a correct state that was registered using chatbot.addPostback() . Then it executes chatbot.runNextState() |
setErrorPostbackState | state | State that is executed if no postback is matching the key registered in chatbot.addPostback(key, state) . |
setInitialState | state | If no postback starts the chatbot, the initial state will be executed as the very first state. |
setInterceptors | array(interceptor) interceptors | Sets the whole interceptor chain. The first interceptor is to be run first. |
setPostbackKeyExtractor | function | Normalizes postback key so that it can be used to find a correct. It's useful if you're passing some data in postback like 'POSTBACK:ARBITRARY_DATA' . In this case, you would register a state as chatbot.addpostback('POSTBACK', state) It accepts webhook.data.postback.payload as the function argument. |
State
State holds all the steps a chatbot shall do upon receiving a webhook. It's a reusable piece of logic. Generally, one state will consist of several 'message sends'.
Method | Params | Description |
---|---|---|
addNextState | nextState condition |
Adds a static transition to a next state. If condition(webhook) return true. The state will be selected for execution. |
execute | channelId contactId webhook |
Executes state`s logic. If you return a new state it will run immediately - it is so called dynamic transition. |
State transitions - static vs. dynamic
Static transitions between states are known from the app startup (or from the compilation). They are defined as chatbot.addPostback(key, state)
or as state.addNextState(state, condition)
.
{ if % 2 === 0 return true // use this state after next webhook event is received return false}
Dynamic transitions between states are decided either in state.execute()
or anywhere you call chatbotCache.setNextState()
.
You can run a state immediately without having to wait for another webhook if you return it from state.execute()
.
{ ifdatacontent console return console }
Cache
Chatbot uses a cache that is referenced in code like chatbotCache
. It keeps temporary data about a contact.
The contact is always identified by contactId
. You can use it to store and retrieve your data using chatbot.set()
and chatbot.get()
.
By default, the cache stores:
- last 100 clients (LRU)
- next state -
chatbot.setNextState()
- last 20 states
chatbot.getPastStates()
Method | Params | Description |
---|---|---|
get | contactId key defaultValue = null |
Returns a value for a key of contact with contactId . |
getLastState | contactId | Returns last visited state. |
getNextState | contactId | Returns the next state that will be executed by chatbot. |
getPastStates | contactId | Returns last 20 states executed for contact contactId . |
reset | Clears the cache. | |
set | contactId key value |
Add value to a key of contact with contactId . |
Interceptor
Interceptors are used to influence received webhook events either before or after a state is executed.
An interceptor is a class that extends require('amio-chatbot-builder').Interceptor
.
Register interceptors using chatbot.setInterceptors([interceptor1, ...])
How the interceptors work:
- Your server receives a webhook event.
- You pass the event over to chatbot via
chatbot.runNextState(webhook)
- Chatbot first iterate all interceptors`
before()
. The first interceptor that returnsfalse
breaks the interceptor chain and state execution is skipped. Go directly to step 5. - Chatbot keeps executing states while
state.execute()
returns a new state. - Chatbot iterates all interceptors`
after()
.
Method | Params | Description |
---|---|---|
before | channelId contactId webhook |
before() is executed before the state itself. Return false if you wish to prevent the state execution. No other interceptors will be run either.You can also change state using chatbotCache.setNextState(newState) . |
after | channelId contactId webhook |
after() is executed after the state execution. It good for a clean up. All registered interceptors are always executed. |
Logging
If you want to enable logs, add namespace amio-chatbot-builder-js:*
to your DEBUG
environment variable.
process.env.DEBUG = 'your-project-namespace:*,amio-chatbot-builder-js:*'
For more details check debug lib and the logz.io wrapper.
How to get contactId/channelId
contactId
/channelId
can be obtained from every webhook. We are trying to resolve them
for you and pass to all methods where they may be needed frequently like state.execute(channelId, contactId, webhook)
.
const contactId = webhookdatacontactidconst channelId = webhookdatachannelid