telegraf / telegraf-session-firebase

Firebase session for Telegraf
MIT License
14 stars 4 forks source link

Build Status NPM Version js-standard-style

Firebase session for Telegraf

Firebase powered session middleware for Telegraf.

Installation

$ npm install telegraf-session-firebase

Example

const Telegraf = require('telegraf')
const firebaseSession = require('telegraf-session-firebase')
const admin = require('firebase-admin')

const serviceAccount = require('path/to/serviceAccountKey.json')
admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: 'https://<DATABASE_NAME>.firebaseio.com'
})
const database = admin.database()

const bot = new Telegraf(process.env.BOT_TOKEN)
bot.use(firebaseSession(database.ref('sessions')))
bot.on('text', (ctx, next) => {
  ctx.session.counter = ctx.session.counter || 0
  ctx.session.counter++
  return next()
})
bot.hears('/stats', ({ reply, session, from }) => reply(`${session.counter} messages from ${from.username}`))
bot.startPolling()

API

Options

Default implementation of getSessionKey:

function getSessionKey(ctx) {
  if (!ctx.from || !ctx.chat) {
    return
  }
  return `${ctx.from.id}/${ctx.chat.id}`
}

Destroying a session

To destroy a session simply set it to null.

bot.on('text', (ctx) => {
  ctx.session = null
})