English فارسی

FSM & state machines

A small, dependency-free finite-state machine for multi-step conversations — wizards, onboarding, forms.

Three pieces

PieceRole
StatesGroupDeclares the states as class attributes
StateOne named state inside a group
FSMContextPer-user state + free-form data, backed by a storage
from balexyz.fsm import State, StatesGroup


class Order(StatesGroup):
    waiting_item = State()
    waiting_address = State()
    confirm = State()

A complete wizard

from balexyz import Client, filters
from balexyz.fsm import State, StatesGroup

client = Client("256049633:eyJ…")


class Order(StatesGroup):
    item = State()
    address = State()


@client.on_message(filters.command("order"))
async def begin(message):
    ctx = message.get_fsm_context()
    await ctx.set_state(Order.item)
    await message.reply("Which item?")


@client.on_message(filters.text)
async def step(message):
    ctx = message.get_fsm_context()
    state = await ctx.get_state()

    if state == Order.item.state:
        await ctx.update_data(item=message.text)
        await ctx.set_state(Order.address)
        await message.reply("Shipping address?")

    elif state == Order.address.state:
        await ctx.update_data(address=message.text)
        data = await ctx.get_data()
        await ctx.finish()
        await message.reply(f"Ordered {data['item']} to {data['address']}")

Context methods

FSMContext — set_state, get_state, set_data, get_data, update_data, clear
set_state(state)
Store a state (pass None to reset)
get_state()
The current state string, or None
set_data(**kw)
Replace the whole data blob
get_data()
Read the blob as a dict
update_data(**kw)
Merge keys into the blob
clear()
Reset both state and data

Storage

Defaults to MemoryStorage, which is lost on restart. For anything real, bring your own:

from balexyz.fsm import MemoryStorage

storage = MemoryStorage()

class RedisStorage:
    async def get_state(self, key): ...
    async def set_state(self, key, state): ...
    async def get_data(self, key): ...
    async def set_data(self, key, data): ...
    async def finish(self, key): ...
Memory storage is fine for one process.

If you run several workers, each will have its own view of the conversation. Implement the five-method storage interface above against Redis or Postgres before you scale out.

Two things to watch

  • Filter overlap. A catch-all filters.text handler will also see /order. Guard with if state is None: return at the top of your step handler.
  • Groups are per user. The context key is derived from sender id, so a group chat with ten people keeps ten independent conversations.
bale xyz 1.0.0 · MIT licensed · unofficial client © 2026 bale xyz contributors