grammyjs / runner

Scale bots that use long polling to receive updates.
https://grammy.dev/plugins/runner
MIT License
18 stars 2 forks source link

Wrong usage of session in the example on the main page of this git #3

Closed ProgrammingLife closed 2 years ago

ProgrammingLife commented 2 years ago

I've tried to compile example from the main page of this git, test.ts:

import { Bot, Context, session } from "grammy";
import { run, sequentialize } from "@grammyjs/runner";

// Create bot
const bot = new Bot("<token>");

/** Resolves the session key for a context object */
function getSessionKey(ctx: Context) {
  return ctx.chat?.id.toString();
}

// Sequentialize before accessing session data!
bot.use(sequentialize(getSessionKey));
bot.use(session({ getSessionKey }));

// Add the usual middleware, now with safe session support
bot.on("message", (ctx) => ctx.reply("Got your message."));

// Still run it concurrently!
run(bot);

It returns me some error message:

» tsc 
test.ts:14:9 - error TS2345: Argument of type 'MiddlewareFn<Context & SessionFlavor<unknown>>' is not assignable to parameter of type 'Middleware<Context>'.
  Type 'MiddlewareFn<Context & SessionFlavor<unknown>>' is not assignable to type 'MiddlewareFn<Context>'.
14 bot.use(session({ getSessionKey }));
           ~~~~~~~~~~~~~~~~~~~~~~~~~~
Found 1 error.

» node -v && tsc -v     
v17.0.1
Version 4.4.4

I think it can be used smth like this:

interface SessionData {
    chatId: string,
    messages: number,
    edits: number,
}
type MyContext = Context & SessionFlavor<SessionData>
const bot = new Bot<MyContext>("....")
const getSessionKey = ( ctx: Context ) => ctx.chat?.id.toString(); // Resolves the session key for a context object

bot.use(session({ initial: () => ({ chatId: getSessionKey, messages: 1, edits: 0 }) }) )

but I don't know how to initialize session object (SessionData) in this case.

KnorpelSenf commented 2 years ago

The runner docs are older than the final session design so they're outdated. Thanks for pointing this out!

You're right that this is how to fix the problem.

You can initialise the session data using the initial option on the same level as getSessionKey.

bot.use(session({ getSessionKey, initial: () => ({ chatId: 0, messages: 1, edits: 0 }) }) )
ProgrammingLife commented 2 years ago

@KnorpelSenf, thanks, man. I got it!

KnorpelSenf commented 2 years ago

Reopening until the README is updated :)

KnorpelSenf commented 2 years ago

@ProgrammingLife can you review #4 and confirm that the new example code is correct?

KnorpelSenf commented 2 years ago

Here's the rendered version I'd like to merge: https://github.com/grammyjs/runner/blob/bc5f5e70ab1515d20231941534b8d60cb0a22f7e/README.md