diff --git a/bot.go b/bot.go index fef2c3e..2dab810 100644 --- a/bot.go +++ b/bot.go @@ -2,6 +2,7 @@ package nechotron import ( "context" + "sync" "time" echo "github.com/NicoNex/echotron/v3" @@ -12,6 +13,8 @@ type bot struct { chatID int64 me *echo.User echo.API + data StateData + lock sync.Mutex state *State } @@ -25,7 +28,9 @@ func (b *bot) Update(u *echo.Update) { Ctx: ctx, } - newState, err := b.state.Fn(upd) + b.lock.Lock() + defer b.lock.Unlock() + newState, err := b.state.Call(upd) if err != nil { upd.LogError("", err, true) } diff --git a/nechotron.go b/nechotron.go index 00be9cb..92cee39 100644 --- a/nechotron.go +++ b/nechotron.go @@ -31,6 +31,7 @@ func (n *Nechotron) newBot(chatID int64) echo.Bot { me: me.Result, API: a, state: n.DefaultState, + data: make(StateData), } b.state = n.DefaultState return b diff --git a/state.go b/state.go index 9379422..d1398f5 100644 --- a/state.go +++ b/state.go @@ -1,20 +1,52 @@ package nechotron import ( - "context" + "errors" "github.com/NicoNex/echotron/v3" ) +type StateData map[string]interface{} + +type Runnable interface { + Call(*Update) (*State, error) +} + type State struct { - Fn stateFn - Data context.Context + fn stateFn +} + +func (s *State) Call(u *Update) (*State, error) { + return s.fn(u) } type stateFn func(*Update) (*State, error) +func (d StateData) Set(name string, data interface{}) { + d[name] = data +} + +func (d StateData) Get(name string) (interface{}, error) { + data, ok := d[name] + if !ok { + return nil, errors.New("can't get data from statedata") + } + return data, nil +} + +func (d StateData) Has(name string) bool { + _, ok := d[name] + return ok +} + +func (d StateData) Clear() { + for k := range d { + delete(d, k) + } +} + var EchoState = State{ - Fn: EchoFunc, + fn: EchoFunc, } func EchoFunc(u *Update) (*State, error) {