simple implementation of middleware-based scene management for puregram package
@puregram/scenes helps you to organize step-by-step handler by providing you needed classes and methods
const { Telegram } = require('puregram')
// @puregram/scenes requires @puregram/session
const { session } = require('@puregram/session')
const { SceneManager, StepScene } = require('@puregram/scenes')
const telegram = Telegram.fromToken(process.env.TOKEN)
const sceneManager = new SceneManager()
telegram.updates.on('message', session())
telegram.updates.on('message', sceneManager.middleware)
telegram.updates.on('message', sceneManager.middlewareIntercept) // default scene entry handler
telegram.updates.on('message', (context) => {
if (/^\/signup$/i.test(context.text)) {
return context.scene.enter('signup')
}
})
sceneManager.addScenes([
new StepScene('signup', [
(context) => {
if (context.scene.step.firstTime || !context.hasText()) {
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.hasText()) {
return context.send('how old are you?')
}
context.scene.state.age = Number.parseInt(context.text, 10)
return context.scene.step.next()
},
async (context) => {
const { firstName, age } = context.scene.state
await context.send(`you are ${firstName} ${age} years old!`)
// automatic exit since this is the last scene
return context.scene.step.next()
}
])
])
telegram.updates.startPolling()$ yarn add @puregram/scenes
$ npm i -S @puregram/scenesyou can tell @puregram/scenes about actual context type by providing it in the StepScene<T>:
import { CallbackQueryContext } from 'puregram'
new StepScene<CallbackQueryContext>('foo', [])also, you can change context type on the fly simply by providing new type to the context variable:
import { CallbackQueryContext, MessageContext } from 'puregram'
new StepScene('bar', [
(context: CallbackQueryContext) => {},
(context: MessageContext) => {}
])returns: SceneInterface | undefined
returns current scene step
returns: Promise<void>
enters to another scene by slug
context.scene.enter('signup')returns: Promise<void>
leaves from current scene
context.scene.leave()returns: Promise<void>
reenters into current scene
context.scene.reenter()returns: void
resets current scene (deletes it)
returns: boolean
returns true if this entry is the first entry in this scene
if (context.scene.step.firstTime) { /* ... */ }returns: number
returns current step ID
returns: StepSceneHandler | undefined
returns current step handler
returns: Promise<void>
reenters into current step handler
if (value.invalid) {
return context.scene.step.reenter()
}returns: Promise<void>
goes to a specific step by stepId
context.scene.step.go(0)returns: Promise<void>
goes to the next step
context.scene.step.next()returns: Promise<void>
goes to the previous step
context.scene.step.previous()