{"id":13989718,"url":"https://github.com/ashubham/bot-context","last_synced_at":"2025-08-11T00:15:04.965Z","repository":{"id":74809834,"uuid":"85452314","full_name":"ashubham/bot-context","owner":"ashubham","description":"Easy, powerful, functional way to maintain conversational context in chat bots.","archived":false,"fork":false,"pushed_at":"2017-03-22T06:40:21.000Z","size":119,"stargazers_count":47,"open_issues_count":4,"forks_count":4,"subscribers_count":7,"default_branch":"master","last_synced_at":"2025-07-22T14:21:10.510Z","etag":null,"topics":["ai","bot-core","bots","chatbots","conversational-ui"],"latest_commit_sha":null,"homepage":"https://chatbotsmagazine.com/maintaining-context-in-chatbots-2016b6a5b7c6","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ashubham.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2017-03-19T05:05:44.000Z","updated_at":"2025-05-29T01:37:52.000Z","dependencies_parsed_at":"2023-07-16T05:16:01.810Z","dependency_job_id":null,"html_url":"https://github.com/ashubham/bot-context","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/ashubham/bot-context","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashubham%2Fbot-context","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashubham%2Fbot-context/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashubham%2Fbot-context/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashubham%2Fbot-context/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ashubham","download_url":"https://codeload.github.com/ashubham/bot-context/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ashubham%2Fbot-context/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":269809830,"owners_count":24478626,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-08-10T02:00:08.965Z","response_time":71,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","bot-core","bots","chatbots","conversational-ui"],"created_at":"2024-08-09T13:01:59.608Z","updated_at":"2025-08-11T00:15:04.921Z","avatar_url":"https://github.com/ashubham.png","language":"JavaScript","funding_links":[],"categories":["JavaScript"],"sub_categories":[],"readme":"# bot-context\n\u003ca href=\"https://travis-ci.org/ashubham/bot-context\"\u003e\n  \u003cimg src=\"https://travis-ci.org/ashubham/bot-context.svg?branch=master\" class=\"badge\"\u003e\n\u003c/a\u003e\n\u003ca href='https://coveralls.io/github/ashubham/bot-context?branch=master'\u003e\n    \u003cimg src='https://coveralls.io/repos/github/ashubham/bot-context/badge.svg?branch=master' alt='Coverage Status' /\u003e\n\u003c/a\u003e\n\u003ca href=\"https://badge.fury.io/js/bot-context\"\u003e\u003cimg src=\"https://badge.fury.io/js/bot-context.svg\" alt=\"npm version\" height=\"18\"\u003e\u003c/a\u003e\n\nA easy and powerful way to maintain conversational context in chat bots. Using function closures.\n[Blog post](https://medium.com/@ashishshubham/maintaining-context-in-chatbots-2016b6a5b7c6#.z08lc981s)\n\n## Core Concept\n\n![context stack](https://raw.githubusercontent.com/ashubham/bot-context/master/img/context-stack.png)\n\nHere we introduce a reactive approach to maintaining the context of conversations. \n\n    - Whenever the bot sends a message, set(push) a context(callback) on the stack.\n    - Whenever the bot recieves a message, match the message in FIFO order to \n      the items on the stack. And call the callback.\n\nThe elegant trick here is that when a callback is pushed on the stack, \nit captures the closure state of the callback function being pushed. \n\nSo when we match the context stack on recieving a message, the closure variables and data\nare maintained, allowing time travel!\n\n## Usage\n\n`$ npm i bot-context`\n\nThis is a very basic pizza delivery bot, to demonstrate the usage of\nbot-context.\n\n```javascript\n// The message recieving module.\nlet context = require('bot-context');\n\nfunction onMessageRecieved(message, userId) {\n  let ctx = botContext.getOrCreate(userId);\n  if(!ctx.isSet()) {\n      init(userId); // initialize the actions.\n  }\n\n  ctx.match(message, function(err, match, contextCb) {\n    if(!err) contextCb(userId, match);\n  });\n}\n```\n\nThe set of actions to send the message:\n\n```javascript\nfunction init(userId) {\n  let ctx = botContext.getOrCreate(userId);\n  ctx.set(\n      /.*/,  // The base matcher to match anything.\n      (match) =\u003e getPizzaType(userId));\n}\n\nfunction getPizzaType(userId) {\n  let ctx = botContext.getOrCreate(userId);\n  ctx.set(\n    /(chicken|cheese|veggie)/, \n    (match) =\u003e getDeliveryAddress(userId, match)\n  );\n  sendMessage(userId, \"What kind of pizza do you want ?\");\n}\n\nfunction getDeliveryAddress(userId, pizzaType) {\n  let address = userDataService.getAddress(userID);\n  let ctx = botContext.getOrCreate(userId);\n\n  if(address) {\n    ctx.set(/(yes|no)/, (reponse) =\u003e {\n        if(response === 'yes') {\n            userDataService.clearAddress(userId);\n            getDeliverAddress(userId, pizzaType);\n        } else {\n            end(userId, pizzaType, address);\n        }\n    });\n    sendMessage(userId, 'Would you like to change your address ?'); \n    return;   \n  }\n\n  ctx.set(\n    validateAddressUsingGoogleAPI, // Can use some async API method\n    (address) =\u003e end(userId, pizzaType, address)\n  ); // Note that pizzaType is now a closure variable.\n  sendMessage(userId, `Please enter the delivery Address.`); \n}\n\nfunction end(userId, pizzaType, address) {\n  sendMessage(userId, `Thank you, a ${pizzaType} pizza, will be` +\n    + `delivered to ${address} in 30 mins.`);\n} \n```\n\nNow, if a user after putting his address changes his mind to another pizza type, \nby just typing the type of the pizza.\n\n\n## Webhooks\n\nWYSIWYG bot creators are the latest hot stuff. Almost all of them allow integration with external\ntools via http `webhooks`.\n\n`bot-context` can easily be used with such bot tools. Please see the [example](https://github.com/ashubham/bot-context/blob/master/examples/webhooks.js),\non how could you setup `bot-context` as a webservice.\n\n\n## API\n\n`var contextMap = require('bot-context');`\n\nreturns an instance of the ContextMap, the following methods are available on it.\n\n-   [ContextMap](#contextmap)\n    -   [getOrCreate()](#getorcreate)\n-   [Context](#context)\n    -   [set](#set)\n    -   [isSet](#isset)\n    -   [match](#match)\n\n## ContextMap *extends Map*\n\nA map to hold contexts for all users/keys\n\n### getOrCreate(uKey: string): Context\n\nGet Or Creates a context given the key.\n\n**Parameters**\n\n-   `uKey` unique key to identify a user. **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** \n\nReturns **[Context](#context)** \n\n## Context\n\nA context uniqiue for each user. The following methods are available on the `context`.\n\n### \u003ca name=\"set\"\u003e\u003c/a\u003eset(matchRegex|matcherFn, contextCallback)\n\nSet the current context.\n\n**Parameters**\n\n-   `matchRegex|matchFn` **([RegExp](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp) | Function)** Used to match the input\n-   `contextCallback` Callback which is stored in the stack, it can hold references to closure vars.\n\n  #### matcherFn(inputText, callback)\n\n  Matcher method called when matching contexts. It is called with the following params.\n\n  **Parameters**\n\n-   `text` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** input text\n-   `callback(boolean)` **[Function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function)** Callback resolving to truthy/falsy value.\n\n  #### contextCallback\n\n  Context callback set in the context stack.\n\n###\u003ca name=\"isset\"\u003e\u003c/a\u003e isSet(): boolean\n\n  Returns, is there any context set.\n\n### \u003ca name=\"match\"\u003e\u003c/a\u003ematch(inputText: string, contextMatchedCallback)\n\n  Match an input text to the collection of currently set contexts.\n\n  **Parameters**\n\n-   `inputText` **[string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)** text\n-   `contextMatchedCallback` The callback to be called if matched.\n\n#### contextMatchedCallback\n\nCallback called when a context is matched, with the following values.\n\n**Parameters**\n\n-   `err` **([string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String) | null)** Error if any\n-   `match` **any** the match returned from the matchFn or regex\n-   `contextCallback` the callback which was previously set to the context stack.\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fashubham%2Fbot-context","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fashubham%2Fbot-context","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fashubham%2Fbot-context/lists"}