Skip to content

Instantly share code, notes, and snippets.

@RealPeha
Created September 16, 2021 14:26
Show Gist options
  • Save RealPeha/535a412234645142cb2b5379eabfca70 to your computer and use it in GitHub Desktop.
Save RealPeha/535a412234645142cb2b5379eabfca70 to your computer and use it in GitHub Desktop.
const { session, Stage } = require('telegraf')
const sceneSessionKey = 'sceneSession'
const scene = /* new Scene() */;
const stage = new Stage([scene], { sessionName: sceneSessionKey })
const emptySessionScene = {
session: { __scenes: {} },
expires: null
}
const sceneSessionConfig = {
property: sceneSessionKey,
getSessionKey: ({ from }) => from.id,
store: {
get: async (id) => {
// тут получает сессию из бд
const result = await SceneSession.findByTgPlayerId(id);
try {
return JSON.parse(result?.session)
} catch {
return emptySessionScene
}
},
set: (id, session) => {
// тут сохраняем сессию в бд
return SceneSession.upsert(id, JSON.stringify(session))
}
},
}
bot.use(session()) // обычная сессия, хранился в памяти, доступна как ctx.session
bot.use(session(sceneSessionConfig)) // сессия, которая хранится в бд, используется внтутри сцен, при чем состояние сцен (ctx.scene.state) также хранится в бд
bot.use(stage)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment