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

bot-context

v0.2.6

Published

Maintain conversation context in your chatbots, its easy and powerful.

Downloads

20

Readme

bot-context

A easy and powerful way to maintain conversational context in chat bots. Using function closures. Blog post

Core Concept

context stack

Here we introduce a reactive approach to maintaining the context of conversations.

- Whenever the bot sends a message, set(push) a context(callback) on the stack.
- Whenever the bot recieves a message, match the message in FIFO order to 
  the items on the stack. And call the callback.

The elegant trick here is that when a callback is pushed on the stack, it captures the closure state of the callback function being pushed.

So when we match the context stack on recieving a message, the closure variables and data are maintained, allowing time travel!

Usage

$ npm i bot-context

This is a very basic pizza delivery bot, to demonstrate the usage of bot-context.

// The message recieving module.
let context = require('bot-context');

function onMessageRecieved(message, userId) {
  let ctx = botContext.getOrCreate(userId);
  if(!ctx.isSet()) {
      init(userId); // initialize the actions.
  }

  ctx.match(message, function(err, match, contextCb) {
    if(!err) contextCb(userId, match);
  });
}

The set of actions to send the message:

function init(userId) {
  let ctx = botContext.getOrCreate(userId);
  ctx.set(
      /.*/,  // The base matcher to match anything.
      (match) => getPizzaType(userId));
}

function getPizzaType(userId) {
  let ctx = botContext.getOrCreate(userId);
  ctx.set(
    /(chicken|cheese|veggie)/, 
    (match) => getDeliveryAddress(userId, match)
  );
  sendMessage(userId, "What kind of pizza do you want ?");
}

function getDeliveryAddress(userId, pizzaType) {
  let address = userDataService.getAddress(userID);
  let ctx = botContext.getOrCreate(userId);

  if(address) {
    ctx.set(/(yes|no)/, (reponse) => {
        if(response === 'yes') {
            userDataService.clearAddress(userId);
            getDeliverAddress(userId, pizzaType);
        } else {
            end(userId, pizzaType, address);
        }
    });
    sendMessage(userId, 'Would you like to change your address ?'); 
    return;   
  }

  ctx.set(
    validateAddressUsingGoogleAPI, // Can use some async API method
    (address) => end(userId, pizzaType, address)
  ); // Note that pizzaType is now a closure variable.
  sendMessage(userId, `Please enter the delivery Address.`); 
}

function end(userId, pizzaType, address) {
  sendMessage(userId, `Thank you, a ${pizzaType} pizza, will be` +
    + `delivered to ${address} in 30 mins.`);
} 

Now, if a user after putting his address changes his mind to another pizza type, by just typing the type of the pizza.

Webhooks

WYSIWYG bot creators are the latest hot stuff. Almost all of them allow integration with external tools via http webhooks.

bot-context can easily be used with such bot tools. Please see the example, on how could you setup bot-context as a webservice.

API

var contextMap = require('bot-context');

returns an instance of the ContextMap, the following methods are available on it.

ContextMap extends Map

A map to hold contexts for all users/keys

getOrCreate(uKey: string): Context

Get Or Creates a context given the key.

Parameters

  • uKey unique key to identify a user. string

Returns Context

Context

A context uniqiue for each user. The following methods are available on the context.

set(matchRegex|matcherFn, contextCallback)

Set the current context.

Parameters

  • matchRegex|matchFn (RegExp | Function) Used to match the input
  • contextCallback Callback which is stored in the stack, it can hold references to closure vars.

matcherFn(inputText, callback)

Matcher method called when matching contexts. It is called with the following params.

Parameters

  • text string input text
  • callback(boolean) Function Callback resolving to truthy/falsy value.

contextCallback

Context callback set in the context stack.

### isSet(): boolean

Returns, is there any context set.

match(inputText: string, contextMatchedCallback)

Match an input text to the collection of currently set contexts.

Parameters

  • inputText string text
  • contextMatchedCallback The callback to be called if matched.

contextMatchedCallback

Callback called when a context is matched, with the following values.

Parameters

  • err (string | null) Error if any
  • match any the match returned from the matchFn or regex
  • contextCallback the callback which was previously set to the context stack.