npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-rasa-assistant

v0.3.0

Published

React hook for easily building custom Rasa assistants

Downloads

1,209

Readme

React Rasa Assistant

React hook for easily building custom Rasa assistants.

Install

npm i react-rasa-assistant

Usage

import useBot from 'react-rasa-assistant'

Examples

Basic:

const Assistant = () => {
    const {
        msgHistory, onInputRef, userText, setUserText, sendUserText,
        selectOption, restartSession,
    } =
        useBot({sockUrl: '<your socket url>'})

    return <>
        {msgHistory.map((msg, msgIdx) => {
            if (msg.text)
                return <div key={msg.ts + '-txt'}>
                    {{in: '< ', out: '> '}[msg.direction]}
                    {msg.text}
                </div>

            if ((msg.quick_replies || msg.buttons))
                return <div key={msg.ts + '-btngroup'}>
                    {(msg.quick_replies || msg.buttons).map((opt, optIdx) =>
                        <button
                            key={opt.payload}
                            onClick={() => selectOption(msgIdx, optIdx)}
                        >
                            {opt.title}
                        </button>
                    )}
                </div>

            // Also handle any other custom properties (if any)
        })}

        <input
            value={userText}
            onChange={e => setUserText(e.target.value)}
            ref={onInputRef}
        />
        <button onClick={sendUserText}>Send</button>

        <br /><button onClick={restartSession}>Restart</button>
    </>
}

Handle custom responses:

const Assistant = () => {
    const {
        msgHistory, onInputRef, userText, setUserText, sendUserText,
        selectOption, botUtter, restartSession,
    } =
        useBot({
            sockUrl: '<your socket url>',
            onUtter: msg => {
                if (
                    msg.direction === 'in'
                    && !msg.text
                    && !msg.quick_replies
                    && !msg.buttons
                ) {
                    console.log('This is a custom message!', msg)

                    botUtter({text: 'I just sent you a custom message!'})
                }
            },
        })

    return ...
}

API

const {
    msgHistory, onInputRef, userText, setUserText,
    sendUserText, selectOption, botUtter, restartSession,
}
    = useBot({sockUrl, sockOpts, initSessionId, initMsg, onError, onUtter})

Expected config object

  • sockUrl: Full socket URL

  • sockOpts: Advanced socket options. See here for a full reference.

  • initSessionId: An optional session id that may be used to continue a previous session.

  • initMsg: An optional text to be sent in the beginning of the conversation. Alternatively an object with the title and payload attributes is supported too; in which case the title will be shown in the conversation and the payload will be sent to the server, just like case with buttons.

  • onError(error): An optional handler that gets called each time the socket emits an error. Error object schema:

    • type: Name of the socket socket error event
    • payload: The error object exactly as emitted by the socket
  • onUtter(msg): An optional handler that is called for each message sent / received. See the details of the message object at the end of the section.

Returned object

  • msgHistory: An array of message objects. See the details of the message object at the end of the section.

  • onInputRef(el): A standard React ref callback that expects the native input element as its sole parameter. Passing the ref this way to the library allows it to handle behavior such as auto focusing and blurring. If this is not something you want, just don't use this and handle those behaviors yourself the way you want.

  • userText: The current value of the text that has not yet been sent.

  • setUserText(text): Setter method for userText above.

  • sendUserText(): Send the current userText to the assistant and empty its value.

  • selectOption(msgIdx, optIdx): Select an option provided by a message with the buttons or quick_replies property. Args:

    • msgIdx: The index of the message that this button is a part of. This is required as in the case of quick replies, the button group is removed after an option is selected.

    • optIdx: The index of the option to select in the buttons or quick_replies array.

  • botUtter(msg): Send a message from the bot, as if it was the bot talking. This is intended to be used to handle custom responses. See the details of the message object, which is the only parameter, at the end of the section.

  • restartSession(): Clear the message history and restart the session.

The message object:

  • ts: Message timestamp

  • direction: Either in (for "incoming") or out (for "outgoing")

  • text: The message text. Optional

  • buttons: A list of button objects. Optional. Button object schema:

    • title: The button title
    • payload: The button payload. Should be a valid Rasa intent.
  • quick_replies: A list of button objects. Optional Quick replies only differ from buttons with their ability of disappearing after being clicked on. Button object schema:

    • title: The button title
    • payload: The button payload. Should be a valid Rasa intent.
  • metadata: Potential metadata as sent by Rasa. Optional

In case of a custom response, custom properties matching the ones in the custom response will exist as well.

Gotchas

In React Native the transports socket option needs to be explicitly provided with the value ['websocket']:

useBot({
    sockUrl: '<your socket url>',
    sockOpts: {transports: ['websocket']},
    ...
}))

The reason for this is that the default value for that option is ['polling', 'websocket'] but polling isn't supported on React Native. The Socket.io client doesn't automatically switch to Websocket connection if polling is failing, so this must be explicitly configured.

Pics or it didn't happen

Visuals of an ugly assistant made with this hook:

assistant screenshot 1 assistant screenshot 2