skip to Main Content

I am developing telegram bot using grammy. I use two sessions in my bot: one with external storage, one with memory storage (for conversations).

bot.use(session({
    profile : {
        storage : require('./storage.js')
    },
    conversation : {}, type : 'multi'
}));

I am traking when different methods of storage was called and was suprised when I found that each time when user enters the conversation profile storage’s write method is called with no changes. I didn’t expect such behaviour and still don’t understand it. Encoding to documentation conversation should only use session provided for them (conversation session).

2

Answers


  1. each time when user enters the conversation profile storage’s write method

    I assume you use await conversation.wait() for this purpose. This method creates a new context object and you have to work with it instead of the original context object.

    This means that instead of writing

    const {message} = await conversation.wait();
    

    you’ll have to use

    const newCtx = await conversation.wait();
    const {message} = newCtx;
    

    Working with the new context object fixed my problem with values dissapearing from the context object used later on.

    await ctx.reply("Напишите название книги");
    
    ctx.session.myValue = 1; // will be added
    
    const newCtx = await conversation.wait();
    
    ctx.session.someValue = 1; // will not be added
    newCtx.session.anotherValue = 1; // will be added
    

    Not the prettiest solution, but it works!

    Login or Signup to reply.
  2. With grammyjs conversation plugin, you should use conversation.session utility to deal with sessions objects as indicated in the documentation #rule-iii-use-convenience-functions :

    // `ctx.session` only persists changes for the most recent context object
    conversation.session.myProp = 42; // more reliable!
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search