Skip to content

Behaviour Builder with FSM

Behaviour builder with FSM is based on the MicroUtils FSM. There are several important things in FSM:

  • State - any object which implements State interface
  • StateHandler (or CheckableHandlerHolder) - the handler of states
  • StatesMachine - some machine which work with states and handlers
  • StatesManager - simple manager that will solve which states to save and notify about states changes via its flows

StatesMachine have two methods:

  • start which will start work of machine
  • startChain which will add new state for handling

The most based way to create StatesMachine and register StateHandlers looks like in the next snippet:

buildFSM<TrafficLightState> {
    strictlyOn<SomeState> {
        // state handling
    }
}.start(CoroutineScope(...)).join()

Full example

You may find full example of FSM usage in the tests of FSM in MicroUtils

So, you must do next steps before you will launch your bot with FSM:

  • Create your states. Remember that you may plan to save them, so it is likely you will need to serialize it there
  • Create your handlers for your states. In most cases it is useful to use CheckableHandlerHolder if you want to use standard states machine
  • Solve which states managers to use (the most simple one is the DefaultStatesManager with InMemoryDefaultStatesManager)

Bot with FSM

There are several extensions for TelegramBot to create your bot with FSM:

All of them will take as an callback some object with type CustomBehaviourContextReceiver and will looks like in the next snippet:

telegramBotWithBehaviourAndFSMAndStartLongPolling<YourStateType>("BOT_TOKEN") {
    // here you may use any operations from BehaviourBuilder
    // here you may use any operations from BehaviourContextWithFSMBuilder like strictlyOn and others
}

Examples