How to manage state and scenes#
Installation#
Before you begin, you need to install the library and initiate the bot; this process is described in detail here: How to import the library and initiate your bot.
How to manage user state#
By default, this library stores state in a key-value map. The key can be any string, any object can be the value. The state identifier is a combination of the chat identifier and the sender identifier, that is, each combination of chatId + senderId will have a separate state.
As an example, a simple bot was created to simulate user registration. To save a string in state, use the construction ctx.session.{var_name} = "string example"
.
Link to example: state-bot.js.
const WhatsAppBot = require('@green-api/whatsapp-bot')
const session = WhatsAppBot.session
const Stage = WhatsAppBot.Stage
const Scene = WhatsAppBot.BaseScene
const bot = new WhatsAppBot({
idInstance: "{{INSTANCE_ID}}",
apiTokenInstance: "{{TOKEN}}",
})
const loginScene = new Scene("loginScene")
loginScene.enter((ctx) => ctx.reply("Hi! This bot is an example of using state.\nPlease enter your login:"))
loginScene.on("text", (ctx) => {
const login = ctx.message.text
if (login && login.length >= 6 && login.length <= 12) {
ctx.session.login = login
ctx.reply("Login \"" + login + "\" - successfully saved.\nCreate a password:")
ctx.scene.enter("passwordScene")
} else {
ctx.reply("Login must be from 6 to 12 characters")
}
})
loginScene.on("message", (ctx) => {
ctx.reply("Message must contain text!")
})
const passwordScene = new Scene("passwordScene")
passwordScene.on("text", (ctx) => {
const password = ctx.message.text
if (password && password.length >= 6 && password.length <= 12) {
ctx.session.password = password
ctx.reply("Success! Your login: " + ctx.session.login + "\nYour password: " + ctx.session.password)
ctx.scene.leave()
} else {
ctx.reply("Password must be between 6 and 12 characters")
}
})
const stage = new Stage([loginScene, passwordScene]) //registration of scenes
bot.use(session()) //initiating a session handler
bot.use(stage.middleware()) //initiating the scene handler
bot.on('message', (ctx) => ctx.scene.enter('loginScene')) //activate the first scene
bot.launch() //launch the bot
List of examples#
Description | Link to example |
---|---|
How to initialize a handler | hello-bot.js |
Scene "Echo" | echo-bot.js |
How to filter by notification type | media-bot.js |
How to filter by message text | filter-bot.js |
How to work with bot state | state-bot.js |
Example of a ready-made chat bot | demo-bot |