/
lineWebhookHandler.go
289 lines (260 loc) · 7.47 KB
/
lineWebhookHandler.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
package http
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"regexp"
"text/template"
"github.com/labstack/echo"
"github.com/line/line-bot-sdk-go/linebot"
log "github.com/sirupsen/logrus"
"github.com/VagabondDataNinjas/gizlinebot/domain"
"github.com/VagabondDataNinjas/gizlinebot/storage"
"github.com/VagabondDataNinjas/gizlinebot/survey"
)
func LineWebhookHandlerBuilder(surv *survey.Survey, s *storage.Sql, bot *linebot.Client, globalVars *domain.GlobalTplVars) func(c echo.Context) error {
return func(c echo.Context) error {
events, err := bot.ParseRequest(c.Request())
if err != nil {
if err == linebot.ErrInvalidSignature {
c.JSON(400, map[string]string{"status": "error", "err": err.Error()})
// w.WriteHeader(400)
} else {
// @TODO log error
c.JSON(500, map[string]string{"status": "error"})
}
}
for _, event := range events {
userId := event.Source.UserID
questionTplVars := &survey.QuestionTemplateVars{
UserId: userId,
Hostname: globalVars.Hostname,
}
eventString, err := json.Marshal(event)
if err != nil {
log.Errorf("Could not marshal event: %+v; err: %s", event, err)
} else {
err = s.AddRawLineEvent(string(event.Type), string(eventString))
if err != nil {
log.Errorf("Could not store event: %+v; err: %s", event, err)
}
}
if event.Type == linebot.EventTypeUnfollow {
err = onUnfollow(userId, s)
log.Infof("Unfollow event: %s", userId)
if err != nil {
log.Error(err)
continue
}
}
if event.Type == linebot.EventTypeFollow {
log.Infof("Follow event: %s", userId)
userProfileResp, err := bot.GetProfile(userId).Do()
if err != nil {
log.Error(err)
continue
}
err = s.AddUpdateUserProfile(userProfileResp.UserID, userProfileResp.DisplayName)
if err != nil {
log.Errorf("AddUpdateUserProfile err: %s", err)
continue
}
profile, err := s.GetUserProfile(userId)
if err != nil {
log.Error(err)
continue
}
if profile.SurveyStarted {
question, err := surv.GetNextQuestion(userId, questionTplVars)
if err != nil {
log.Error(err)
continue
}
if _, err = bot.PushMessage(userId, linebot.NewTextMessage(question.Text)).Do(); err != nil {
log.Error(err)
continue
}
} else {
log.Infof("User %s: sending welcome messages", userId)
err = sendWelcomeMsgs(userId, bot, s, globalVars)
if err != nil {
log.Error(err)
continue
}
}
}
if event.Type == linebot.EventTypeMessage {
switch message := event.Message.(type) {
case *linebot.LocationMessage:
err = surv.RecordGpsAnswer(userId, message.Latitude, message.Longitude, message.Address, "line")
if err != nil {
log.Error(err)
break
}
case *linebot.TextMessage:
customQuestionId, replyText, qTs, err := s.CustomQuestion(userId)
if err != nil {
log.Error(err)
}
// did this user get a custom question sent?
if customQuestionId != "" {
// have they answered this custom question already?
answered, err := s.UserAnsweredCustomQuestion(userId, customQuestionId, qTs)
if err != nil {
log.Error(err)
break
}
if answered {
log.WithFields(log.Fields{
"UserId": userId,
"QuestionId": customQuestionId,
}).Infof("User already answered this question")
// if user already answered question record in the answers table with "na" question id
if err = surv.RecordAnswerRaw(userId, "na", message.Text, "line"); err != nil {
log.Error(err)
break
}
// do not continue
break
}
if err = surv.RecordAnswerRaw(userId, customQuestionId, message.Text, "line"); err != nil {
log.Error(err)
break
}
if replyText != "" {
replyTextMsg, err := templateCustomQuestionReply(replyText, userId, s)
if err != nil {
log.Error(err)
break
}
log.WithFields(log.Fields{
"UserId": userId,
}).Infof("Sending custom question reply text")
if _, err = bot.PushMessage(userId, linebot.NewTextMessage(replyTextMsg)).Do(); err != nil {
log.Error(err)
}
}
} else {
answer, err := surv.RecordAnswer(userId, message.Text, "line")
if err != nil {
log.Error(err)
break
}
if answer.QuestionId == "price" {
err = sendPriceList(bot, s, userId)
if err != nil {
log.Error(err)
}
}
question, err := surv.GetNextQuestion(userId, questionTplVars)
if err != nil {
log.Error(err)
break
}
if _, err = bot.PushMessage(userId, linebot.NewTextMessage(question.Text)).Do(); err != nil {
log.Error(err)
}
}
}
}
}
return nil
}
}
func onUnfollow(userId string, s *storage.Sql) error {
p, err := s.GetUserProfile(userId)
if err != nil {
return err
}
p.Active = false
p.SurveyStarted = false
return s.UpdateUserProfile(p)
}
func templateCustomQuestionReply(msgTpl, userId string, s *storage.Sql) (msg string, err error) {
loc, err := s.FindUserLocation(userId)
if err != nil {
return "", err
}
if loc.NameThai == "" {
log.Warnf("could not find location for user id \"%s\"", userId)
}
priceList, err := userPriceList(userId, s)
if err != nil {
return "", err
}
tpl, err := template.New("customQuestionReply").Parse(msgTpl)
if err != nil {
return "", err
}
type TplVars struct {
PriceList string
Location string
}
buf := new(bytes.Buffer)
tplVars := TplVars{
Location: loc.NameThai,
PriceList: priceList,
}
err = tpl.Execute(buf, tplVars)
if err != nil {
return "", err
}
return buf.String(), nil
}
func sendWelcomeMsgs(userId string, bot *linebot.Client, s *storage.Sql, globalVars *domain.GlobalTplVars) error {
welcomeTplVars := &storage.WelcomeMsgTplVars{
UserId: userId,
Hostname: globalVars.Hostname,
}
welcomeMsgs, err := s.GetWelcomeMsgs(welcomeTplVars)
if err != nil {
return err
}
for _, welcomeMsg := range welcomeMsgs {
// check if the message is a video one
isVideoMsg, _ := regexp.MatchString(".*.mp4", welcomeMsg)
if isVideoMsg {
vidMsgRegex := regexp.MustCompile("\\|")
vidAndPreview := vidMsgRegex.Split(welcomeMsg, -1)
if len(vidAndPreview) != 2 {
return errors.New(fmt.Sprintf("Unexpected video message format. Got: \"%s\"", welcomeMsg))
}
if _, err := bot.PushMessage(userId, linebot.NewVideoMessage(vidAndPreview[0], vidAndPreview[1])).Do(); err != nil {
return err
}
continue
}
// check if the message is a button one
isWebSurveyBtn, _ := regexp.MatchString("web-survey-btn", welcomeMsg)
if isWebSurveyBtn {
cfg, err := s.GetWebSurveyBtnConfig()
if err != nil {
return err
}
surveyUrl := globalVars.Hostname + "/?uid=" + userId
action := linebot.NewURITemplateAction(cfg.Label, surveyUrl)
buttonTemplate := &linebot.ButtonsTemplate{
Title: cfg.Title,
Text: cfg.Text,
Actions: []linebot.TemplateAction{action},
}
if len(cfg.ImageName) > 0 {
buttonTemplate.ThumbnailImageURL = globalVars.Hostname + "/lineimgs/" + cfg.ImageName
}
altText := cfg.Title
if altText == "" {
altText = "Groots"
}
buttonMsg := linebot.NewTemplateMessage(altText, buttonTemplate)
if _, err = bot.PushMessage(userId, buttonMsg).Do(); err != nil {
return err
}
continue
}
if _, err := bot.PushMessage(userId, linebot.NewTextMessage(welcomeMsg)).Do(); err != nil {
return err
}
}
return nil
}