vegapokerbot/internal/handler/fsmwizard/init.go

76 lines
1.8 KiB
Go
Raw Normal View History

package fsmwizard
2024-05-13 16:57:55 +03:00
import (
"time"
2024-05-13 16:57:55 +03:00
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/handler/iface"
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/handler/util"
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/pkg/fsm"
2024-05-13 16:57:55 +03:00
"github.com/maypok86/otter"
)
var (
wizards otter.Cache[int64, fsm.IMachine[Wizard]]
states []fsm.IState[Wizard]
errorState *ErrorState
)
func init() {
storage, err := otter.MustBuilder[int64, fsm.IMachine[Wizard]](1000).
Cost(func(key int64, value fsm.IMachine[Wizard]) uint32 {
return 1
}).
WithTTL(time.Hour * 24 * 7).
Build()
if err != nil {
panic(err)
}
wizards = storage
}
2024-05-13 19:46:55 +03:00
func Get(userID int64) fsm.IMachine[Wizard] {
if machine, ok := wizards.Get(userID); ok {
2024-05-13 16:57:55 +03:00
return machine
}
machine := newWizard()
2024-05-13 19:46:55 +03:00
wizards.Set(userID, machine)
2024-05-13 16:57:55 +03:00
return machine
}
func newWizard() fsm.IMachine[Wizard] {
return fsm.New[Wizard](states[0].ID(), Wizard{}, wizardPreHandle, states, errorState)
2024-05-13 16:57:55 +03:00
}
// PopulateStates will init all state handlers for future use.
2024-05-13 16:57:55 +03:00
func PopulateStates(app iface.App) {
states = []fsm.IState[Wizard]{
NewRegisterState(app),
2024-05-13 17:18:22 +03:00
NewWaitingForMemberWebhookState(app),
NewAddChatMemberState(app),
NewKeyboardChooserState(app),
2024-05-13 17:18:22 +03:00
NewRemoveChatMemberState(app),
2024-05-13 16:57:55 +03:00
NewHelpState(app),
NewUnknownCommandState(app),
2024-05-13 16:57:55 +03:00
}
errorState = NewErrorState(app.Log())
}
func wizardPreHandle(w *Wizard, mc fsm.MachineControls[*Wizard]) {
if w.Data.Message != nil {
switch {
case util.MatchCommand("start", w.Data.Message):
mc.Move(RegisterStateID, w)
case util.MatchCommand("help", w.Data.Message):
mc.Move(HelpStateID, w)
case util.HasCommand(w.Data.Message):
mc.Move(UnknownCommandStateID, w)
default:
return
}
}
if w.Data.MyChatMember != nil {
mc.Move(WaitingForMemberWebhookStateID, w)
}
}