context-chatbot v1.0.2
Context For Chat Bot
Simplify your code for chatbot without headache.
⚠️Breaking change⚠️
version 0.1.7 and above no longer use context variable, if you want update version from 0.1.6 and below, please check variable naming
Installation
Copy this code to your command line.
npm i context-chatbotand add this code to your project.
import { Ctx } from "context-chatbot";Quick Start
- first, register context to module.
Ctx.registerContext('welcome', (id, payload)=>{
console.log('hello ' + id)
console.log(payload)
})or register from array.
Ctx.registerArrayContext([
{
state: 'welcome',
callback: (id, payload)=>{
console.log('welcome' + id)
console.log(payload)
}
}
])- then, set state for id (person/number/etc).
Ctx.setState('6281955551111', 'welcome')- finally, put this line code to your bot file.
Ctx.Context('6281955551111', 'this is payload')
// output:
// 'welcome 6281955551111'
// 'this is payload'Context with timer
This function allow you to restricted response from user (time out), if the time is up, then the state will change to the desired state
Ctx.registerArrayContext([
{
state: 'welcome',
callback: (id, payload, timeOut)=>{
console.log('welcome' + id)
console.log(payload)
//Dont forget to clear timeout
clearTimeOut(timeOut)
}
}
])//if there is no input for 5 seconds, state will change from 'welcome' to 'base'
Ctx.setState(id, "welcome", 5000, "base");Using middleware
if you dont know where to place setState function to change state, maybe this can help you
Ctx.setMiddleware((id, payload, next) => {
if (payload.message.includes("!login")) {
Ctx.setState(id, "login_ask_username");
}
next();
});API
Ctx.registerContext(state, callback)
Create a context with named state
state: stringcallback: Functionid: stringpayload: anytimeOut: optionalsetTimeOut function for Ctx with timer
Ctx.registerArrayContext(arr)
Create a context from array of object
arr: Array of objectstate: stringcallback: Functionid: stringpayload: anytimeOut: optionalsetTimeOut function for context with timer
Ctx.setState(id, state)
change the state of an id
id: stringstate: stringtimer: miliseconds number (Optional)set time out context responsebackTo: string (Optional)go to target state if timer is timeout
Ctx.Context(id, payload)
determine context of an id (if state id not found, 'base' status will be added automatically. Make sure to add 'base' context first, but you can change the default state, check API below)
id: stringstate: any
Ctx.setDefaultState(state)
set default state if state of id not found
state: string
Ctx.setMiddleware(midFunc)
set middleware before enter the context
midFunc: Functionid: stringpayload: anynext: Function
@adiwajshing/baileys implementation
coming soon~