Changed State
This commit is contained in:
parent
5842815c95
commit
1a8decf4d4
7
bot.go
7
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)
|
||||
}
|
||||
|
|
|
@ -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
|
||||
|
|
40
state.go
40
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) {
|
||||
|
|
Loading…
Reference in New Issue