telegraf-mysql-session
v1.0.0
Published
MySQL powered session middleware for Telegraf
Downloads
18
Maintainers
Readme
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 serveruser
: usernamepassword
: user passworddatabase
: Database nameproperty
: 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
})