Wednesday, May 30, 2018

Oracle Bot Cloud (IBCS): Custom UI

Problem Description: In this blog I would be going over various options to build a web UI for IBCS chat bot.

By default IBCS provides two sdks to build web UI for Chatbot. We can download those sdks from
http://www.oracle.com/technetwork/topics/cloud/downloads/mobile-suite-3636471.html under heading Bots Client SDK


We can follow link https://docs.oracle.com/en/cloud/paas/mobile-suite/use-chatbot/bot-channels.html#GUID-A0A40E26-54BA-4EDD-A4C5-95D498D6CF61 to find out how to use these SDKs.


Widget is very cool and rich but still at times you want to build your own custom UI instead of widget. To do that you can follow
https://docs.oracle.com/en/cloud/paas/mobile-suite/use-chatbot/bot-channels.html#GUID-78F6DD7E-5085-476B-AD03-1318D9107D39

In this blog I am trying to enhance that code to handle postback requests. Also this blog will help me in my next blog to achieve voice based conversation.

1. Add below code in html
HTML:
 <div id="no-display" style="display:none;"></div>
       <p>User ID: <span id="user-id"></span></p>
       <ul id="conversation"></ul>
    <input type="text" id="text-input" placeholder="text">

<script src="js/app.js"></script>


2. Add app.js inside js directory. It can have following code
!function(e,t,n,r){
    function s(){try{var e;if((e="string"==typeof this.response?JSON.parse(this.response):this.response).url){var n=t.getElementsByTagName("script")[0],r=t.createElement("script");r.async=!0,r.src=e.url,n.parentNode.insertBefore(r,n)}}catch(e){}}var o,p,a,i=[],c=[];e[n]={init:function(){o=arguments;var e={then:function(t){return c.push({type:"t",next:t}),e},catch:function(t){return c.push({type:"c",next:t}),e}};return e},on:function(){i.push(arguments)},render:function(){p=arguments},destroy:function(){a=arguments}},e.__onWebMessengerHostReady__=function(t){if(delete e.__onWebMessengerHostReady__,e[n]=t,o)for(var r=t.init.apply(t,o),s=0;s<c.length;s++){var u=c[s];r="t"===u.type?r.then(u.next):r.catch(u.next)}p&&t.render.apply(t,p),a&&t.destroy.apply(t,a);for(s=0;s<i.length;s++)t.on.apply(t,i[s])};var u=new XMLHttpRequest;u.addEventListener("load",s),u.open("GET",r+"/loader.json",!0),u.responseType="json",u.send()
}(window,document,"Bots", "<Your-Bot-sdk-url>");

var appId = '<Your app id>';

Bots.init({
        appId: appId, embedded: true
    }).then(function (res){
        console.log("init complete");

    });

Bots.render(document.getElementById('no-display'));


var inputElement = document.getElementById('text-input');
  inputElement.onkeyup = function(e) {
  if (e.key === 'Enter') {
    var totalMsg = Bots.getConversation().messages.length;
    if(Bots.getConversation().messages[totalMsg-1] && Bots.getConversation().messages[totalMsg-1].actions){
        
        var actions = Bots.getConversation().messages[totalMsg-1].actions.filter(function(action){
            return action.text === inputElement.value; //Improve it by performing case insensitive matching
        })
        if(actions){
            Bots.triggerPostback(actions[0]._id).then(function() {
                        inputElement.value = '';
                    });
        }
        
    }
    else{
       Bots.sendMessage(inputElement.value).then(function() {
                inputElement.value = '';
            }); 
    }
        
    }
   
  }


function displayUserMessage(message) {
    console.log(message);
            var conversationElement = document.getElementById('conversation');
            var messageElement = document.createElement('li');
            messageElement.innerText = message.name + ' says "' + message.text + '"';
            conversationElement.appendChild(messageElement);
        }

        function createButtonElement(action) {
            var btnElement = document.createElement('button');
            var btnTitle = document.createTextNode(action.text);
            btnElement.appendChild(btnTitle);
            btnElement.onclick = function(e){Bots.triggerPostback(action._id);};
            return btnElement;
        }

    function displayServerMessage(message) {
         console.log(message);
            var conversationElement = document.getElementById('conversation');
            var messageElement = document.createElement('li');
            var text = 'Server says "' + message.text + '"';
            messageElement.innerText = text;

            if(message.actions && message.actions.length > 0){
                var wrapperElement = document.createElement('div');
                for(var i = 0; i < message.actions.length; i++){
                    var action = message.actions[i];
                    var btnElement = createButtonElement(action);
                    wrapperElement.appendChild(btnElement);
                }
                messageElement.appendChild(wrapperElement);
                isPostBackRequired = true;
                lastPostBackServerMsg = message;
            }
            conversationElement.appendChild(messageElement);


        }
  // display new messages
  Bots.on('message:sent', displayUserMessage);

  Bots.on('message:received', displayServerMessage);



NOTE:
1. Bot-sdk-url is url of your sdk directory. If you copy bot-sdk inside js directory as bot-client-sdk-js and server is running on port 8000, your bot-sdk-url would be http://localhost:8000/js/bots-client-sdk-js
2. app-id mentioned in above code is given on channels page of IBCS (once you register a web channel)

3. Input element in which user types message is enhanced to handle postBack message of user.
4. displayUserMessage function adds user typed message in list
5. displayServerMessage function adds server message in list. It also create appropriate buttons if server wants user to select one value.

UI is very crude but it gives you complete control to decorate it.

Now we have a very basic UI ready. My idea is to enhance it further and add voice feature to it in my Next blog.

Thats all in this blog.

32 comments:

Blogger said...

Do you understand there is a 12 word phrase you can tell your partner... that will trigger deep feelings of love and impulsive appeal to you deep inside his heart?

That's because deep inside these 12 words is a "secret signal" that triggers a man's instinct to love, worship and care for you with all his heart...

12 Words Who Fuel A Man's Desire Instinct

This instinct is so hardwired into a man's mind that it will make him work harder than before to do his best at looking after your relationship.

In fact, triggering this powerful instinct is so important to getting the best possible relationship with your man that the instance you send your man a "Secret Signal"...

...You'll instantly find him open his mind and heart for you in a way he never expressed before and he'll see you as the one and only woman in the galaxy who has ever truly interested him.

Jessica Cromwell said...
This comment has been removed by the author.
saniyaa said...

Uncommon tips and clear. This will be to a great degree supportive for me when I get a chance to start my blog. HackingUniversity

Notress said...

Kumpulan Script Termux

Affluenz IT Academy said...

Nice article. Studying artificial intelligence opens a world of opportunities. Join
ai training in kolkata

Alexa james said...

Hello, Such A Nice Article. Great Share. Also, if You Are Looking for sofas reviews and Guides. then you can checkout here.
https://sofareviewsguide.puzl.com/
https://bestkidscouchreviews.blogspot.com/

Catherine said...

custom Logo Design services

jatin said...

Check this out how Google Verified Calls beating Truecaller 2020

sam said...

very interesting , good job and thanks for sharing such a good blog.
Computer Repair Largo

Muhammad Azwar said...

Nice Article, thanks for this information
Also check this out
Laptops, Mobiles, Games, Tv, Smartwatches etc Daily Tech News Updates.

Technology said...

Best VR Headset For iPhone 7 Plus Try it Now

Anonymous said...

Nice Blog. Thanks for sharing this one. It will be helpful for those who are unaware about it. If anyone is looking to build apps with the latest trends & technologies, reach Way2Smile Solutions. Android Application Development Companies in Chennai

Anonymous said...

this blog is very help to me its give me lots of information iam also writing same blog on Salesforce Spring 21 Sp21 Certification Material and exam

Anonymous said...

Thanks for sharing this useful information. It will be helpful for the freshers to Learn easily.

If you looking for best iOS app development company, reach out way2smile Best iPhone App Development Company in Chennai

Ashish Kumar said...

Thanks for updates.

ivr service provider

toll free number service provider

click2call service provider

International toll free number

virtual number service provider

Outbound Calling Solutions

Minavo Telecom Networks

bulk sms services

sam said...

very interesting, good job, and thanks for sharing such a good blog.
Computer Repair Largo

SparkInList said...

Very informative, I really enjoyed reading it.
Top 10 Cheapest Technologies To Generate Power at Home

sosyal adres said...

Thank you so much for sharing this post .

Tom (Admin) said...

I have gone through your blog and read articles especially technology-related. Your explanation is clear and easy to understand which helps me a lot in my blog writing Mcqs about programming. Thanks

Custom Software Development said...

Thanks for sharing this quality information with us. I really enjoyed reading. Will surely going to share this URL with my friends. Custom Software Development

Robert Doxon said...

Backups ensure that your critical data will survive any of the likely hazards. Too many individuals and companies have suffered from having their hardware lost or stolen, destroyed by fires or natural disasters, infected with malware or corrupted by targeted hacker attacks. Common sense dictates that all hard drives will eventually fail; the question is whether or not you are prepared for the worst-case scenario.
Use hyper-v backup software from Nakivo to secure your data.

Hi Tech Institute Agra said...

Hi-tech Institute is that place in Agra. Where students are being taught repairing courses with the advanced technology of mobile and laptops. Many students have completed their dream today by taking courses from hi-tech institutes.

Today the students of Hi-Tech Institute Agra are working as engineering in mobile and laptop companies in big cities.


Hi-Tech institute Agra branch

"Now all the students have the same dream,



By taking admission in Hi-tech institute,



To make your life successful.



Visit at-;

https://www.hitechinstituteagra.com/index.html

Admin said...

Watch latest Technology News in Tech News by KP

Anonymous said...

Business are widely using transcription services to keep them organized and make their communication effective. To avail the best transcription services around the globe, click here.

Graphics said...

Cool stuff you have got and you keep update all of us. Office-paket

Anonymous said...

Connect Pandora on Roku

Simply, download Pandora on Roku, login to your Pandora account, and activate it by accessing the Pandora.com/roku activation steps. Check steps

sohag sarker said...

https://www.technologysohag.com/2021/12/walton-refrigerator-2022-will-be-bumper.html?m=1Best Walton Refrigerator in 2022

Hire Bike On Rent said...

Nice blog! The blog is very informative, I enjoyed reading something that is new to me.We offer you good condition bikes that are suitable on the rash roads of mountains. Read our blogs all about Manali.
Bike on rent in Manali
Bike Rentals in Manali

Anonymous said...

Thank you so much for perfect blog hope to see this amazing blogs in coming cays custom android app development

Hamzey Sobh said...

If you are looking for Ticket traffic in USA. mytikkit is an app that provides the best services and manages all your records in a single app.

Ekta said...

Your content writing is so nyc thanku admin for this valuable work.

Read More About Technology and Computer

beyond acatalepsy said...

Hey Nice article
Book publishing in India

Hey Nice article
Book Publisher in india
Hey Nice article
self publishing in India

Hey Nice article
Delhi Book Fair

Hey Nice article
odisha book fair 2022

Hey Nice article
kolkata Book Fair

Hey Nice article
jaipur literature book fair 2022

Hey Nice article
chennai book fair 2022