VK-IO Scenes - Simple implementation of middleware-based scene management 🎬
Node.js 12.20.0 or newer is required
- Using
Yarn
(recommended)yarn add @vk-io/scenes
- Using
npm
npm i @vk-io/scenes
- Using
pnpm
pnpm add @vk-io/scenes
import { VK } from 'vk-io';
// Session implementation can be any
import { SessionManager } from '@vk-io/session';
import { SceneManager, StepScene } from '@vk-io/scenes';
const vk = new VK({
token: process.env.TOKEN
});
const sessionManager = new SessionManager();
const sceneManager = new SceneManager();
vk.updates.on('message_new', sessionManager.middleware);
vk.updates.on('message_new', sceneManager.middleware);
vk.updates.on('message_new', sceneManager.middlewareIntercept); // Default scene entry handler
vk.updates.on('message_new', (context, next) => {
if (context.text === '/signup') {
return context.scene.enter('signup');
}
return next();
});
sceneManager.addScenes([
new StepScene('signup', [
(context) => {
if (context.scene.step.firstTime || !context.text) {
return context.send('What\'s your name?');
}
context.scene.state.firstName = context.text;
return context.scene.step.next();
},
(context) => {
if (context.scene.step.firstTime || !context.text) {
return context.send('How old are you?');
}
context.scene.state.age = Number(context.text);
return context.scene.step.next();
},
async (context) => {
const { firstName, age } = context.scene.state;
await context.send(`👤 ${firstName} ${age} ages`);
return context.scene.step.next(); // Automatic exit, since this is the last scene
}
])
]);
vk.updates.start().catch(console.error);