-
Notifications
You must be signed in to change notification settings - Fork 2
/
messenger_wrapper.go
211 lines (189 loc) · 5.35 KB
/
messenger_wrapper.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"strings"
)
// RE implement the session store & session
import (
"github.com/PuerkitoBio/goquery"
"github.com/paked/messenger"
)
type Messenger struct {
bot *Bot
client *messenger.Messenger
store SessionStore
}
// NewMessenger - Initialize new Messenger wrapper
func NewMessenger(b *Bot) *Messenger {
m := &Messenger{
bot: b,
client: messenger.New(messenger.Options{
Verify: b.Configs["messenger-verify"] == "yes",
AppSecret: b.Configs["messenger-app-secret"],
VerifyToken: b.Configs["messenger-verify-token"],
Token: b.Configs["messenger-page-token"],
}),
store: NewSessionStore(),
}
m.Boot()
return m
}
// SendGreeting - send the greeting data/messages
func (m Messenger) SetGreeting() error {
if desc, ok := m.bot.Configs["description"]; ok {
return m.client.GreetingSetting(desc)
}
return nil
}
// GetMainMenu - find the main menu
func (m Messenger) GetMainMenu() *Menu {
mainMenu := m.bot.Configs["main-menu"]
if "" == mainMenu {
return nil
}
menu := m.bot.Menus[mainMenu]
return menu
}
// SendMainMenu - sending the main messenger menu
func (m Messenger) SetMainMenu(menu *Menu) error {
if menu == nil {
return nil
}
callToActions := []messenger.CallToActionsItem{}
for _, btn := range menu.Buttons {
cta := messenger.CallToActionsItem{}
cta.Title = btn.Title
if strings.HasPrefix(btn.Href, "http://") || strings.HasPrefix(btn.Href, "https://") {
cta.Type = "web_url"
cta.MessengerExtension = (btn.Embed != "no") && (btn.Embed != "")
cta.WebviewHeightRatio = btn.Embed
} else {
cta.Type = "postback"
cta.Payload = fmt.Sprintf("trgt=%s&btn=%s", btn.Href[1:], btn.ID)
}
callToActions = append(callToActions, cta)
}
err := m.client.CallToActionsSetting("existing_thread", callToActions)
if err != nil {
return err
}
return m.client.CallToActionsSetting("new_thread", []messenger.CallToActionsItem{
{
Title: "Get Started ^_^",
Type: "postback",
Payload: "get_started",
},
})
}
func (m Messenger) GetWelcomeMenu() *Menu {
return m.bot.Menus[m.bot.Configs["welcome-menu"]]
}
// Boot - Setup the default handlers
func (m Messenger) Boot() {
// send the main menu
if err := m.SetMainMenu(m.GetMainMenu()); err != nil {
log.Println(err)
return
}
// send greetings
if err := m.SetGreeting(); err != nil {
log.Println(err)
return
}
// handling the free text input
m.client.HandleMessage(func(msg messenger.Message, r *messenger.Response) {
// setup the session
session := NewMessengerSession(
m.bot,
m.store,
r,
msg.Sender,
)
// setting up states "seen, typing ... etc"
r.SenderAction("mark_seen")
r.SenderAction("typing_on")
defer r.SenderAction("typing_off")
// expecting a user input ...
if session.IsExpectingUserInput() {
input := m.bot.Inputs[session.GetCurrentElement()]
ans := msg.Text
if input.Type == "file" {
if len(msg.Attachments) < 1 {
r.Text("Please upload a valid file", messenger.MessagingType("RESPONSE"))
return
}
ans = msg.Attachments[0].Payload.URL
}
session.SetData(input.Name, ans)
session.SendNodesOf(m.bot.Document.Find("#" + session.GetCurrentContainer()))
return
}
// from templates
err, found := session.MatchTemplate(msg.Text)
if !found || err != nil {
log.Println("[template]", err)
session.SendText("Sorry, but I cannot understand your input")
}
})
// handling the postbacks "link/button" clicks
m.client.HandlePostBack(func(p messenger.PostBack, r *messenger.Response) {
// setup the session
session := NewMessengerSession(
m.bot,
m.store,
r,
p.Sender,
)
// setting up states "seen, typing ... etc"
r.SenderAction("mark_seen")
r.SenderAction("typing_on")
defer r.SenderAction("typing_off")
// get started button ?
if p.Payload == "get_started" {
if err := m.SetGreeting(); err != nil {
log.Println("[greeting-message]", err)
return
}
if err := session.SendBasicMenu(m.GetWelcomeMenu()); err != nil {
log.Println("[welcome-menu]", err)
return
}
return
}
// the required action
needle, _ := url.ParseQuery(p.Payload)
log.Println("[postback]", needle, ", ShouldBeInput: ", session.IsExpectingUserInput())
// reset?
if needle.Get("btn") != "" && m.bot.Buttons[needle.Get("btn")] != nil && m.bot.Buttons[needle.Get("btn")].Reset {
session.Forget()
}
// an answer?
if session.IsExpectingUserInput() && needle.Get("answer") == "yes" && needle.Get("input") != "" {
input := m.bot.Inputs[needle.Get("input")]
if input == nil {
log.Println("[input]", "unknown input with id (", needle.Get("input"), ")")
return
}
session.SetData(input.Name, needle.Get("value"))
session.SendNodesOf(m.bot.Document.Find("#" + session.GetCurrentContainer()))
return
}
// an action?
trgt := m.bot.Document.Find("#" + needle.Get("trgt"))
switch goquery.NodeName(trgt) {
case "div", "dialog", "form":
log.Println("[sending nodes] has error?", session.SendNodesOf(trgt))
case "menu", "nav":
log.Println("[sending menu] has error?", session.SendBasicMenu(m.bot.Menus[trgt.AttrOr("id", "")]))
default:
r.Text("Sorry, I couldn't understand you", messenger.MessagingType("RESPONSE"))
}
})
}
// ServeHTTP - handle the http requests
func (m Messenger) ServeHTTP(res http.ResponseWriter, req *http.Request) {
m.client.Handler().ServeHTTP(res, req)
}