Skip to main content

State Machines

For multi-stage workflows with well-defined states and transitions (onboarding, order lifecycle, support tickets), Botgami offers a finite state machine: state.machine defines and instantiates one, state.command sends events, and state.read inspects it.

tip

For simple multi-step flows, a user.* variable plus when/branch is usually enough. Reach for a state machine when you have several named states and event-driven transitions you want to model explicitly.

state.machine

Define and instantiate a machine. You describe states and the events that move between them, then create an instance per user or per workflow.

let { instance_id, state } = state.machine(
instance_id: `order-${flow.order_id}`,
data: { items: flow.cart }
)
send.text(`Order created in state: ${state}`)
ParamTypeNotes
instance_idStringStable id for this instance
dataObjectInitial context data

Outputs: instance_id, state, instance, error_text.

state.command

Dispatch an event to an instance, causing a transition:

let { from_state, to_state } = state.command(
instance_id: `order-${flow.order_id}`,
event: "pay",
data: { amount: flow.total }
)
send.text(`Order moved from ${from_state} to ${to_state}.`)
ParamTypeNotes
instance_id!StringWhich instance
event!StringThe event/transition name
dataObjectEvent payload

Outputs: from_state, to_state, instance, error_text.

state.read

Read an instance (or list of instances) and its history:

let { instance, history, count } = state.read(instance_id: `order-${flow.order_id}`)
send.text(`Current state: ${instance.state} (${count} transitions)`)
ParamType
instance_id!String

Outputs: instance, instances, history, count.

See also