telegraf / telegraf-session-redis

Redis session middleware for Telegraf
MIT License
50 stars 25 forks source link

define a variable #5

Closed aminjoharinia closed 7 years ago

aminjoharinia commented 7 years ago

Hi there how to define a variable when program start running I mean before any bot action/hear/on/use if i use ctx.session.variablethen it says ctx is not defind thanks

dotcypress commented 7 years ago

Hey!

You can use custom middleware for that:

const Telegraf = require('telegraf')
const RedisSession = require('telegraf-session-redis')

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

const session = new RedisSession()

bot.use(session.middleware())

bot.use((ctx, next) => {
  // Init with default value
  ctx.session.counter = ctx.session.counter || 0
  return next()
})

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

bot.startPolling()
aminjoharinia commented 7 years ago

@dotcypress Thank you very much for your helps I got the idea and It Works but i find this a better solution for my situation ( i have many different types of data ) just a simple example

bot.use((ctx, next) => {
if (typeof ctx.session.quantity === 'undefined' ) {

    ctx.session.totalprice = {
      "hotdog": 0,
      "7up": 0,
      "coca": 0,
      "pizza": 0    
    }
}
.
.
.
.

anyway ,Thank you so much