telegraf-mysql-session

1.0.0 • Public • Published

Build Status NPM Version js-standard-style

MySQL session middleware for Telegraf

MySQL powered session middleware for Telegraf. forked from Redis session project for telegraf. Saves session both on mysql and in memory and use memory where possible.

Installation

$ npm install telegraf-mysql-session

Setup

you should create a table named sessions in your database.

CREATE TABLE `sessions` (
  `id` varchar(100) NOT NULL,
  `session` longtext NOT NULL,
  PRIMARY KEY (`id`))

Example

const Telegraf = require('telegraf')
const MySQLSession = require('telegraf-mysql-session')

const telegraf = new Telegraf(process.env.BOT_TOKEN)

const session = new MySQLSession({
  host: 'localhost',
  user: 'user',
  password: 'pass',
  database: 'telegraf_sessions'
})

telegraf.use(session.middleware())

telegraf.on('text', (ctx) => {
  ctx.session.counter = ctx.session.counter || 0
  ctx.session.counter++
  console.log('Session', ctx.session)
})

telegraf.startPolling()

When you have stored the session key beforehand, you can access a session without having access to a context object. This is useful when you perform OAUTH or something similar, when a REDIRECT_URI is called on your bot server.

const mysqlSession = new MySQLSession()

// Retrieve session state by session key
mysqlSession.getSession(key)
  .then((session) => {
    console.log('Session state', session)
  })

// Save session state
mysqlSession.saveSession(key, session)

API

Options

  • host: hostname of mysql server
  • user: username
  • password: user password
  • database: Database name
  • property: context property name (default: session)
  • getSessionKey: session key function (ctx) => any)

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.

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

Package Sidebar

Install

npm i telegraf-mysql-session

Weekly Downloads

3

Version

1.0.0

License

MIT

Unpacked Size

6.75 kB

Total Files

4

Last publish

Collaborators

  • jamol_tokhtaev