-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.go
104 lines (88 loc) · 2.24 KB
/
bot.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package whatsapp_chatbot_golang
import (
"github.com/green-api/whatsapp-api-client-golang/pkg/api"
"log"
"time"
)
type Bot struct {
api.GreenAPI
CleanNotificationQueue bool
StateManager
Publisher
isStart bool
ErrorChannel chan error
}
func NewBot(IDInstance string, APITokenInstance string) *Bot {
return &Bot{
GreenAPI: api.GreenAPI{
IDInstance: IDInstance,
APITokenInstance: APITokenInstance,
},
CleanNotificationQueue: true,
StateManager: NewMapStateManager(map[string]interface{}{}),
Publisher: Publisher{},
ErrorChannel: make(chan error, 1),
}
}
func (b *Bot) StartReceivingNotifications() {
if b.CleanNotificationQueue {
b.DeleteAllNotifications()
}
b.isStart = true
log.Print("Bot Start receive webhooks")
for b.isStart == true {
response, err := b.Methods().Receiving().ReceiveNotification()
if err != nil {
b.ErrorChannel <- err
time.Sleep(5000)
continue
}
if response["body"] == nil {
log.Print("webhook queue is empty")
continue
} else {
responseBody := response["body"].(map[string]interface{})
notification := NewNotification(responseBody, b.StateManager, &b.GreenAPI, &b.ErrorChannel)
b.startCurrentScene(notification)
_, err := b.Methods().Receiving().DeleteNotification(int(response["receiptId"].(float64)))
if err != nil {
b.ErrorChannel <- err
continue
}
}
}
}
func (b *Bot) StopReceivingNotifications() {
if b.isStart {
b.isStart = false
log.Print("Bot stopped")
} else {
log.Print("Bot already stopped!")
}
}
func (b *Bot) DeleteAllNotifications() {
log.Print("deleting notifications Start...")
for {
response, _ := b.Methods().Receiving().ReceiveNotification()
if response["body"] == nil {
log.Print("deleting notifications finished!")
break
} else {
_, err := b.Methods().Receiving().DeleteNotification(int(response["receiptId"].(float64)))
if err != nil {
b.ErrorChannel <- err
}
}
}
}
func (b *Bot) startCurrentScene(n *Notification) {
currentState := n.StateManager.Get(n.StateId)
if currentState == nil {
currentState = n.StateManager.Create(n.StateId)
}
if n.GetCurrentScene() != nil {
b.Publisher.clearAll()
n.GetCurrentScene().Start(b)
}
b.Publisher.publish(n)
}