Andrii Myronenko
Andrii Myronenko

Reputation: 41

Telegraf BaseScene custom context with typescript implementation

I'm writing a telegram bot with Telegraf (v4.12.2) and typescript (v5.1.6) and trying to implement the stage. But for some reason can not set custom scene context with the fields i need. May be someone encountered the same problem before, please take a quick look.

As far as i know that Telegraf has two types of session stores, scene session and telegraf session. My goal is to create custom scene session store with the fields time, longitude, latitude. This data i will get from user when they enters the scene. I played with different types but eventually there is always any in one of the places, either new BaseScene<any> or new Stage<any>.

I want to avoid any and wonder if it's even possible.

Here's the minimal code.

const bot = new Telegraf<SceneContext>('token')

const scene = new BaseScene<any>('id')

const stage = new Stage<SceneContext>(scene)

I could do something like this but dont know how to set up correct Stage context then:

interface CustomSceneSessionData extends SceneSessionData {
  time: number;
  offset: number;
  chatId: number;
  latitude: number;
  longitude: number;
  timeInput: string;
}

const scene = new BaseScene<SceneContext<CustomSceneSessionData>>('id')

*putting SceneContext here says that types of scene and SceneContext are incompatible*
const stage = new Stage<SceneContext>(scene)

So eventually it is either new BaseScene<any> or new Stage<any> and the main question

Is there any way to avoid using any and implement custom Context for Scenes?

Upvotes: 2

Views: 1262

Answers (1)

Ron Vaknin
Ron Vaknin

Reputation: 66

I'm using it this way

export interface SceneContext extends Context {
    mySessionData: someSessionDataInteface;
    scene: Scenes.SceneContextScene<SceneContext, SceneSession>;
}


const bot = new Telegraf<SceneContext>('token')

const scene = new BaseScene<SceneContext>('id')

const stage = new Stage<SceneContext>(scene)

If you want to extend SceneSessionData you can use this example

Upvotes: 2

Related Questions