interact: separate interfaces

This commit is contained in:
c9s 2022-01-13 22:24:51 +08:00
parent 7eba6b20c9
commit 76c64b041f
3 changed files with 25 additions and 9 deletions

View File

@ -128,7 +128,6 @@ func main() {
globalInteraction := interact.New()
globalInteraction.SetMessenger(&interact.Telegram{
Interact: globalInteraction,
Bot: b,
})

View File

@ -30,8 +30,18 @@ const (
StateAuthenticated State = "authenticated"
)
type Messenger interface {
type TextMessageResponder interface {
SetTextMessageResponder(responder Responder)
}
type CommandResponder interface {
AddCommand(command string, responder Responder)
}
type Messenger interface {
TextMessageResponder
CommandResponder
Start()
}
@ -140,6 +150,9 @@ func (i *Interact) runCommand(command string, args []string, ctxObjects ...inter
}
func (i *Interact) SetMessenger(messenger Messenger) {
messenger.SetTextMessageResponder(func(reply Reply, response string) error {
return i.handleResponse(response, reply)
})
i.messenger = messenger
}

View File

@ -38,13 +38,15 @@ func (r *TelegramReply) build() {
r.menu.Reply(rows...)
}
//go:generate callbackgen -type Telegram
type Telegram struct {
Interact *Interact
Bot *telebot.Bot
Bot *telebot.Bot
// messageCallbacks is used for interact to register its message handler
messageCallbacks []func(reply Reply, message string)
// textMessageResponder is used for interact to register its message handler
textMessageResponder Responder
}
func (b *Telegram) SetTextMessageResponder(textMessageResponder Responder) {
b.textMessageResponder = textMessageResponder
}
func (b *Telegram) Start() {
@ -52,8 +54,10 @@ func (b *Telegram) Start() {
log.Infof("onText: %+v", m)
reply := b.newReply()
if err := b.Interact.handleResponse(m.Text, reply); err != nil {
log.WithError(err).Errorf("response handling error")
if b.textMessageResponder != nil {
if err := b.textMessageResponder(reply, m.Text); err != nil {
log.WithError(err).Errorf("response handling error")
}
}
reply.build()