Skip to content

FrozDark/telegraf-session-mysql

 
 

Repository files navigation

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-session-mysql

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-session-mysql')

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
})

About

MySQL session middleware for Telegraf

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • JavaScript 95.8%
  • Shell 4.2%