[документация]@dataclass(slots=True)classStateContext:"""User state context. Provides a convenient interface for managing FSM states and user data within handlers. Args: bot: VKBot instance. user_id: User ID. fsm_name: Finite state machine name. """bot:"VKBot"user_id:intfsm_name:str="default"_manager:StateManager=field(init=False,repr=False)fsm:"VKBotFSM"=field(init=False)def__post_init__(self)->None:self._manager=self.bot.state_managerself.fsm=FSMRegistry.get_or_create(self.fsm_name)@propertydefcurrent(self)->str|None:"""Current state of this user, read from storage."""returnself._manager.get_state(self.user_id)
[документация]defset(self,state:str)->bool:"""Transition the user to ``state``. Validates the transition against the FSM graph, executes any registered callbacks, then persists the new state to storage. Raises: ValueError: If the transition is not allowed by the graph. """current=self.currentifnotself.fsm.can_transition(current,state,self):raiseValueError(f"Transition from '{current}' to '{state}' not allowed")self.fsm.execute_transition(current,state,self)self._manager.set_state(self.user_id,state)returnTrue
[документация]defget(self)->str|None:"""Return the current state (alias for :attr:`current`)."""returnself.current
[документация]deffinish(self)->None:"""Reset the user's state and clear all stored data."""self._manager.reset(self.user_id)
@propertydefdata(self)->dict[str,Any]:"""User data stored alongside the state."""returnself._manager.get_data(self.user_id)
[документация]defupdate(self,**kwargs:Any)->None:"""Merge ``kwargs`` into the user's stored data."""self._manager.update_data(self.user_id,**kwargs)
[документация]defclear_data(self)->None:"""Clear all user data without resetting the state."""self._manager.set_data(self.user_id,{})
[документация]defis_state(self,state:str)->bool:"""Return ``True`` if the user is currently in ``state``."""returnself.current==state
[документация]defis_in_group(self,group:str)->bool:"""Return ``True`` if the user's current state belongs to ``group``."""current=self.currentifnotcurrent:returnFalsereturnself.fsm.is_in_group(current,group)
[документация]defget_next_states(self)->list[str]:"""Return all states reachable from the user's current state."""current=self.currentifcurrentisNone:return[]returnself.fsm.get_next_states(current,self)