100 lines
2.3 KiB
Go
100 lines
2.3 KiB
Go
package fsmwizard
|
|
|
|
import (
|
|
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/pkg/types"
|
|
"time"
|
|
|
|
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/handler/iface"
|
|
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/internal/handler/util"
|
|
"gitea.neur0tx.site/Neur0toxine/vegapokerbot/pkg/fsm"
|
|
)
|
|
|
|
var (
|
|
wizards *types.TTLMap[int64, fsm.IMachine[Wizard]]
|
|
states []fsm.IState[Wizard]
|
|
errorState *ErrorState
|
|
appPointer iface.App
|
|
)
|
|
|
|
func init() {
|
|
wizards = types.NewTTLMap[int64, fsm.IMachine[Wizard]](time.Hour * 24 * 7)
|
|
}
|
|
|
|
func Get(userID int64) fsm.IMachine[Wizard] {
|
|
if machine, ok := wizards.Get(userID); ok && machine != nil {
|
|
return machine
|
|
}
|
|
machine := newWizard()
|
|
wizards.Set(userID, machine)
|
|
return machine
|
|
}
|
|
|
|
func newWizard() fsm.IMachine[Wizard] {
|
|
return fsm.New[Wizard](states[0].ID(), wizardRouter, states, errorState)
|
|
}
|
|
|
|
// PopulateStates will init all state handlers for future use.
|
|
func PopulateStates(app iface.App) {
|
|
appPointer = app
|
|
states = []fsm.IState[Wizard]{
|
|
NewRegisterState(app),
|
|
NewWaitingForMemberWebhookState(app),
|
|
NewAddChatMemberState(app),
|
|
NewKeyboardChooserState(app),
|
|
NewConfigureRedmineQueryState(app),
|
|
NewRemoveChatMemberState(app),
|
|
NewHelpState(app),
|
|
NewUnknownCommandState(app),
|
|
}
|
|
errorState = NewErrorState(app.Log())
|
|
}
|
|
|
|
func wizardRouter(w *Wizard, mc fsm.MachineControlsWithState[Wizard]) {
|
|
if w.Data.Message != nil {
|
|
if w.UserID == 0 {
|
|
w.UserID = w.Data.Message.From.ID
|
|
}
|
|
if w.ChatID == 0 {
|
|
w.ChatID = w.Data.Message.Chat.ID
|
|
}
|
|
if w.User == nil {
|
|
user, err := appPointer.DB().ForUser().ByTelegramID(w.Data.Message.From.ID)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
if user != nil && user.ID > 0 {
|
|
w.User = user
|
|
}
|
|
}
|
|
if w.Chat == nil {
|
|
chat, err := appPointer.DB().ForChat().ByTelegramID(w.Data.Message.Chat.ID)
|
|
if err != nil {
|
|
return
|
|
}
|
|
|
|
if chat != nil && chat.ID > 0 {
|
|
w.Chat = chat
|
|
}
|
|
}
|
|
if w.TGChat.ID == 0 {
|
|
w.TGChat = w.Data.Message.Chat
|
|
}
|
|
|
|
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)
|
|
}
|
|
}
|