bbgo_origin/pkg/interact/interact.go

359 lines
7.4 KiB
Go
Raw Normal View History

2022-01-12 13:45:12 +00:00
package interact
2022-01-11 18:54:13 +00:00
import (
2022-01-13 14:15:05 +00:00
"context"
"fmt"
2022-01-11 18:54:13 +00:00
"reflect"
"strconv"
2022-01-12 09:49:34 +00:00
"strings"
"text/scanner"
2022-01-11 18:54:13 +00:00
2022-01-13 14:15:05 +00:00
log "github.com/sirupsen/logrus"
2022-01-11 18:54:13 +00:00
)
2022-01-13 14:15:05 +00:00
type Reply interface {
Message(message string)
AddButton(text string)
RemoveKeyboard()
}
2022-01-13 17:58:04 +00:00
// Responder defines the logic of responding the message
type Responder func(message string, reply Reply, ctxObjects ...interface{}) error
2022-01-13 14:15:05 +00:00
type CustomInteraction interface {
Commands(interact *Interact)
}
2022-01-13 14:15:05 +00:00
type State string
2022-01-13 14:15:05 +00:00
const (
StatePublic State = "public"
StateAuthenticated State = "authenticated"
)
2022-01-13 14:24:51 +00:00
type TextMessageResponder interface {
SetTextMessageResponder(responder Responder)
}
type CommandResponder interface {
2022-01-13 14:15:05 +00:00
AddCommand(command string, responder Responder)
2022-01-13 14:24:51 +00:00
}
type Messenger interface {
TextMessageResponder
CommandResponder
2022-01-13 17:58:04 +00:00
Start(ctx context.Context)
}
2022-01-11 18:54:13 +00:00
// Interact implements the interaction between bot and message software.
type Interact struct {
2022-01-13 15:41:22 +00:00
// commands is the default public command map
commands map[string]*Command
2022-01-13 15:41:22 +00:00
// privateCommands is the private command map, need auth
privateCommands map[string]*Command
2022-01-13 14:15:05 +00:00
states map[State]State
statesFunc map[State]interface{}
originState, currentState State
messenger Messenger
}
func New() *Interact {
return &Interact{
2022-01-13 14:15:05 +00:00
commands: make(map[string]*Command),
originState: StatePublic,
currentState: StatePublic,
states: make(map[State]State),
statesFunc: make(map[State]interface{}),
}
}
func (it *Interact) SetOriginState(s State) {
it.originState = s
2022-01-13 14:15:05 +00:00
}
func (it *Interact) AddCustomInteraction(custom CustomInteraction) {
custom.Commands(it)
2022-01-13 14:15:05 +00:00
}
func (it *Interact) PrivateCommand(command string, f interface{}) *Command {
2022-01-13 15:41:22 +00:00
cmd := NewCommand(command, f)
it.privateCommands[command] = cmd
2022-01-13 15:41:22 +00:00
return cmd
}
func (it *Interact) Command(command string, f interface{}) *Command {
cmd := NewCommand(command, f)
it.commands[command] = cmd
return cmd
}
func (it *Interact) getNextState(currentState State) (nextState State, final bool) {
var ok bool
2022-01-13 14:15:05 +00:00
final = false
nextState, ok = it.states[currentState]
if ok {
2022-01-13 14:15:05 +00:00
// check if it's the final state
if _, hasTransition := it.statesFunc[nextState]; !hasTransition {
2022-01-13 14:15:05 +00:00
final = true
}
return nextState, final
}
2022-01-13 14:15:05 +00:00
// state not found, return to the origin state
return it.originState, final
2022-01-11 18:54:13 +00:00
}
func (it *Interact) setState(s State) {
2022-01-13 17:58:04 +00:00
log.Infof("[interact] transiting state from %s -> %s", it.currentState, s)
it.currentState = s
2022-01-13 14:15:05 +00:00
}
func (it *Interact) handleResponse(text string, ctxObjects ...interface{}) error {
args := parseCommand(text)
f, ok := it.statesFunc[it.currentState]
if !ok {
return fmt.Errorf("state function of %s is not defined", it.currentState)
}
_, err := parseFuncArgsAndCall(f, args, ctxObjects...)
if err != nil {
return err
}
nextState, end := it.getNextState(it.currentState)
if end {
it.setState(it.originState)
return nil
}
it.setState(nextState)
return nil
}
func (it *Interact) getCommand(command string) (*Command, error) {
switch it.currentState {
2022-01-13 16:17:41 +00:00
case StateAuthenticated:
if cmd, ok := it.privateCommands[command]; ok {
2022-01-13 16:17:41 +00:00
return cmd, nil
}
case StatePublic:
if _, ok := it.privateCommands[command]; ok {
2022-01-13 16:17:41 +00:00
return nil, fmt.Errorf("private command can not be executed in the public mode")
}
}
if cmd, ok := it.commands[command]; ok {
2022-01-13 16:17:41 +00:00
return cmd, nil
}
return nil, fmt.Errorf("command %s not found", command)
}
func (it *Interact) runCommand(command string, args []string, ctxObjects ...interface{}) error {
cmd, err := it.getCommand(command)
2022-01-13 16:17:41 +00:00
if err != nil {
return err
}
it.setState(cmd.initState)
if _, err := parseFuncArgsAndCall(cmd.F, args, ctxObjects...); err != nil {
return err
}
// if we can successfully execute the command, then we can go to the next state.
nextState, end := it.getNextState(it.currentState)
if end {
it.setState(it.originState)
return nil
}
it.setState(nextState)
return nil
2022-01-12 13:45:12 +00:00
}
2022-01-11 18:54:13 +00:00
func (it *Interact) SetMessenger(messenger Messenger) {
2022-01-13 17:58:04 +00:00
// pass Responder function
messenger.SetTextMessageResponder(func(message string, reply Reply, ctxObjects ...interface{}) error {
return it.handleResponse(message, append(ctxObjects, reply)...)
2022-01-13 14:24:51 +00:00
})
it.messenger = messenger
2022-01-13 14:15:05 +00:00
}
2022-01-13 16:17:41 +00:00
// builtin initializes the built-in commands
func (it *Interact) builtin() error {
it.Command("/uptime", func(reply Reply) error {
2022-01-13 16:17:41 +00:00
reply.Message("uptime")
return nil
})
return nil
}
func (it *Interact) init() error {
if err := it.builtin(); err != nil {
2022-01-13 16:17:41 +00:00
return err
}
for n, cmd := range it.commands {
for s1, s2 := range cmd.states {
if _, exist := it.states[s1]; exist {
return fmt.Errorf("state %s already exists", s1)
}
it.states[s1] = s2
}
for s, f := range cmd.statesFunc {
it.statesFunc[s] = f
}
2022-01-13 14:15:05 +00:00
// register commands to the service
if it.messenger == nil {
2022-01-13 14:15:05 +00:00
return fmt.Errorf("messenger is not set")
}
2022-01-13 16:17:41 +00:00
commandName := n
2022-01-13 17:58:04 +00:00
it.messenger.AddCommand(commandName, func(message string, reply Reply, ctxObjects ...interface{}) error {
args := parseCommand(message)
return it.runCommand(commandName, args, append(ctxObjects, reply)...)
2022-01-13 14:15:05 +00:00
})
}
return nil
2022-01-12 13:45:12 +00:00
}
func (it *Interact) Start(ctx context.Context) error {
if err := it.init(); err != nil {
2022-01-13 14:15:05 +00:00
return err
}
// TODO: use go routine and context
2022-01-13 17:58:04 +00:00
it.messenger.Start(ctx)
2022-01-13 14:15:05 +00:00
return nil
2022-01-11 18:54:13 +00:00
}
2022-01-12 09:49:34 +00:00
func parseCommand(src string) (args []string) {
2022-01-11 18:54:13 +00:00
var s scanner.Scanner
2022-01-12 09:49:34 +00:00
s.Init(strings.NewReader(src))
s.Filename = "command"
for tok := s.Scan(); tok != scanner.EOF; tok = s.Scan() {
text := s.TokenText()
if text[0] == '"' && text[len(text)-1] == '"' {
2022-01-12 09:49:34 +00:00
text, _ = strconv.Unquote(text)
2022-01-11 18:54:13 +00:00
}
args = append(args, text)
2022-01-11 18:54:13 +00:00
}
2022-01-12 09:49:34 +00:00
return args
2022-01-11 18:54:13 +00:00
}
func parseFuncArgsAndCall(f interface{}, args []string, objects ...interface{}) (State, error) {
2022-01-11 18:54:13 +00:00
fv := reflect.ValueOf(f)
ft := reflect.TypeOf(f)
2022-01-12 17:48:14 +00:00
argIndex := 0
2022-01-11 18:54:13 +00:00
var rArgs []reflect.Value
for i := 0; i < ft.NumIn(); i++ {
at := ft.In(i)
switch k := at.Kind(); k {
case reflect.Interface:
found := false
2022-01-12 17:48:14 +00:00
2022-01-13 17:58:04 +00:00
for oi := 0; oi < len(objects); oi++ {
obj := objects[oi]
objT := reflect.TypeOf(obj)
objV := reflect.ValueOf(obj)
fmt.Println(
at.PkgPath(),
at.Name(),
2022-01-12 17:48:14 +00:00
objT, "implements", at, "=", objT.Implements(at),
)
if objT.Implements(at) {
found = true
rArgs = append(rArgs, objV)
break
}
}
if !found {
v := reflect.Zero(at)
rArgs = append(rArgs, v)
}
2022-01-11 18:54:13 +00:00
case reflect.String:
2022-01-12 17:48:14 +00:00
av := reflect.ValueOf(args[argIndex])
2022-01-11 18:54:13 +00:00
rArgs = append(rArgs, av)
2022-01-12 17:48:14 +00:00
argIndex++
2022-01-11 18:54:13 +00:00
case reflect.Bool:
2022-01-12 17:48:14 +00:00
bv, err := strconv.ParseBool(args[argIndex])
2022-01-11 18:54:13 +00:00
if err != nil {
return "", err
2022-01-11 18:54:13 +00:00
}
av := reflect.ValueOf(bv)
rArgs = append(rArgs, av)
2022-01-12 17:48:14 +00:00
argIndex++
2022-01-11 18:54:13 +00:00
case reflect.Int64:
2022-01-12 17:48:14 +00:00
nf, err := strconv.ParseInt(args[argIndex], 10, 64)
2022-01-11 18:54:13 +00:00
if err != nil {
return "", err
2022-01-11 18:54:13 +00:00
}
av := reflect.ValueOf(nf)
rArgs = append(rArgs, av)
2022-01-12 17:48:14 +00:00
argIndex++
2022-01-11 18:54:13 +00:00
case reflect.Float64:
2022-01-12 17:48:14 +00:00
nf, err := strconv.ParseFloat(args[argIndex], 64)
2022-01-11 18:54:13 +00:00
if err != nil {
return "", err
2022-01-11 18:54:13 +00:00
}
av := reflect.ValueOf(nf)
rArgs = append(rArgs, av)
2022-01-12 17:48:14 +00:00
argIndex++
2022-01-11 18:54:13 +00:00
}
}
out := fv.Call(rArgs)
2022-01-12 18:06:29 +00:00
if ft.NumOut() == 0 {
return "", nil
2022-01-12 18:06:29 +00:00
}
// try to get the error object from the return value
var state State
var err error
2022-01-12 18:06:29 +00:00
for i := 0; i < ft.NumOut(); i++ {
outType := ft.Out(i)
2022-01-11 18:54:13 +00:00
switch outType.Kind() {
case reflect.String:
if outType.Name() == "State" {
state = State(out[i].String())
}
2022-01-11 18:54:13 +00:00
case reflect.Interface:
o := out[i].Interface()
2022-01-11 18:54:13 +00:00
switch ov := o.(type) {
case error:
err = ov
2022-01-11 18:54:13 +00:00
}
}
}
return state, err
2022-01-11 18:54:13 +00:00
}