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 := interact.New()
globalInteraction.SetMessenger(&interact.Telegram{ globalInteraction.SetMessenger(&interact.Telegram{
Interact: globalInteraction,
Bot: b, Bot: b,
}) })

View File

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

View File

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