fb-bot-kit-session
v1.0.3
Published
MySQL session for fb-bot-kit
Downloads
3
Maintainers
Readme
MySQL session for fb-bot-kit
MySQL powered session for fb-bot-kit. forked from telegraf-session-mysql. Saves session both on mysql and in memory and use memory where possible.
Installation
$ npm install fb-bot-kit-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 Session = require('fb-bot-kit-session')
const mysqlSession = new Session({
host: 'localhost',
user: 'user',
password: 'pass',
database: 'session_db'
});
handleFacebookData(data) {
data.entry.forEach((entry) => {
entry.messaging.forEach(async(event) => {
await mysqlSession.init(event)
...
});
});
}
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 Session()
// 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
.
bot.on('text', (ctx) => {
ctx.session = null
})