ChatBots

Ask tech team
From QuickBlox Developers (API docs, code samples, SDK)
Jump to: navigation, search

Contents

Overview

Use chat bots to enable users to conversationally interact with your service or your product.

Bots are third-party applications that run inside QuickBlox platform. Bots have almost same qualities as human: they have profile photos, names, they can send messages and upload files, and they can be added to and removed from private group chats.

Chat bots are controlled programmatically via QuickBlox Javascript/Node.js SDK

How To Build Chat Bots

Get a QuickBlox account and create your first application

In order to start develop you first Chat Bot you have to register new QuickBlox account and create your first application. Go to https://quickblox.com/signup and get a QuickBlox account, then go to https://admin.quickblox.com/apps/new and create your first application. Then save somewhere application's credentials (Application ID, Authorization key, Authorization secret), we will use them later.

Create bot user

Go to Users module in QuickBlox dashboard (e.g. <your_app_id>/service/users https://admin.quickblox.com/apps/<your_app_id>/service/users) and create new user for you chat bot. Then save somewhere this user's ID and password. We just need these 2 values, will use them later.

Create Node.js carcass application

Open terminal and type the following commands:

mkdir my_awesome_bot
cd my_awesome_bot
npm init

This will ask you a bunch of questions, and then write a package.json file for you. More information on npm init.

The main thing is that we have now a package.json file and can start develop our first chat bot.

Connect QuickBlox Javascript/Node.js SDK

In terminal type the following command:

npm install quickblox --save

Create index.js file

In terminal type the following command:

touch index.js

It will create the main entry point for your bot. Open this file and let's write some logic.

Making heart beat of your bot

Open index.js file and write the following code:

'use strict';
 
const QB = require('quickblox');
 
const CONFIG = {
    "appId": "...",
    "authKey": "...",
    "authSecret": "...",
    "botUser": {
        "id": "...",
        "password": "..."
    }
};
 
// Initialise QuickBlox
QB.init(CONFIG.appId, CONFIG.authKey, CONFIG.authSecret);
 
// Connect to Real-Time Chat
QB.chat.connect({
    userId: CONFIG.botUser.id,
    password: CONFIG.botUser.password
  }, (chatConnectError) => {
    if (chatConnectError) {
        console.log('[QB] chat.connect is failed', JSON.stringify(chatConnectError));
        process.exit(1);
    }
 
    console.log('[QB] Bot is up and running');
 
    // Add chat messages listener
    QB.chat.onMessageListener = onMessageListener;
});
 
function onMessageListener(userId, msg) {
 
  // process 1-1 messages
  if (msg.type == 'chat') {
    if(msg.body){
        let answerMessage = {
            type: 'chat',
            body: msg.body, // echo back original message
            extension: {
                save_to_history: 1
            }
        };
 
        QB.chat.send(userId, answerMessage);
    }
  }
 
}
 
process.on('exit', function () {
    console.log('Kill bot');
    QB.chat.disconnect();
});

This is a simple bot that simply reply back with origin message. Nothing especial. But you got the idea.

For CONFIG variable, put the values from previous steps (from [1] and [2]).

Run our bot

In terminal type the following command:

node index.js

Now you can write something to your bot and will receive a reply.

Source code

https://github.com/QuickBlox/quickblox-javascript-sdk/tree/gh-pages/samples/chat_bots/simple_bot

Improve bot's intelligence

Usually, it's not enough just to build simple bot which echoes your messages. It's better to add some intelligence for you bot.

For this purpose, we need to connect some bot's intelligence platform/library to your bot. There is a cool product called https://www.rivescript.com. RiveScript is a scripting language for chatterbots, making it easy to write trigger/response pairs for building up a bot's intelligence.

Install RiveScript

Inside your bot directory run the following command to install RiveScript:

npm install rivescript --save

Prepare '.rive' file

RiveScript is a text-based scripting language meant to aid in the development of interactive chatbots. To write your own RiveScript code, you will only need a simple text editing program. A RiveScript document is a text file containing RiveScript code. These files will have a .rive extension. An example file name would be replies.rive.

Create a txt file in your bot's directory and name it replies.rive. Then go to https://www.rivescript.com/try, choose rs-standard.rive template and copy all content into your file.

Read more information on RiveScript code.

Connect RiveScript to your bot

Open index.js file and add the following code:

const RiveScript = require('rivescript');
 
...
 
// Init RiveScript logic
var riveScriptGenerator = new RiveScript();
 
function loadingDone(batch_num) {
    console.log("[RiveScript] Batch #${batch_num} has finished loading!");
    riveScriptGenerator.sortReplies();
}
 
function loadingError(batch_num, error) {
    console.log("[RiveScript] Load the batch #${batch_num} is failed", JSON.stringify(error));
}
 
// load our replies file
riveScriptGenerator.loadFile('replies.rive', loadingDone, loadingError);
 
...
 
let answerMessage = {
  type: 'chat',
  body: riveScriptGenerator.reply(userId, msg.body),
  extension: {
    save_to_history: 1
  }
};
...

Here we initialise RiveScript, then load all replies flows from replies.rive file and then build message reply based on RiveScript replies flows.

Demo

In terminal type the following command to run our bot:

node index.js

Now you can write something to your bot and will receive a reply.

Chat bot intelligence.png

Source code

https://github.com/QuickBlox/quickblox-javascript-sdk/tree/gh-pages/samples/chat_bots/rivescript

Where to go next

Explore QuickBlox Javascript/Node.js SDK to add more capabilities for your bot.