DEV Community

riversun
riversun

Posted on • Updated on

How to quickly create Chat Bot UI for both smartphones and PCs

Overview

It is a brief guide for creating the chatbot UI in JavaScript.

  • Responsive: Auto detect Smartphone and PC browser and render a correct chat UI.
  • Minimally invasive:Do not jam existing content , and it works if you put only one script tag in html

guide

[here is a demo]

This demo is simple echo chat. But a few command available.

  • If you write "show buttons", you can see action buttons on chat UI.
  • Or you write "show image", you can see image in chat.

Example project is available on this repo.
https://github.com/riversun/chatux-example

Target

  • People who can write Java Script (even beginners)
  • People with node.js environment (npm or yarn can be used)
  • People interested in chatbots

What you can do

Create a chatbot UI that supports both PC browser and Smart Phone like the following demo

In the case of smartphone, the chat UI is displayed on the chat UI fitted to the screen.

In the case of PC browser, the chat UI is displayed on the floating window. I will explain in the main part what technology is used to achieve this.

Install and minimal code

using npm

install

npm install chatux --save
Enter fullscreen mode Exit fullscreen mode

code

import {ChatUx} from 'chatux';

const chatux = new ChatUx();

chatux.init({
    api: {
        endpoint: 'http://localhost:8080/chat',//chat server
        method: 'GET',//HTTP METHOD when requesting chat server
        dataType: 'json'//json or jsonp is available
    }
});

chatux.start();
Enter fullscreen mode Exit fullscreen mode

using with script tag

<script src="https://riversun.github.io/chatux/chatux.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

code

const chatux = new ChatUx();

chatux.init({
    api: {
        endpoint: 'http://localhost:8080/chat',//chat server
        method: 'GET',//HTTP METHOD when requesting chat server
        dataType: 'json'//json or jsonp is available
    }
});

chatux.start();


Enter fullscreen mode Exit fullscreen mode

How it works

The system of chatux is very simple.

Let's look at the execution sequence of chatux.

Suppose you have a chat server for chatux at http://localhost:8080/chat
Specify server endpoint like this.

chatux.init({
    api: {
        endpoint: 'http://localhost:8080/chat',
        method: 'GET',
        dataType: 'json'
    }
});

Enter fullscreen mode Exit fullscreen mode

The following is the sequence.

image

{
  "output": [
    {
      "type": "text",
      "value": "You say 'hello'"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode
  • 3. According to the response, chatux renders the result on the chat screen. image

So, if you create chat server that can do this kind of interaction, you can easily create chatbots etc.

Next, let's see how to render.

Chat server

Let's create a simple chat server.

  • initialize npm project and install express
npm init
npm install express
Enter fullscreen mode Exit fullscreen mode
  • Write a simple server that returns json.
const express = require('express');
const app = express();
const port = 8080;

// enabling CORS
app.use(function (req, res, next) {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept');
    next();
});
app.get('/chat', function (req, res) {
    const userInputText = req.query.text;

    const response = {
        output: []
    };

    const msg = response.output;
    msg.push({
        type: 'text',
        value: `You say ${userInputText}`
    });
    res.json(response);
});

app.listen(port, () => {
    console.log('chat server started on port:' + port);
});


Enter fullscreen mode Exit fullscreen mode
  • start server
npm start
Enter fullscreen mode Exit fullscreen mode
  • Access directory

http://localhost:8081/chat?text=hello

You will get JSON for chatux as follows.

{"output":[{"type":"text","value":"You say hello"}]}
Enter fullscreen mode Exit fullscreen mode
  • Access from ChatUX on browser
chatux.init({
    api: {
        endpoint: 'http://localhost:8080/chat',
        method: 'GET',
        dataType: 'json'
    }
});
chatux.start(true);//true:automatically open chat

Enter fullscreen mode Exit fullscreen mode

image


How to render a chat UI

Since chatux can render various variations of chat UI, I introduce them below.
I want to show raw JSON and code example for chat server respectively.

Show text

SERVER CODE

app.get('/chat', function (req, res) {
    const response = {output: []};
    const msg = response.output;
    msg.push({
        type: 'text',
        value: 'Hello world'
    });
    res.json(response);
});
Enter fullscreen mode Exit fullscreen mode

JSON

{
  "output": [
    {
      "type": "text",
      "value": "Hello world!"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

RESULT

image


Show image

SERVER CODE

app.get('/chat', function (req, res) {
    const response = {output: []};
    const msg = response.output;
    msg.push({
        type: 'image',
        value: 'https://avatars1.githubusercontent.com/u/11747460'
    });
    res.json(response);
});
Enter fullscreen mode Exit fullscreen mode

JSON

{
  "output": [
    {
      "type": "image",
      "value": "https://avatars1.githubusercontent.com/u/11747460"
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

RESULT

image


Show action buttons

SERVER CODE

app.get('/chat', function (req, res) {
    const response = {output: []};
    const msg = response.output;
    const opts = [];
    opts.push({label: 'label1', value: 'value1'});
    opts.push({label: 'label2', value: 'value2'});
    opts.push({label: 'label3', value: 'value3'});
    msg.push({type: "option", options: opts});
    res.json(response);
});
Enter fullscreen mode Exit fullscreen mode

JSON

{
  "output": [
    {
      "type": "option",
      "options": [
        {
          "label": "label1",
          "value": "value1"
        },
        {
          "label": "label2",
          "value": "value2"
        },
        {
          "label": "label3",
          "value": "value3"
        }
      ]
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

RESULT

image


Show html

SERVER CODE

app.get('/chat', function (req, res) {
    const response = {output: []};
    const msg = response.output;
    msg.push({
        type: 'html',
        value: 'Click <a href="https://github.com/riversun" target="_blank" >here</a> to open a page.',
        delayMs: 500
    });
    res.json(response);
});
Enter fullscreen mode Exit fullscreen mode

JSON

{
  "output": [
    {
      "type": "html",
      "value": "Click <a href=\"https://github.com/riversun\" target=\"_blank\" >here</a> to open a page.",
      "delayMs": 500
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

RESULT

image


Show youtube

SERVER CODE

app.get('/chat', function (req, res) {
    const response = {output: []};
    const msg = response.output;
    const videoId = 'TP4lxliMHXY'; //youtube video id
    msg.push({
        type: 'youtube',
        value: videoId,
        delayMs: 500 // wait(milliseconds)
    });
    res.json(response);
});
Enter fullscreen mode Exit fullscreen mode

JSON

{
  "output": [
    {
      "type": "youtube",
      "value": "TP4lxliMHXY",
      "delayMs": 500
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

RESULT

image


Show multiple elements

SERVER CODE

app.get('/chat', function (req, res) {
    const response = {output: []};
    const msg = response.output;
    msg.push({
        type: 'text',
        value: 'What is this?',
        delayMs: 500
    });
    msg.push({
        type: 'image',
        value: 'https://upload.wikimedia.org/wikipedia/commons/a/a3/Aptenodytes_forsteri_-Snow_Hill_Island%2C_Antarctica_-adults_and_juvenile-8.jpg'
    });
    const opts = [];
    opts.push({label: 'bob', value: 'value1'});
    opts.push({label: 'riversun', value: 'value2'});
    opts.push({label: 'john', value: 'value3'});
    msg.push({type: 'option', options: opts});
    res.json(response);
});
Enter fullscreen mode Exit fullscreen mode

JSON

{
  "output": [
    {
      "type": "text",
      "value": "What is this?",
      "delayMs": 500
    },
    {
      "type": "image",
      "value": "https://upload.wikimedia.org/wikipedia/commons/a/a3/Aptenodytes_forsteri_-Snow_Hill_Island%2C_Antarctica_-adults_and_juvenile-8.jpg"
    },
    {
      "type": "option",
      "options": [
        {
          "label": "bob",
          "value": "value1"
        },
        {
          "label": "riversun",
          "value": "value2"
        },
        {
          "label": "john",
          "value": "value3"
        }
      ]
    }
  ]
}

Enter fullscreen mode Exit fullscreen mode

RESULT

image


Initialization parameters

The following example shows all ChatUX initialization parameters.
You can customize the behavior of ChatUX as you like.


    const chatux = new ChatUx();

    //init parameters
    const opt = {
        renderMode: 'auto',//'auto' or 'pc' or 'mobile'
        buttonOffWhenOpenFrame: false,//true:Turn off wakeup button when the chat window is opened.only for pc mode.
        bot: {
            wakeupText: null,//user input which is automatically send to server on startup
            botPhoto: null,//URL of bot photo image
            humanPhoto: null,//URL of human photo image
            widget: {
                sendLabel: 'SEND',//label for SEND button
                placeHolder: 'Say something'//default caption for input box
            }
        },
        api: {
            endpoint: 'http://localhost:8081/chat',//endpoint of chat server
            method: 'GET',//'GET' or 'POST'
            dataType: 'json',//'json' or 'jsonp'
            errorResponse: {
                output: [
                    //Message displayed when a network error occurs when accessing the chat server
                    {type: 'text', value: 'Sorry, an error occurred'}
                ]
            }
        },
        window: {
            title: 'My chat',//window title

            //infoUrl
            // If this value is set, an 'info' icon will appear at the left of the window's
            // title bar, and  clicking this icon will jump to this URL
            infoUrl: 'https://github.com/riversun/chatux',
            size: {
                width: 350,//window width in px
                height: 500,//window height in px
                minWidth: 300,//window minimum-width in px
                minHeight: 300,//window minimum-height in px
                titleHeight: 50//title bar height in px
            },
            appearance: {
                //border - border style of the window
                border: {
                    shadow: '2px 2px 10px  rgba(0, 0, 0, 0.5)',
                    width: 0,
                    radius: 6
                },
                //titleBar - title style of the window
                titleBar: {
                    fontSize: 14,
                    color: 'white',
                    background: '#4784d4',
                    leftMargin: 40,
                    height: 40,
                    buttonWidth: 36,
                    buttonHeight: 16,
                    buttonColor: 'white',
                    buttons: [
                        //Icon named 'hideButton' to close chat window
                        {
                            fa: 'fas fa-times',//specify font awesome icon
                            name: 'hideButton',
                            visible: true
                        }
                    ],
                    buttonsOnLeft: [
                        //Icon named 'info' to jump to 'infourl' when clicked
                        {
                            fa: 'fas fa-comment-alt',//specify font awesome icon
                            name: 'info',
                            visible: true
                        }
                    ],
                },
            }
        },
        //wakeupButton style
        wakeupButton: {
            right: 20,//right position in pixel
            bottom: 20,//bottom position in pixel
            size: 60,//wakeup button size
            fontSize: 25//wakeup button font size for fontawesome icon
        },
        //Define a callback method to be called when an event occurs
        methods: {
            onChatWindowCreate: (win) => {
                //Called only once when a chat window is created
                console.log('#onChatWindowCreate');
            },
            onChatWindowPause: (win) => {
                //Called when the chat window is closed
                console.log('#onChatWindowPause');
            },
            onChatWindowResume: (win) => {
                //Called when the chat window is back to open
                console.log('#onChatWindowResume');
            },
            onUserInput: (userInputText) => {
                //Called back when the user enters text.
                //In other words, this method can intercept text input.
                // If it returns true, it is treated as consumed and no user-input-text is sent to the server.
                console.log('#onUserInput userInputText=' + userInputText);
                if (userInputText === 'end') {
                    const consumed = true;
                    chatux.dispose();
                    return consumed;
                }
            },
            //For local test, get the user input text but stop accessing the chat server.
            // onServerProcess: (userInputText) => {
            //     const response = {"output": [{"type": "text", "value": 'You said "' + userInputText + '"'}]};
            //     return response;
            // },
            onServerResponse: (response) => {
                //A callback that occurs when there is a response from the chat server.
                // You can handle server responses before reflecting them in the chat UI.
                console.log('#onServerResponse response=' + JSON.stringify(response));
                return response;
            }
        }
    };

    //initialize
    chatux.init(opt);

    chatux.start(true);//true:open chat UI automatically
Enter fullscreen mode Exit fullscreen mode

Summary

  • I introduced how to make a chat UI that supports both smartphone and PC browser with ChatUX.

  • If you want more custom, see README at https://github.com/riversun/chatux and source code may be helpful.

Top comments (0)