Rasa Webchat Integration

Hi all,

I had created a video tutorial in which I have shown how you can connect Rasa bot with the Webchat:

6 Likes

That works! thanks.

1 Like

Welcome, glad that it helped you :slight_smile:

Hey , hope you are doing well . I want to fetch te userID from the html as below , That is once the user logs in the website , i want to fetch the userID to make api calls .

Chat widget
// Or you can replace latest with a specific version Thank you

Here im running my application with,

> rasa run --enable-api -vv

because of my notification thing but here i want to try with, **

> rasa run -m models --enable-api --cors “*” --debug so how can i combine them and run

Hey @rishier827, I didn’t understand what are you trying to say can you explain in detail :sweat_smile:

1 Like

Thankz problem solved☺

@JiteshGaikwad to use customdata in actions.py file , or fill slots with it ?

Thankz

Hi @Aashay1, sorry for the late reply, I have updated the socket.io channel for extracting the customData that you can send from the rasa-webchat, just follow the below steps and it will work:

Step1: Just add the socketChannel.py file from this repository to your project :

socketChannel_RasaBot/socketChannel.py at master · JiteshGaikwad/socketChannel_RasaBot · GitHub

Step2: Now register the above channel in your credentials.py file as mentioned in this repo:

socketChannel_RasaBot/credentials.yml at cae5b9c314238dfd927634f66b9a5c2a962bd662 · JiteshGaikwad/socketChannel_RasaBot · GitHub

Step3: Now in the bot-ui i.e rasa-webchat, add the customData that you want to send as mentioned here:

GitHub - botfront/rasa-webchat: A feature-rich chat widget for Rasa and Botfront

Step4: Now if you want to extract the customData, just write down the below code in your actions.py file:

socketChannel_RasaBot/actions.py at cae5b9c314238dfd927634f66b9a5c2a962bd662 · JiteshGaikwad/socketChannel_RasaBot · GitHub

I have written the function that extracts the metadata from the tracker, you can get it here:

socketChannel_RasaBot/actions.py at cae5b9c314238dfd927634f66b9a5c2a962bd662 · JiteshGaikwad/socketChannel_RasaBot · GitHub

Note: I have just updated the socket.io channel’s handle_message method to extract the customData as metadata :

socketChannel_RasaBot/socketChannel.py at cae5b9c314238dfd927634f66b9a5c2a962bd662 · JiteshGaikwad/socketChannel_RasaBot · GitHub

Let me know if this helps you :slight_smile:

4 Likes

Hi @JiteshGaikwad, I am sorry to ask a silly questions as I am a fresher , but how to add multiple custom Data

Try the below code and let me know if this helps:

{“customData”:[{“key1”:“value1”,“key2”:“value2”}]}

1 Like

Did this solved your problem?

Just one last question , My actions server and webchat is running and i want to know the current tracker state , How am i suppose to do it in python

Thanks a lot ,

You can get the current tracker state using the below code:

tracker.current_state()

1 Like

Hi @JiteshGaikwad, I Think i am using it the wrong way ,

Please have a look at my actions.py and index.script file below

from future import absolute_import from future import division from future import unicode_literals

from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher

from rasa.core.actions.action import Action from rasa.core.events import SlotSet from rasa_sdk import Tracker from rasa_sdk.executor import CollectingDispatcher

from typing import Dict, Text, Any, List import requests from rasa_sdk import Action from rasa_sdk.events import SlotSet, FollowupAction from rasa_sdk.forms import FormAction

from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher

def extract_metadata_from_tracker(tracker): events = tracker.current_state()[‘events’] user_events = [] for e in events: if e[‘event’] == ‘user’: user_events.append(e) print(e[‘event’])

return user_events[-1]['metadata']

class GetLeaveBalance(Action):

def name(self):
    return 'get_leave_balance'

def run(self, dispatcher, tracker, domain):
    
    
    #importing lib to connect with wsdl 
    from suds.client import Client
    from suds.sax.element import Element
    
    #specfying the wsdl url and setting the client 
    url = "http://devmobileapi.xxxxxxxxxxxxxxxxx.in/API/xxxxxxxxxxxxxxxxx.svc?wsdl"
    client = Client(url)
    
    #creating the headers for auth in service xml and setting the values for both API-key and API-Code
    Namespace = ('ns2', 'http://xxxxxxxxxxxxxxxxxxx.com/v1')
    name_space = Element('APICode', ns=Namespace).setText('xxxxxxxxxxxxxxxx')

    Apikey =('ns2',"http://xxxxxxxxxxxxxxxxxxxx.com/v1")
    api_key = Element('APIKey',ns= Apikey).setText('xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ')
    
    client.set_options(soapheaders=(name_space,api_key))
    
    # getting the leave data from GetLeaveBalance for specific user 
    #leave=client.service.GetLeaveBalance("1")      **I want to fill this field** 
    leave_data= Client.dict(leave)

##################### Creating list of leave types

    leave_list= tracker.get_slot("leave_type")
    leave_t = leave_list[0]
    
    leave_type=["short_leave", "casual_leave", "sick_leave","earned_leave", "leave_without_pay",
                "paid_leave","paternity_leave","leave"]
    if leave_t in leave_type:
        
        if leave_t == "leave":
            short_l=leave_data['LeaveBalance']["LeaveBalanceData"][0]["Balance"]
            casual_l=leave_data['LeaveBalance']["LeaveBalanceData"][1]["Balance"]
            sick_l=leave_data['LeaveBalance']["LeaveBalanceData"][2]["Balance"]
            earned_l=leave_data['LeaveBalance']["LeaveBalanceData"][3]["Balance"]
            without_pay_l=leave_data['LeaveBalance']["LeaveBalanceData"][4]["Balance"]
            privilege_l=leave_data['LeaveBalance']["LeaveBalanceData"][5]["Balance"]
            Paternity_l=leave_data['LeaveBalance']["LeaveBalanceData"][6]["Balance"]
            
            text_leave=(""" Your Leave balance summary is as follows:
                Short Leave :{}
                Casual Leave : {}
                Sick Leave: {}
                Earned Leave : {}
                Leave Without Pay : {}
                Privilege Leave : {}
                Paternity Leave : {}""".format(short_l,casual_l,sick_l,earned_l,without_pay_l,privilege_l,privilege_l,Paternity_l))
            
         
        
        if leave_t=="short_leave":
              short_l=leave_data['LeaveBalance']["LeaveBalanceData"][0]["Balance"]
              
              text_leave=("""you have {} short leave left""".format(short_l))
              
        if leave_t=="casual_leave":
             casual_l=leave_data['LeaveBalance']["LeaveBalanceData"][1]["Balance"]
             text_leave=("""you have {} casual leave left""".format(casual_l))
             
        if leave_t=="sick_leave":
             sick_l=leave_data['LeaveBalance']["LeaveBalanceData"][2]["Balance"]
             text_leave=("""you have {} sick leave left""".format(sick_l))
             
        if leave_t=="earned_leave":
             earned_l=leave_data['LeaveBalance']["LeaveBalanceData"][3]["Balance"]
             text_leave=("""you have {} earned leave left""".format(earned_l))
             
        if leave_t=="leave_without_pay":
             #without_pay_l=leave_data['LeaveBalance']["LeaveBalanceData"][4]["Balance"]
             text_leave=("""You are limited to have only 30 unplaned leaves in a year""")
             
        if leave_t=="paid_leave":
             privilege_l=leave_data['LeaveBalance']["LeaveBalanceData"][5]["Balance"]
             text_leave=("""you have {} paid leave left""".format(privilege_l))
             
        if leave_t=="paternity_leave":
             Paternity_l=leave_data['LeaveBalance']["LeaveBalanceData"][6]["Balance"]
             text_leave=("""you have {} paternity leave left""".format(Paternity_l))             
    else:           
        text_leave=("please enter a valid leave type")
        
    dispatcher.utter_message(text_leave)

    return []     

Index.html (script )file div id=“webchat” script src=“https://storage.googleapis.com/mrbot-cdn/webchat-latest.js”></script // Or you can replace latest with a specific version script WebChat.default.init({ selector: “#webchat”, initPayload: “/get_started”, customData: {“language”: “en”,"useID":“1”}, // arbitrary custom data. Stay minimal as this will be added to the socket socketUrl: “http://localhost:5005”, socketPath: “/socket.io/”, title: “Title”, subtitle: “Subtitle”, }) script

what’s the error?

Hi @JiteshGaikwad I have copied the fill in the the repo , Copied the code into actions.py file ,

I am not sure how to use it. I am very new to this field !!!

Thankz Aashay

Hi Guys,

I am able to solve, How to pass Custom data and set slot with rasa web

#################### you html webchat scrip #####################

div id=“webchat” script src=“https://storage.googleapis.com/mrbot-cdn/webchat-latest.js”></script // Or you can replace latest with a specific version script WebChat.default.init({ selector: “#webchat”, initPayload : ‘/get_started{“userID”:“1”}’, customData:{}, // arbitrary custom data. Stay minimal as this will be added to the socket socketUrl: “http://localhost:5005”, socketPath: “/socket.io/”, title: “Title”, subtitle: “Subtitle”, }) /script

#################### your actions.py ############# from future import absolute_import from future import division from future import unicode_literals

from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher

from rasa.core.actions.action import Action from rasa.core.events import SlotSet from rasa_sdk import Tracker from rasa_sdk.executor import CollectingDispatcher

from typing import Dict, Text, Any, List import requests from rasa_sdk import Action from rasa_sdk.events import SlotSet, FollowupAction from rasa_sdk.forms import FormAction

from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from rasa.core.events import UserUttered

from rasa_core.trackers import DialogueStateTracker

class GetLeaveBalance(Action):

def name(self):
    return 'get_leave_balance'


def run(self, dispatcher, tracker, domain):
    
    
    #importing librires to connect with wsdl 
    from suds.client import Client
    from suds.sax.element import Element
    
    userID = tracker.get_slot("userID")
     
    print("userID :",userID)

Thank you

Hi Guys,

I am able to solve, How to pass Custom data and set slot with rasa web

#################### you html webchat scrip #####################

div id=“webchat” script src=“https://storage.googleapis.com/mrbot-cdn/webchat-latest.js”></script // Or you can replace latest with a specific version script WebChat.default.init({ selector: “#webchat”, initPayload : ‘/get_started{“userID”:“1”}’, customData:{}, // arbitrary custom data. Stay minimal as this will be added to the socket socketUrl: “http://localhost:5005”, socketPath: “/socket.io/”, title: “Title”, subtitle: “Subtitle”, }) /script

#################### your actions.py ############# from future import absolute_import from future import division from future import unicode_literals

from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher

from rasa.core.actions.action import Action from rasa.core.events import SlotSet from rasa_sdk import Tracker from rasa_sdk.executor import CollectingDispatcher

from typing import Dict, Text, Any, List import requests from rasa_sdk import Action from rasa_sdk.events import SlotSet, FollowupAction from rasa_sdk.forms import FormAction

from typing import Any, Text, Dict, List

from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from rasa.core.events import UserUttered

from rasa_core.trackers import DialogueStateTracker

class GetLeaveBalance(Action):

def name(self):
    return 'get_leave_balance'


def run(self, dispatcher, tracker, domain):
    
    
    #importing librires to connect with wsdl 
    from suds.client import Client
    from suds.sax.element import Element
    
    userID = tracker.get_slot("userID")
     
    print("userID :",userID)

Thank you

Hi @JiteshGaikwad, can you help explain what is the difference between a button and a quick_replies in this Webchat? They both look the same visually and i am a little confused on this.

Can you point me to any reference where i can check on this info?

Thanks