v0.3.x · pyrogram_patch
FSM & States
The Finite State Machine lets you guide users through multi-step flows. Define state groups, set/get state in handlers, and store arbitrary data alongside each state.
Defining States
from pyrogram_patch.fsm import StatesGroup, State
class Registration(StatesGroup):
name = State()
email = State()
phone = State()
# State names are <Group>:<field>
# Registration.name → "Registration:name"
# Registration.email → "Registration:email"Using FSMContext in Handlers
from pyrogram_patch.fsm import FSMContext
@router.on_command("register")
async def start_registration(client, message, state: FSMContext):
await state.set_state(Registration.name)
await message.reply("Enter your name:")
@router.on_message(StateFilter(Registration.name))
async def got_name(client, message, state: FSMContext):
await state.update_data(name=message.text)
await state.set_state(Registration.email)
await message.reply("Enter your email:")
@router.on_message(StateFilter(Registration.email))
async def got_email(client, message, state: FSMContext):
data = await state.get_data()
await state.clear_state()
await message.reply(
f"Registered: {data['name']} <{message.text}>"
)StateFilter
from pyrogram_patch.fsm.filters import StateFilter
# Match a specific state
@router.on_message(StateFilter(Registration.name))
async def handler(client, message, state: FSMContext): ...
# Match any state in the group
@router.on_message(StateFilter(Registration))
async def any_reg_state(client, message, state: FSMContext): ...
# Match no state (user is outside any flow)
@router.on_message(StateFilter(state=None))
async def no_state(client, message, state: FSMContext): ...FSMContext API
| Method | Description |
|---|---|
await set_state(state) | Set the current state |
await get_state() | Return current state string or None |
await clear_state() | Clear state and data |
await update_data(**kw) | Merge kwargs into stored data |
await get_data() | Return stored data dict |
await clear_data() | Clear stored data, keep state name |