Skip to content
This repository has been archived by the owner on Apr 28, 2023. It is now read-only.

vlad-iakovlev/grammy-named-session

Repository files navigation

grammy-named-session

Named session for grammY. Works the same way as built-in session but allows you to set custom name for data access.

GitHub CI Codecov NPM

How to install

npm install grammy-named-session

How to use

import { Bot, Context } from 'grammy';
import { namedSession } from 'grammy-named-session';

interface Item {
  id: string
  value: string
}

interface MyState {
  items: Item[]
  users: Record<number, string>
}

interface MyContext extends Context {
  myState: MyState
}

const myStateMiddleware = (dirName: string) => {
  return namedSession<MyContext, 'myState'>({
    // type MaybePromise<T> = Promise<T> | T

    // Initial data, required
    // (ctx: MyContext) => MaybePromise<MyContext['myState']>
    getInitial: () => ({
      items: [],
      users: {},
    }),

    // Session key, required
    // (ctx: MyContext) => MaybePromise<string | undefined>
    getSessionKey: (ctx) =>
      ctx.chat?.id === undefined ? undefined : `my_${ctx.chat.id}`,

    // Storage adapter, required
    // (ctx: MyContext) => MaybePromise<StorageAdapter<MyContext['myState']>>
    getStorage: () => new FileAdapter({ dirName }),

    // Access name, must be the same as in the types, required
    // string
    name: 'myState',
  })
}

(async () => {
  const bot = new Bot<MyContext>('<bot-token>');

  bot.use(myStateMiddleware('db/v1'));

  bot.command('start', async (ctx) => {
    // Access data as usual but with custom name
    await ctx.mySession.users[ctx.from.id] = ctx.from.first_name;
  });
})()