Telegraf session for unique user?

Viewed 5316

I'm building a wallet bot and I was wondering how can I initiate a session for an unique user. For example, in this session I would need an object containing the unique user identifier, the public key and secret key so they can access this after initiating the bot.

I was thinking in something like this:

var myWallet = (ctx) =>{
return{
  user: ctx.from.id,
  publicKey: wallet.public,
  secretKey: wallet.secret

}
}

bot.command('/myWallet', (ctx)=>{
   ctx.reply(myWallet.user);
   ctx.reply(myWallet.publicKey);
   ctx.reply(myWallet.secretKey);
})

But when I type /myWallet on my bot nothing happens, any idea what am I doing wrong?

1 Answers

Might be a bit late but for sessions you can use Telegrafs inbuild session management. Here an example:

const session = require('telegraf/session')

const bot = new Telegraf(process.env.BOT_TOKEN)
bot.use(session())
bot.on('text', (ctx) => {
    ctx.session.counter = ctx.session.counter || 0
    ctx.session.counter++
    return ctx.reply(`Message counter:${ctx.session.counter}`)
})

Basically it just works like above example. You intitiate a session (bot.use(session());) then when a user writes you use the context of the returned message (ctx) in which all user data is stored (username, id, message, etc) and calling the session from that (ctx.session). In there you store your regular variable data. Now normal sesions are active until the bot shuts down. When you want persistent sessions just import an 3rd-party session manager as written in the docs.

So to sum that up:

const session = require('telegraf/session') // import session addon
ctx.session.walletData = 'some data' // store data in session
console.log(ctx.session.walletData) // show data
Related