Middleware for locally stored sessions & database
⚡️ Features
-
Any type of storage: Memory
, FileSync
, FileAsync
, ... (implement your own)
-
Any format you want: JSON
, BSON
, YAML
, XML
, ... (implement your own)
-
Shipped together with power of lodash
-
Supports basic DB-like operations (thanks to lodash-id):
getById
, insert
, upsert
, updateById
, updateWhere
, replaceById
, removeById
, removeWhere
, createId
,
🚀 Installation
$ npm install -S telegraf-session-local
💡 TIP: We recommend pnpm
package manager: npm i -g pnpm
and then pnpm i -S telegraf-session-local
.
It's in-place replacement for npm
, faster and better than npm
/yarn
, and saves your disk space.
👀 Quick-start example
const { Telegraf } = require('telegraf')
const LocalSession = require('telegraf-session-local')
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.use((new LocalSession({ database: 'example_db.json' })).middleware())
bot.on('text', (ctx, next) => {
ctx.session.counter = ctx.session.counter || 0
ctx.session.counter++
ctx.replyWithMarkdownV2(`Counter updated, new value: \`${ctx.session.counter}\``)
return next()
})
bot.command('/stats', (ctx) => {
ctx.replyWithMarkdownV2(`Database has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`)
})
bot.command('/remove', (ctx) => {
ctx.replyWithMarkdownV2(`Removing session from database: \`${JSON.stringify(ctx.session)}\``)
ctx.session = null
})
bot.launch()
📄 Full example
const { Telegraf } = require('telegraf')
const LocalSession = require('telegraf-session-local')
const bot = new Telegraf(process.env.BOT_TOKEN)
const localSession = new LocalSession({
database: 'example_db.json',
property: 'session',
storage: LocalSession.storageFileAsync,
format: {
serialize: (obj) => JSON.stringify(obj, null, 2),
deserialize: (str) => JSON.parse(str),
},
state: { messages: [] }
})
localSession.DB.then(DB => {
console.log('Current LocalSession DB:', DB.value())
})
bot.use(localSession.middleware())
bot.on('text', (ctx, next) => {
ctx.session.counter = ctx.session.counter || 0
ctx.session.counter++
ctx.replyWithMarkdownV2(`Counter updated, new value: \`${ctx.session.counter}\``)
ctx.sessionDB.get('messages').push([ctx.message]).write()
return next()
})
bot.command('/stats', (ctx) => {
ctx.replyWithMarkdownV2(`Session has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`)
})
bot.command('/remove', (ctx) => {
ctx.replyWithMarkdownV2(`Removing session from lowdb database: \`${JSON.stringify(ctx.session)}\``)
ctx.session = null
})
bot.launch()
Another examples located in /examples
folder (PRs welcome)
Also, you may read comments in /lib/session.js
Tema Smirnov and contributors / github.tema@smirnov.one /