Create a Simple Chat bot in SAP UI5

by | Apr 20, 2023 | UI5, UI5 Integrations

Home » SAP » UI5 » UI5 Integrations » Create a Simple Chat bot in SAP UI5

Introduction

A chatbot is an important function and has become part of all front-end applications nowadays. In this article, we will Create a Simple Chat bot in SAP UI5.

What is Chat Bot?

A Chat Bot is an application via which any person can interact with a system or computer. The answers generated by the computers may be hardcoded based on the questions or can be real-time generated with the help of Artificial intelligence.

How to Implement Chatbot in SAP UI5?

In this article, we will develop a simple chat bot where the answers are hardcoded in the UI itself. You can always replace those responses by sending the inputs to your APIs and showing the result of the APIs as output.

Steps to Create a Simple Chat Bot in SAP UI5

Steps to Create a Simple Chat bot in SAP UI5

Flow of Chat Bot

Flow of Chat Bot

View.xml

<mvc:View controllerName="Test.Test.controller.Main" xmlns:mvc="sap.ui.core.mvc" displayBlock="true" xmlns="sap.m" xmlns:core="sap.ui.core"
    xmlns:html="http://www.w3.org/1999/xhtml">
    <Shell id="shell">
        <App id="app">
            <pages>
                <Page id="page" title="Simple Chat Bot using SAP UI5">
                    <content></content>
                    <footer>
                        <OverflowToolbar>
                            <ToolbarSpacer/>
                            <Button text="Click to Chat" icon="sap-icon://message-popup" press="handleMessagePopoverPress"/>
                        </OverflowToolbar>
                    </footer>
                </Page>
            </pages>
        </App>
    </Shell>
</mvc:View>

 

Controller.js

sap.ui.define([
    "sap/ui/core/mvc/Controller",
    "sap/m/MessageBox",
    "sap/m/MessageToast",
    "sap/ui/model/json/JSONModel"
], function (Controller, MessageBox, MessageToast, JSONModel) {
    "use strict";
    return Controller.extend("Test.Test.controller.Main", {
        handleMessagePopoverPress: function (oEvent) {
            // create popover
            if (!this._oPopover) {
                this._oPopover = sap.ui.xmlfragment("Test.Test.fragment.Bot", this);
                this.getView().addDependent(this._oPopover);
            }
            if (this._oPopover.isOpen()) {
                this._oPopover.close();
            } else {
                this._oPopover.openBy(oEvent.getSource());
            }
        },
        ask: function (oEvent) {
            var input = sap.ui.getCore().byId("query").getValue();
            var fBox = new sap.m.FlexBox({
                alignItems: "Start",
                justifyContent: "End"
            });
            var text = new sap.m.Text({
                text: input
            });
            text.addStyleClass("chat2");
            fBox.addItem(text);
            fBox.addStyleClass("sapUiSmallMarginTop");
            sap.ui.getCore().byId("chat").addItem(fBox);
            sap.ui.getCore().byId("query").setValue("");
            this.answer(input);
        },
        answer: function (query) {
            var greetings = ["hi", "hello", "what's up", "wassup"];
            var greetings_response = ["Hello", "Nice to meet you", "Hmm mm"];
            var job = ["what can you do for me?", "what can you do for me", "what can you do", "what can you do?"];
            if (query) {
                if (greetings.indexOf(query.toLowerCase()) != -1) {
                    var item = greetings_response[Math.floor(Math.random() * greetings_response.length)];
                    var a = this.createText(item);
                    this.reply(a);
                } else if (query.toLowerCase().match(/what.*you.*do/g)) {
                    var a = this.createText("What do you want me to do? XD");
                    var b = this.createButton("Show you your Questionnaire");
                    var c = this.createButton("Show you user details");
                    var d = this.createButton("Delete users");
                    var e = this.createButton("Do something naughty");
                    var vbox = new sap.m.VBox();
                    vbox.addItem(a);
                    vbox.addItem(b);
                    vbox.addItem(c);
                    vbox.addItem(d);
                    vbox.addItem(e);
                    this.reply(vbox);
                } else {
                    this.reply();
                }
            }
        },
        reply: function (ans) {
            if (ans) {
                var fBox = new sap.m.FlexBox({
                    alignItems: "Start",
                    justifyContent: "Start"
                });
                ans.addStyleClass("chat1");
                ans.addStyleClass("sapUiSizeCompact");
                fBox.addItem(ans);
                fBox.addStyleClass("sapUiSmallMarginTop");
                sap.ui.getCore().byId("chat").addItem(fBox);
            } else {
                var fBox = new sap.m.FlexBox({
                    alignItems: "Start",
                    justifyContent: "Start"
                });
                var text = new sap.m.Text({
                    text: "Did not recognize you. Come again"
                });
                text.addStyleClass("chat1");
                fBox.addItem(text);
                fBox.addStyleClass("sapUiSmallMarginTop");
                sap.ui.getCore().byId("chat").addItem(fBox);
            }
            $("#pop-cont").scrollTop($("#pop-cont")[0].scrollHeight - $("#pop-cont").height());
        },
        onClear: function (oEvent) {
            sap.ui.getCore().byId("chat").removeAllItems();
        },
        onScroll: function () {
            $("#pop-cont").scrollTop($("#pop-cont")[0].scrollHeight - $("#pop-cont").height());
        },
        createText: function (text) {
            var text = new sap.m.Text({
                text: text
            });
            return text;
        },
        buttonPress: function (btext) {
            var that = this;
            var naughty = ["I just did.\n I was being naughty by giving you the option of being naughty :D", "You should not ask for that ;)",
                "Its rude to ask for it", "Gotcha :P ", "That was a character test, you failed"
            ];
            var btext = btext.toLowerCase();
            if (btext.match(/show.*ques/g)) {
                var Input = new sap.m.Input({
                    submit: function (oEvent) {
                        that.onTestPress(oEvent, oEvent.getParameter("value"));
                    }
                });
                var a = this.createText("Provide the SET NAME-SET ID  and hit Enter");
                var vbox = new sap.m.VBox();
                vbox.addItem(a);
                vbox.addItem(Input);
                this.reply(vbox);
            } else if (btext.match(/show.*user/g)) {
                var Input = new sap.m.Input({
                    submit: function (oEvent) {
                        that.onUserPress(oEvent, oEvent.getParameter("value"));
                    }
                });
                var a = this.createText("Provide the USER_ID  and hit Enter");
                var vbox = new sap.m.VBox();
                vbox.addItem(a);
                vbox.addItem(Input);
                this.reply(vbox);
            } else if (btext.match(/delete.*user/g)) {
                var a = this.createText("Sorry the function is not yet available");
                this.reply(a);
            } else if (btext.match(/naughty/g)) {
                var item = naughty[Math.floor(Math.random() * naughty.length)];
                var a = this.createText(item);
                this.reply(a);
            }
        },
        createButton: function (text) {
            var that = this;
            var link = new sap.m.Button({
                text: text,
                type: sap.m.ButtonType.Accept,
                press: function (oEvent) {
                    that.buttonPress(text);
                }
            });
            link.addStyleClass("sapUiSmallMarginTop");
            return link;
        },
    });
});

 

Bot.fragment.xml

<core:FragmentDefinition id="fragment23" xmlns="sap.m" xmlns:core="sap.ui.core">
    <Popover id="pop" title="Welcome to UI5 Chat Bot" class="sapUiContentPadding" resizable="true" verticalScrolling="true" contentHeight="200px"
        placement="Top" initialFocus="query">
        <footer>
            <Toolbar>
                <ToolbarSpacer/>
                <Input submit="ask" id="query" type="text" width="200px" value="" class="sapUiSmallMargin"/>
                <Button text="Clear" press="onClear"/>
            </Toolbar>
        </footer>
        <VBox id="chat">
            <FlexBox class="sapUiSmallMarginTop" alignItems="Start" justifyContent="Start">
                <items>
                    <Text class="chat1" text="How may I help you?"/>
                </items>
            </FlexBox>
        </VBox>
    </Popover>
</core:FragmentDefinition>

Output

Simple Chat Bot using SAP UI5

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Author