Skip to content

Latest commit

 

History

History
 
 

scenes

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 

VK-IO Scenes

NPM version Build Status NPM downloads Code quality

VK-IO Scenes - Simple implementation of middleware-based scene management 🎬

Installation

Node.js 8.0.0 or newer is required

Yarn

Recommended

yarn add @vk-io/scenes

NPM

npm i @vk-io/scenes

Example usage

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();

sceneManager.addScene(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`);

		await context.scene.leave();
	}
]));

vk.updates.on('message', sessionManager.middleware);
vk.updates.on('message', sceneManager.middleware);

// Custom handler scene and global exit from the scene using the button
vk.updates.on('message', (context, next) => {
	if (!context.scene.current) {
		return next();
	}

	const cancel =  context.messagePayload && context.messagePayload.command === 'cancel';

	if (cancel) {
		return context.scene.leave({
			canceled: true
		});
	}

	return context.scene.reenter();
});

// Or default handler
// vk.updates.on('message', sceneManager.middlewareIntercept);

vk.updates.hear('/signup', (context) => {
	return context.scene.enter('signup');
});

vk.updates.start().catch(console.error);