# rasa-webchat-josh

> Chat web widget for React apps and Rasa Core chatbots; created from rasa webchat

Latest version **0.0.9** (published 2018-12-20) · MIT license · 0 weekly downloads

## Install

```sh
npm install rasa-webchat-josh
pnpm add rasa-webchat-josh
yarn add rasa-webchat-josh
bun add rasa-webchat-josh
```

## Health

**Score 15/100 (F)** — status: abandoned.

Positive: no vulnerabilities.

Warnings: low downloads; no types; no esm support; pre 1.0.

Negative: abandoned; low maintenance score.

## Facts

| | |
|---|---|
| Version | 0.0.9 |
| Published | 2018-12-20 |
| First published | 2018-12-18 |
| Weekly downloads | 0 |
| License | MIT |
| TypeScript types | none |
| Module format | CommonJS |
| Dependencies | 15 |
| Unpacked size | 465.9 KB |
| Known vulnerabilities | 0 (+2 in 2 direct dependencies) |
| Install scripts | no |
| GitHub stars | 0 |
| Author | Joshua |
| Maintainers | joshuapro14 |
| Keywords | react, chat, widget, javascript |

## Links

- npm: https://www.npmjs.com/package/rasa-webchat-josh
- Repository: git@https://github.com/joshuapro14/rasa-webchat
- npm.io page: https://npm.io/package/rasa-webchat-josh

## Dependencies (15)

- [redux](https://npm.io/package/redux.md) ^3.7.2
- [uniqueid](https://npm.io/package/uniqueid.md) ^1.0.0
- [immutable](https://npm.io/package/immutable.md) ^3.8.2
- [node-sass](https://npm.io/package/node-sass.md) ^4.9.3
- [react-dom](https://npm.io/package/react-dom.md) ^15.6.2
- [socket.io](https://npm.io/package/socket.io.md) ^2.1.1
- [prop-types](https://npm.io/package/prop-types.md) ^15.6.2
- [html-loader](https://npm.io/package/html-loader.md) ^0.5.5
- [react-redux](https://npm.io/package/react-redux.md) ^5.0.6
- [har-validator](https://npm.io/package/har-validator.md) ^5.1.3
- [react-markdown](https://npm.io/package/react-markdown.md) ^4.0.3
- [html-webpack-plugin](https://npm.io/package/html-webpack-plugin.md) ^3.2.0
- [react-event-observer](https://npm.io/package/react-event-observer.md) ^0.5.11
- [html-webpack-template](https://npm.io/package/html-webpack-template.md) ^6.2.0
- [react-immutable-proptypes](https://npm.io/package/react-immutable-proptypes.md) ^2.1.0

## Alternatives

- [mobx-react](https://npm.io/package/mobx-react.md) — 2.8M weekly downloads
- [rc-tree](https://npm.io/package/rc-tree.md) — 2.6M weekly downloads
- [@react-oauth/google](https://npm.io/package/@react-oauth/google.md) — 1.3M weekly downloads
- [@wagmi/connectors](https://npm.io/package/@wagmi/connectors.md) — 877.0K weekly downloads
- [vee-validate](https://npm.io/package/vee-validate.md) — 836.4K weekly downloads

## Recent versions

- 0.0.9 (latest) — 2018-12-20
- 0.0.7 — 2018-12-20
- 0.0.6 — 2018-12-20
- 0.0.5 — 2018-12-19
- 0.0.4 — 2018-12-18
- 0.0.3 — 2018-12-18
- 0.0.2 — 2018-12-18
- 0.0.1 — 2018-12-18

## README

# webchat

A simple webchat widget to connect with a chatbot. Forked from [react-chat-widget](https://github.com/Wolox/react-chat-widget)
Further forked from [rasa-webchat](https://github.com/mrbot-ai/rasa-webchat)
## Features

- Text Messages
- Quick Replies
- Images and Videos
- Snippet style for links (only as responses for now)
- Markdown support
- Easy to import in a script tag or as a React Component
- Persistent sessions
- Event Observer

![demonstration](./assets/chat-demonstration.gif)

## Setup

### In a `<script> tag

In your `<body/>`:
```javascript
<div id="webchat"/>
<script src="https://storage.googleapis.com/mrbot-cdn/webchat-0.5.0.js"></script>
<script>
  WebChat.default.init({
    selector: "#webchat",
    initPayload: "/get_started",
    interval: 1000, // 1000 ms between each message
    customData: {"userId": "123"}, // arbitrary custom data. Stay minimal as this will be added to the socket
    socketUrl: "http://localhost:5500",
    socketPath: "/socket.io/",
    title: "Title",
    subtitle: "Subtitle",
    inputTextFieldHint: "Type a message...",
    connectingText: "Waiting for server...",
    fullScreenMode: false,
    profileAvatar: "http://to.avat.ar",
    openLauncherImage: 'myCustomOpenImage.png',
    closeLauncherImage: 'myCustomCloseImage.png',
    params: {
      images: {
        dims: {
          width: 300,
          height: 200,
        }
      },
      storage: "local"
    }
  })
</script>
```

About images: `width` and `height` define the size in pixels that images in messages are crop-scaled to. If not present, the image will scale to the maximum width of the container and the image.

It is recommended to use a particular version (i.e. "webchat-<version>.js") however the file "webchat-latest.js"
is also available and is updated continuously with the latest version.

### As a React component

Install the package from GitHub by running:
```bash
npm install --save rasa-webchat-josh
npm install --save react-event-observer
```

Then once it is installed it can be implemented as follows.

```javascript
import React, { Component } from 'react';
import ReactObserver from 'react-event-observer';
import {
  Widget,
  BOT_MESSAGE_RECEIVED,
  CHAT_OPENED,
  CHAT_CLOSED
} from 'rasa-webchat-josh';

class CustomWidget extends Component {

  constructor(props){
    super(props);
    this.observer = ReactObserver();
    this.initializeListeners();
  }

  //Event listener
  initializeListeners(){
    this.msgAddListener = this.observer.subscribe(BOT_MESSAGE_RECEIVED,(data) =>{
      console.log("Message added **; size "+data);
    });
    this.chatOpened = this.observer.subscribe(CHAT_OPENED,(data) =>{
      console.log("Chat opened; isChatOpen "+data);
    });
    this.chatClosed = this.observer.subscribe(CHAT_CLOSED,(data) =>{
      console.log("Chat closed; isChatOpen "+data);
    });    
  }

  render(){
    return(
      <div>
      <Widget
        interval={2000}
        initPayload={"/get_started"}
        socketUrl={"http://localhost:5500"}
        socketPath={"/socket.io/"}
        title={"Title"}
        inputTextFieldHint={"Type a message..."}
        connectingText={"Waiting for server..."}
        embedded={true}
        openLauncherImage="myCustomOpenImage.png"
        closeLauncherImage="myCustomCloseImage.png"
        observer={this.observer}
        params={{
          images: {
            dims: {
              width: 300,
              height: 200
            }
          },
          storage: "local"
        }}
      />
      </div>
    )
  }
}

```

- Make sure to have the prop `embedded`
set to `true` if you don't want to see the launcher.

### Backend

#### Rasa Core

Use the SocketIOInput channel: See [instructions in the Rasa Core documentation](https://rasa.com/docs/core/connectors/#socketio-connector)

#### Others
Your backend must expose a socket with [socket.io](http://socket.io)

##### Receiving messages from the chat

```python
@socketio.on('user_uttered')
    def handle_message(message):
        # do something
```

##### Sending messages from the backend to the chat widget

###### sending plain text

```python
emit('bot_uttered', {"text": "hello"}, room=session_id)
```

###### sending quick replies

```python
message = {
  "text": "Happy?",
  "quick_replies":[
    {"title":"Yes", "payload":"/affirm"},
    {"title":"No", "payload":"/deny"}
  ]}
emit('bot_uttered', message, room=socket_id)
```

###### sending a link Snippet

Admittedly a bit far fetched, thinking that Snippets would evolve to carousels
of generic templates :)

```python
message = {
  "attachment":{
    "type":"template",
    "payload":{
      "template_type":"generic",
      "elements":[
        {
          "title":"Title",
          "buttons":[ {
            "title":"Link name",
            "url": "http://link.url"
          }
        ]
      }
    ]
  }
}
}
emit('bot_uttered', message, room=socket_id)
```

###### sending a Video Message

```python
message = {
  "attachment":{
    "type":"video",
    "payload":{
      "title":"Link name",
      "src": "https://www.youtube.com/watch?v=f3EbDbm8XqY"
    }
  }
}
emit('bot_uttered', message, room=socket_id)
```

###### sending an Image Message

```python
message = {
      "attachment":{
        "type":"image",
        "payload":{
          "title":"Link name",
          "src": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcT_IX5FSDQLrwm9qvuXu_g7R9t_-3yBSycZ8OxpRXvMDaTAeBEW"
        }
      }
    }
emit('bot_uttered', message, room=socket_id)
```


## Usage

### Session Persistence

`storage` specifies the location where the the conversation and state of the WebChat is stored in the browser's storage.

`storage: "session"` defines the state to be stored in the session storage. The session storage persists on reload of the page, and is cleared after the browser or tab is closed, or when `sessionStorage.clear()`is called.

`storage: "local"` defines the state to be stored in the local stoage. The local storage persists after the the browser is closed, and is cleared when the cookies of the browser are cleared, or when `localStorage.clear()`is called.



## API

| Method                  |  Description                                                                                                       |
|-------------------------|--------------------------------------------------------------------------------------------------------------------|
| WebChat.toggle()        | Toggle the open/close state of the chat window, send initPayload if webchat is not initialized and is toggled open |
| WebChat.open()          | Open the chat window, send initPayload if webchat is not initialized                                               |
| WebChat.close()         | Close the chat window                                                                                              |
| WebChat.isOpen()     | Get the open/closed state of the widget                                                                               |
| WebChat.show()          | Show the chat widget, send initPayload if the chat is in open state and not initialized                            |
| WebChat.hide()          | Hide the chat widget                                                                                               |
| WebChat.isVisible()     | Get the shown/hidden state of the widget                                                                           |



## Styles

hierarchy:
```
.conversation-container
  |-- .header
        |-- .title
        |-- .close-function
        |-- .loading
  |-- .messages-container
        |-- .message
              |-- .client
              |-- .response
        |-- .replies
              |-- .reply
              |-- .response
        |-- .snippet
              |-- .snippet-title
              |-- .snippet-details
              |-- .link
        |-- .imageFrame
        |-- .videoFrame
  |-- .sender
        |-- .new-message
        |-- .send
```

| Class                   |  Description                                                        |
|-------------------------|---------------------------------------------------------------------|
| .widget-container       | The div containing the chatbox of the default version               |
| .widget-embedded        | div of the embedded chatbox (using embedded prop)                   |
| .full-screen            | div of the fullscreen chatbox (using fullScreenMode prop)           |
| .conversation-container | the parent div containing the header, message-container and sender  |
| .messages-container     | the central area where the messages appear                          |
| .sender                 | div of the bottom area which prompts user input                     |
| .new-message            | the text input element of sender                                    |
| .send                   | the send icon element of sender                                     |
| .header                 | div of the top area with the chatbox header                         |
| .title                  | the title element of the header                                     |
| .close-button           | the close icon of the header                                        |
| .loading                | the loading status element of the header                            |
| .message                | the boxes holding the messages of client and response               |
| .replies                | the area that gives quick reply options                             |
| .snippet                | a component for describing links                                    |
| .imageFrame             | a container for sending images                                      |
| .videoFrame             | a container for sending video                                       |

## Usage with Docker

Since you have to install the package from GitHub, npm will clone the repo to the global .npm directory before
building the module in your node_modules directory. For this reason docker will have trouble installing the package,
of course the global .npm directory doesn't exist in the container. To solve this simply add the following line
in your Dockerfile before the `RUN npm install` command

```docker
RUN mkdir -p /root/.npm
```


## Contributors
[@PHLF](https://github.com/phlf)
[@znat](https://github.com/znat)
[@TheoTomalty](https://github.com/TheoTomalty)
[@Hub4IT](https://github.com/Hub4IT)
[@dliuproduction](https://github.com/dliuproduction)

---
_Source: https://npm.io/package/rasa-webchat-josh · Machine-readable twin of the npm.io package page. Health data is recomputed on every publish._
