forked from drakenot/gramarr
/
conversation.go
61 lines (49 loc) · 1.32 KB
/
conversation.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package main
import (
"fmt"
tb "gopkg.in/tucnak/telebot.v2"
"github.com/patrickmn/go-cache"
"time"
)
type Conversation interface {
Run(m *tb.Message)
CurrentStep() Handler
Name() string
}
type ConversationManager struct {
convos *cache.Cache
}
func NewConversationManager() *ConversationManager {
convos := cache.New(30*time.Minute, 10*time.Minute)
return &ConversationManager{convos: convos}
}
func (cm *ConversationManager) ProcessMessage(m *tb.Message) {
key := cm.convoKey(m)
if convo, ok := cm.convos.Get(key); ok {
c := convo.(Conversation)
c.CurrentStep()(m)
}
}
func (cm *ConversationManager) HasConversation(m *tb.Message) bool {
_, exists := cm.convos.Get(cm.convoKey(m))
return exists
}
func (cm *ConversationManager) StartConversation(c Conversation, m *tb.Message) {
c.Run(m)
cm.convos.SetDefault(cm.convoKey(m), c)
}
func (cm *ConversationManager) StopConversation(c Conversation) {
for key, item := range cm.convos.Items() {
current := item.Object.(Conversation)
if c == current {
cm.convos.Delete(key)
}
}
}
func (cm *ConversationManager) Conversation(m *tb.Message) (Conversation, bool) {
c, exists := cm.convos.Get(cm.convoKey(m))
return c.(Conversation), exists
}
func (cm *ConversationManager) convoKey(m *tb.Message) string {
return fmt.Sprintf("%d:%d", m.Chat.ID, m.Sender.ID)
}