我正在使用 Telegraf (v4.12.2) 和 typescript (v5.1.6) 编写一个电报机器人,并尝试实现该阶段。但由于某种原因无法使用我需要的字段设置自定义场景上下文。可能有人遇到过同样的问题,请快速查看。
据我所知,Telegraf 有两种类型的会话存储,场景会话和 Telegraf 会话。我的目标是创建包含时间、经度、纬度字段的自定义场景会话存储。当用户进入场景时,我将从他们那里获得这些数据。我玩过不同的类型,但最终其中一个地方总是有
any
,要么是new BaseScene<any>
,要么是new Stage<any>
。
我想避免
any
并想知道这是否可能。
这是最少的代码。
const bot = new Telegraf<SceneContext>('token')
const scene = new BaseScene<any>('id')
const stage = new Stage<SceneContext>(scene)
我可以做这样的事情,但不知道如何设置正确的舞台上下文:
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)
所以最终要么是
new BaseScene<any>
要么 new Stage<any>
以及主要问题
有什么方法可以避免使用任何场景并实现自定义场景上下文?
我就是这样用的
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)
如果你想扩展
SceneSessionData
你可以使用这个例子