Skip to content

EN FSM and Scenes

Andrewkydev edited this page Aug 26, 2026 · 3 revisions

FSM and Scenes

Русский: RU-FSM-and-Scenes

For new multi-step conversations, use the storage-backed scenes from state.

store := memory.New()
app.Storage(store)

fsm := state.NewFSM(store.Sessions(), 24*time.Hour)
app.Use(state.SessionMiddleware(store.Sessions(), 24*time.Hour))
app.Use(fsm.Middleware())

scene := state.NewScene("feedback", 24*time.Hour)
scene.Step("message", func(ctx *botctx.Context, session state.Session) error {
	text := ctx.Input()
	if len(text) < 5 {
		return ctx.SendText("Please provide more detail")
	}
	session.Set("feedback.message", text)
	scene.Next(session)
	return ctx.SendText("Confirm: yes or no")
})

scene.Step("confirm", func(ctx *botctx.Context, session state.Session) error {
	if strings.EqualFold(ctx.Input(), "yes") {
		if err := fsm.Exit(ctx); err != nil {
			return err
		}
		return ctx.SendText("Saved")
	}
	return ctx.SendText("Answer yes or no")
})

fsm.Scene(scene)
app.Command("feedback", func(ctx *botctx.Context) error {
	if err := fsm.Enter(ctx, "feedback"); err != nil {
		return err
	}
	return ctx.SendText("Leave your feedback")
})

Rules

  • Register session middleware before FSM middleware.
  • An active scene intercepts events before the router; handle /cancel inside the scene flow.
  • scene.Next advances to the next step; the scene ends after its final step.
  • fsm.Exit deletes the FSM session.
  • State keys include the platform, chat, and user.
  • Session values must be serializable with encoding/json.
  • Repository and JSON decoding failures stop the handler; they are never treated as an empty session.
  • Same-key updates are serialized within one process. Multiple replicas require store-level concurrency control.

Place i18n.Middleware between session and FSM middleware. Scene handlers then use ctx.T like ordinary handlers, while i18n.SetLocale stores a language choice in the same attached session. See Localization.

core/fsm is a lower-level compatibility API with ctx.State, SetState, and ClearState. Do not mix both APIs in the same flow.

Clone this wiki locally