Giter VIP home page Giter VIP logo

webchat's Introduction

SAP Conversational AI Webchat

Default Usage Self-Hosted Installation Getting Started on SAP Conversational AI License

REUSE status

What is a webchat?

The SAP Conversational AI webchat let you deploy a bot straight to a website. It will be embed and available through a chat box on your pages. The webchat is one of the many channels available on SAP Conversational AI, and end-to-end bot building platform. This webchat is built using the React library, along with Redux for state managment.

Compatibility

This webchat is supported by all mobile and desktop browsers in their latest versions. Internet Explorer support starts at version 9.0.

Usage

Three different installations on the webchat module are possible.

  • The default is the simplest and fatest route, and offers some customization options.
  • The self-hosted webchat offers even more customization option, but you'll have to deal with the hosting and maintenance of the module.
  • Use it as a React component

Default webchat

To use the webchat, you need an account on SAP Conversational AI and a bot. Then, go to the CONNECT tab and click on Webchat. It will open a window that lets you adjust your webchat settings, including:

  • color scheme,
  • header customization,
  • bot and user pictures,
  • webchat logo and call to action,
  • conversation duration

Once you're satisfied with the settings, click on the SAVE button. A script tag appears, and you just have to copy paste it in your web page to embed the webchat. The script must be placed in the <body> tag.

Self-hosted webchat

If you want to customize your webchat even more, you can opt for a self-hosted installatiton. Just fork this project to get started!

Installation

Clone the repository you forked, and install the dependencies.

$> git clone YOUR_REPO_URL
$> cd webchat
$> npm install

Run in development mode

$> npm run start

Eslint + prettier

$> npm run prettier

Build for production

$> npm run build

Use your webchat

Once you're done, build it and host it. To use it instead of the default one provided by SAP Conversational AI, you need to set up the Webchat channel in the CONNECT tab of your bot. You'll be using the same script as the default installation, but you have to replace the src field by your own URL.

<script
  src="YOUR_WEBCHAT_URL"
  ...
></script>

React component

You can import the webchat as a React component like the following example:

import CaiWebchat from 'webchat';

export default class ReactWebchat extends Component {
  render() {
    return (
      <CaiWebchat
        onRef={ref => {
          this.webchat = ref;
        }}
        channelId={YOUR_CHANNEL_ID}
        token={YOUR_TOKEN}
        preferences={{
          accentColor: '#E05A47',
          complementaryColor: '#FFFFFF',
          botMessageColor: '#707070',
          botMessageBackgroundColor: '#F6F6F6',
          backgroundColor: '#FFFFFF',
          headerLogo: 'https://cdn.cai.tools.sap/webchat/webchat-logo.svg',
          headerTitle: 'My awesome chatbot',
          botPicture: 'https://cdn.cai.tools.sap/webchat/bot.png',
          userPicture: 'https://cdn.cai.tools.sap/webchat/user.png',
          onboardingMessage: 'Come speak to me!',
          expanderLogo: 'https://cdn.cai.tools.sap/webchat/webchat-logo.svg',
          expanderTitle: 'Click on me!',
          conversationTimeToLive: 24,
          openingType: 'never',
          welcomeMessage: 'Hello world !',
        }}
        getLastMessage={message => {
          console.log(message)
        }}
      />
    );
  }
}

Props

Name Type Required Description
onRef function false Function which returns ref of the webchat
channelId string true Channel id (you can get in SAP Conversational AI)
token string true Token (you can get in React.ai)
preferences object true Object containing some settings
getLastMessage function false Function which returns the last message sent by the webchat

Methods

You can access these methods by using the reference of the component (use OnRef)

<CaiWebchat
  onRef={ref => this.webchat = ref }
>
...

this.webchat.clearMessages();
Name Description
clearMessages() Clear all messages in the webchat

Bot Memory management

One thing you might want to do is to send custom data from your website to the bot, like the name of the logged in user, his ID, the page he is currently on (to send product suggestions for example). To do that, you can define a window.webchatMethods.getMemory function, the webchat will call it before sending user messages, and send your arbitrary payload along with the message to the bot.

If you use SAP Conversational AI's bot-builder (you should :)), your payload will be put in the memory of the conversation, meaning that you will be able to access this data in your bot-builder. Let's say you send this as payload : { "userName": "Dominik", "userId": 123456 }, you will then be able to send this as a greeting message : Hello {{ memory.userName }} ! How do you do ?.

window.webchatMethods.getMemory must return a JSON object or a Promise resolving a JSON object :

  • { "memory": { ... }, "merge": <boolean> } where { ... } is your arbitrary payload. merge is an instruction for the bot-builder. If set to true, the payload will be merged with the existing memory, overriding common keys but keeping the ones absent from the payload. If set to false, the memory will be replaced entirely by your payload.

If your getMemory function takes more than 10 seconds, the message will be sent anyway, without waiting for your function to finish.

Examples :

<html>
  <head>
    <script>
      window.webchatMethods = {
        // called at each user message
        getMemory: (conversationId) => {
          const memory = { userName: 'Dominik Bousquet', userId: 123456 }
          return { memory, merge: true }
        }
      }
    </script>
  </head>
  <body>
    <script src="https://cdn.cai.tools.sap/webchat/webchat.js"
      channelId="<channelId>"
      token="<token>"
      id="cai-webchat"
    ></script>
  </body>
</html>
window.webchatMethods = {
  getMemory: (conversationId) => {
    const getCookie = (name) => {
      const value = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)')
      return value ? value[2] : null
    }
    const userName = getCookie('userName')
    const memory = { userName, currentUrl: window.location.href }
    return { memory, merge: true }
  }
}
window.webchatData = {}
window.webchatMethods = {
  getMemory: (conversationId) => {
    if (window.webchatData.savedUserData) {
      return { memory: window.webchatData.savedUserData, merge: true }
    }
    return new Promise((resolve, reject) => {
      axios.get('/current_user')
        .then((response) => {
          const memory = { userName: response.data.name, userId: response.data.id }
          window.webchatData.savedUserData = memory
          resolve({ memory, merge: true })
        })
        .catch(reject)
    })
  }
}
window.webchatData = {}
window.webchatMethods = {
  getMemory: (conversationId) => {
    if (!window.webchatData.oriUrl) {
      window.webchatData.oriUrl = window.location.href
    }
    // merge: false - reset the conversation if the user
    // switched to another page since the first message
    if (window.webchatData.oriUrl !== window.location.href) {
      return { memory: {}, merge: false }
    }
    return { memory: { userName: 'Dominik' }, merge: true }
  }
}

Getting started with SAP Conversational AI

We build products to help enterprises and developers have a better understanding of user inputs.

  • NLP API: a unique API for text processing, and augmented training.
  • Bot Building Tools: all you need to create smart bots powered by SAP Conversational AI's NLP API. Design even the most complex conversation flow, use all rich messaging formats and connect to external APIs and services.
  • Bot Connector API: standardizes the messaging format across all channels, letting you connect your bots to any channel in minutes.

Learn more about:

API Documentation Discover the platform First bot tutorial Advanced NodeJS tutorial Advanced Python tutorial

License

Copyright (c) [2016] SAP Conversational AI

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

webchat's People

Contributors

ajinkyapatil8190 avatar akhnot avatar akshaykmr080 avatar dependabot[bot] avatar diesirae avatar dorianequartino avatar fksi avatar janteuni avatar jasmineeeewu avatar jhoudan avatar jwandrocke avatar jyguyomarch avatar lucasdchamps avatar oliviernguyen avatar thierry4l avatar yoojene avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webchat's Issues

Custom Webchat widget

Hi, guys!

At my company, we are looking for a chatbot service for a website with a strict condition to have an entire own appearance of a web widget. So looks like this repo really fits for us as we want to create own bot client based on this project and still use https://recast.ai as a chatbot service. But could you please confirm that we can fork this repo, modify it as we need and connect to our user Webchat channel without any gotchas?

Thanks in advance!

ChatId fetching / message polling race condition

To 100% of the time configure the webchat to be always open from the admin panel.

Then you'll see a poll request to /conversation//?poll and also a cors message for that request.
The thing is nothing stops the components from doing the poll when no/insufficient credentials are given.
The app recovers once the state is updated and the next poll cycle comes around.

poll-404
cors-errors

How to create webchat iframe window?

for example snatchbot.me has the dedicated link for the webchat which I could embed to my site wherever I want

For example
<iframe src="https://snatchbot.me/webchat/?botID=xxxxxx&appID=IZxx0Q4kcjNhJWtW61ExxO06b" width="100%" height="100%" frameborder="0" scrolling="no"></iframe>

Can I make the same with recast.ai webchat? How?

Open WebChat on Buttonclick

Hi, is it possible to create a HTML button to open the WebChat (created in SAP Conversational AI)?

Thanks in advance:)

Remove the lib folder from git

You should not commit the lib folder as it's only generated files.
Add this folder to you .gitignore and you should be good to go!

Problem with page events after Webchat loads

Problem Description
When Webchat loads in a page, it breaks some features of the page. For example - auto suggest or button doesn't work.

Steps to reproduce

  1. Open Chrome and go to [(https://www.google.com/)]
  2. Open Developer Tools --> Console.
  3. Copy-paste the below code to dynamically load the Webchat script (add your channelid and token in below script).

window.loadRecastAI = function () { var oElem = document.createElement("div"); oElem.id = "recast-ai"; var oScript = document.createElement("script"); oScript.setAttribute('src', 'https://cdn.recast.ai/webchat/webchat.js'); oScript.setAttribute('channelId', '**Insert your Channel ID here**'); oScript.setAttribute('token', '**Insert your Token here**'); oScript.setAttribute('id', 'recast-webchat'); oElem.appendChild(oScript); document.body.appendChild(oElem); }; window.loadRecastAI();

  1. Now type something in google search text box. The auto suggest should not work. Also click on Microphone button, it should do nothing.

New user preference: Webchat position in the page

Add a new key in "preferences" object to choose if the webchat is sticky at the right or the left of the page. And if the Webchat opens like now from the bottom to top, or from the right to left / or the left to right.

Navigation with Routers within Fiori Web App

Hello,

I am trying to do navigation within my web app. I have different views like this:
myapp.com/view1
myapp.com/view2

Based on the user intent such as "go to view2", the route would change to "view2".

I included the script tag in my index.html and I can see the chat but I don't have access to my root component to call the router method, is the dev team planning to have a workaround for this navigation feature that I am trying to implement?

How to use with Fiori App

index.html in Fiori App doesn't import the SAP Conversational AI webchat script. I am trying to import my chatbot to my Fiori App. Docs say I need to put the following tag into the body tag of my index.html, <script src="https://cdn.cai.tools.sap/webchat/webchat.js" channelId="<Channel ID>" token="<token ID>" id="cai-webchat" ></script>

but in Fiori index.html imports don't work based on this post so one has to implicitly require the library in manifest.json or create a separate folder and put the library code in it.

I have read the docs and in React it is as easy as doing <import CaiWebchat from 'webchat';> and then one can provide the token IDs.

I came across to this post, but the OP doesn't need to provide any token IDs when importing the library. Also, the import is not from CDN unlike my case where I am trying to provide tokens and get the library from CDN. I tried putting the js code into a file and point to it in my manifest.json but without the token IDs it doesn't run.
Also, the issue #5 tells the same problem, but the OP seems to have a problem with url appending.
I also created a SAP question here
Any help is appreciated.

Using Webchat Channel: message type "list" is not displayed

In the bot i use list of response message, it looks good in recast.ai Test/CHAT WITH YOUR BOT.
But when i tried to use WebChat channel, everything is the same as in CHAT WITH YOUR BOT except:
The bot response with empty message when it suppose to be a list.

The button and text message is fine. only the list type message is not displayed.

I trace the network and it looks the list content is returned, but it is just not displayed.

I tested in Chrome and Safari.

Is it a known issue? or do i did something wrong?

Swipe on mobile

When I have messages with arrows:

  • Carousel
  • Quick replies

If I'm in a mobile version, I should use the swipe gesture to navigate, and not only the touch on arrows.

Get the chatID

Is there some way to get the current chatID in the client-side using Javascript/Jquery ?

The error message "Wrong memory format" is always shown.

This error message seems to be issued by the method getMemoryOptions (the line console.error(WRONG_MEMORY_FORMAT) ) in src/cntainers/Chat/index.js, even if it is not necessary to set the memory value from Webchat.
Is it necessary to always set the memory value when sending the message?
I think it is not suitable.
At least this message should be console.warn or console.log, not console.error.
Please consider this.

Integrate O365 SSO

Hello,

does somebody know how to implement it?
How do I retrieve the SSO required data out of the page to integrate it to the bot?

Thank you!

Fix the Quick Replies alignement

I always have arrows for quick replies, and sometimes it's not needed:

  • Quick replies should be align at the center of the webchat when they are one or two and don't use all the space.
  • When there is multiple quick replies and we need arrows to navigate, the first time they appears on the screen, they are stick to the right and should take all the space of the screen:

screen shot 2018-10-14 at 19 26 41

Like here, when I click a first time to the right arrow, then back to the left arrow, they appears well and take all the space:

screen shot 2018-10-14 at 19 27 04

Displaying more than 3 buttons in response

Hi everyone,

i´m currently trying to display more than just three button elements in the chat window, but for some reason it does not work. Does anyone know where the settings for this case are?

Here an example:

 replies: [
        {
          type: "buttons",
          content: {
            title: `You are searching for ${oMemory.product.raw} for the following regions. `,
            buttons: [
              {
                value: "test1",
                title: "test2",
                type: "postback"
              },
              {
                value: "test1",
                title: "test2",
                type: "postback"
              },
              {
                value: "test1",
                title: "test2",
                type: "postback"
              },
              {
                value: "test1",
                title: "test2",
                type: "postback"
              },
              {
                value: "test1",
                title: "test2",
                type: "postback"
              }
            ]
          }
        }
      ],
      conversation: {
        memory: oMemory
      }

chatbot_display

The Code above results in the image I´ve attached.

Thanks.

Use multiple Webchats on one domain

Hi there,

In my use case it is possible to add more than one Webchat to a website, each in its own iframe.
Testing this scenario, I found that one chatbot stops responding after I open the page for the second time.
After clearing the Browser Cookies one of the chatbots is responding, while the other one doesn’t respond still.

This was tested with Chrome browser.

Do you know what causes this issue and how it can be resolved?

Thank you and Kind regards!

Add minHeight for Webchat textarea

Problem Description
Webchat textarea element doesn't have minHeight applied in its style. This causes textarea to load with irregular size on different web pages. Because it inherits the minHeight from parent. In our site, textarea size is large enough to overflow the page size.

Fix
Add minHeight (let's say 70px) to textarea style.

_react2.default.createElement('textarea', { ref: function ref(i) { return _this3._input = i; }, value: value, style: {minHeight: 70, width: '100%', maxHeight: 70, resize: 'none' }, placeholder: 'Write a reply...', onChange: function onChange(e) { return _this3.setState({ value: e.target.value }, _this3.autoGrow); }, onKeyPress: function onKeyPress(e) { if (e.key === 'Enter') { _this3.sendMessage(); e.preventDefault(); } }, rows: 1 })

Speech to text

I want to integrate speech to text functionality in my application.
Looking for help.
Thanks

Be able to run the project locally

I wanted to contribute to the project but it seems not easy.

It would be nice if npm start spawns a simple webserver serving and index.html with the webchat loaded (with a random demo token).

It would be easier to contribute to this project!

The webchat should provide some context information from the web page to the bot actions

Intro

I asked the question about this feature on the Recast community Slack group and had some feedback from Oliver Nguyen who confirmed that it was not supported. So the following is an attempt to explain the use cases and why this would be useful.

I am making those notes as an issue in the Webchat project, but I understand this may have broader implications (probably not only a webchat concern). Let me know if there is a better place to submit this issue.

Use case

I am building a bot for a client. The bot basically answers the same types of questions, with the same skills and the same “knowledge base” (through webhooks calls in the actions), for many instances of the client product. Each instance is a different website, and the instance information is important for the bot to get the right answer.

More concretely:

  • webchat is embedded on domain1.com AND domain2.com
  • when the user asks “what are your opening hours”, the answer is different depending if the user is on domain1.com or domain2.com
  • currently, the message that will be send to the bot backend (webhook type of action for that skill) does not include any information that allows to know the webchat context (domain1 or domain2)
  • so the bots needs to ask the user for their context (eg. “are you shopping on domain1 or domain2?”)

I am sure there are other similar situations. For instance, a support bot on an ecommerce site should know what product the user is asking about if he/she is on a product page.

Proposed implementations

I have no prefered implementation, as long as there is a way to know “where” / “in what context” the webchat was used, from the message that is sent to my API through the webhook actions. Here are a few ideas.

Referring URL

Simply having the URL of the page containing the webchat as a new property of the message object would work. Very simple to implement from my bot developper point of view.

channelId

I could create multiple webchat connectors, each of which have a unique channelId. Now, if the channelId information was sent as a property of the message object, that would work as well. This is a bit more tedious however, and would not really scale well for some use cases (eg. the ecommerce example above).

Custom attribute in the script tag

Just like the channelId, we could add a property to the script tag for embedding the webchat, and that info would be send in the message object (or injected in the bot memory right from the start of the conversation?). Also easy to implement from my developer perspective.

New user preference: font family

Add in the object "preferences" a font-family that will be applied for all the texts in the webchat.
The font should be a google font url, so it's simple to embed it.

Not able to install

when typing "git clone YOUR_REPO_URL"
it shows YOUR_REPO_URL
how do i correct it

How to use with React

Hi everyone!

How can I use it as a React Component??

I have cloned the repo ( https://github.com/SAPConversationalAI/Webchat ) -> npm install -> npm run build , and then.. what next? I thought I could copy the generated webchat.js file in the ‘dist’ folder into my own React app and import it as CaiWebchat from ‘webchat’, like mentioned in github and that would be it.

But I get the following error: ‘Attempted import error: ‘./webchat’ does not contain a default export (imported as ‘CaiWebchat’).'

Even if I try to call a script in the main html page but in src I point it to this webchat.js I get Unexpected token <..

Something I am not doing right.

Has anyone managed to make it work?? Can you point me in some direction?

Thanks in advance!

Embed a video

Hello,

I can't seem to embed a video in a rich message, although sending type 'video' with a url.
I'm just getting a blank section :/

image

Can I embed vimeo / youtube ?
Do I need a https://blabla.com/video.mp4 link ?

Any thoughts ?

Support clickable url

When url are displayed in a text message or other messages type (the button message type also support a little text before buttons), we should have a clickable url.

Example:
message: "Please visit our website for more information here: https://john.doe/faq"

As a user, I should be able to click on the url and open it in a new page.

import react component

Hello,

I'd like to change the Preferences like BotPicture etc. How can I manage that? where to import the React Component in the README ?

Thank you

Error: Request failed with status code 500

Hello,
I implemented a very simple Webchat with SAP CAI. After generate the connection informationg I just included into my SAPUI5 app with the following code:

`
if (!document.getElementById("cai-webchat")) {
var s = document.createElement("script");
s.setAttribute("id", "cai-webchat");
s.setAttribute("src", "https://cdn.cai.tools.sap/webchat/webchat.js");
s.setAttribute("channelId", "Channed Id Goes Here");
s.setAttribute("token", "Token Goes Here");
document.body.appendChild(s);
}

`
The icon appeared into my page but when I try to submit a message the chat shows "Couldn’t send this message" the error "Error: Request failed with status code 500" is displayed in the console.

TestChatBot - Google Chrome

Anyone has an idea of what is wrong?

Regards.

Integrating WebChat into an Angular Web App

Hi,

I am trying to integrate the WebChat interface into an existing Angular based web app.

What I did so far is, adding the script tag to the HTML body

<script
  src="YOUR_WEBCHAT_URL"
  ...
></script>

A div is being created at the end of the body

<div id="cai-webchat-div"></div>

However it is empty and hence no chat interface/button is showing up.

Any idea what I am missing here?

Regards,
Andreas

Parsing Incoming/Outgoing messages

Hello,
I'm looking for a webhook to parse incoming / outgoing messages.

  • the basic documentation works (using <script> tags)
  • the window.webchatMethods webhook works but I can't find a documentation of available methods
  • Folowing the WebClientDevGuide there is no windows.sap or windows.sapcai objects to hook with
  • Folllowing this answer of an issue in this repository the applicationParse is never called back

Is there an up to date documentation ?
Thanks

mutated redux state

Hi!

The code

fmtMessages = () => {
    return reduceRight(
      this.props.messages,
      (acc, cur) => {
        const nextMessage = acc[0]

        cur.displayIcon = !nextMessage || nextMessage.participant.isBot !== cur.participant.isBot

        acc.unshift(cur)
        return acc
      },
      [],
    )
  }

is muting redux state, which is dangerous practise. I believe it to be the source of a bug that duplicates sent messages, although I'm not sure.

this is my correction to the code:

fmtMessages = () => {
    return reduceRight(
      this.props.messages,
      (acc, cur) => {
        const nextMessage = acc[0]

        cur.displayIcon = !nextMessage || nextMessage.participant.isBot !== cur.participant.isBot

        acc.unshift(cur)
        return acc
      },
      [],
    )
  }

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.