-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_bot.go
322 lines (285 loc) · 9.86 KB
/
api_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
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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package main
import (
"database/sql"
"log"
"net/http"
"strings"
_ "github.com/go-sql-driver/mysql"
"github.com/line/line-bot-sdk-go/linebot"
)
// LinkCustomer : A chatbot DB to store account link information.
type LinkCustomer struct {
//Data from CustData from provider.
ID string
Name string
Nounce string
LinkUserID string
userID string
}
type OrderList struct {
//Data from CustData from provider.
brandId string
orderStatus string
fullName string
totalPrice string
brandName string
}
// var orderLists []OrderList
var linkedCustomers []LinkCustomer
func callbackHandler(w http.ResponseWriter, r *http.Request) {
events, err := bot.ParseRequest(r)
if err != nil {
if err == linebot.ErrInvalidSignature {
w.WriteHeader(400)
} else {
w.WriteHeader(500)
}
return
}
db, err := sql.Open("mysql", "")
if err != nil {
panic(err.Error())
}
defer db.Close()
for _, event := range events {
if event.Type == linebot.EventTypeMessage {
switch message := event.Message.(type) {
case *linebot.TextMessage:
var userID string
if event.Source != nil {
userID = event.Source.UserID
}
switch {
case strings.EqualFold(message.Text, "#link"):
//token link
//1. The bot server calls the API that issues a link token from the LINE user ID.
//2. The LINE Platform returns the link token to the bot server.
res, err := bot.IssueLinkToken(userID).Do()
if err != nil {
log.Println("Issue link token error, err=", err)
}
log.Println("Get user token:", res.LinkToken)
//3. The bot server calls the Messaging API to send a linking URL to the user.
//4. The LINE Platform sends a linking URL to the user.
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage("點擊連結以綁定帳號: "+serverURL+"link?linkToken="+res.LinkToken)).Do(); err != nil {
log.Println("err:", err)
}
case strings.EqualFold(message.Text, "#unlink"):
for _, usr := range linkedCustomers {
rs, err := db.Query("SELECT `userId` FROM linebot WHERE `username` = ?", usr.ID)
if err != nil {
panic(err.Error())
}
defer rs.Close()
var ur LinkCustomer
for rs.Next() {
rs.Scan(&ur.userID)
}
log.Println("USERID:" + ur.userID)
if ur.userID == event.Source.UserID {
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage("您已成功取消綁定帳號!")).Do(); err != nil {
log.Println("err:", err)
}
log.Println("before_USERID:" + usr.LinkUserID)
_, err := db.Exec("DELETE FROM `linebot` WHERE `username` = ?", usr.ID)
if err != nil {
log.Println("exec failed:", err)
return
}
usr.LinkUserID = ""
usr.Nounce = ""
ur.userID = ""
userID = ""
usr.Name = ""
return
}
}
case strings.EqualFold(message.Text, "#order"):
for _, usr := range linkedCustomers {
rs, err := db.Query("SELECT `userId` FROM linebot WHERE `username` = ?", usr.ID)
if err != nil {
panic(err.Error())
}
defer rs.Close()
var urdf LinkCustomer
for rs.Next() {
rs.Scan(&urdf.userID)
}
if urdf.userID == event.Source.UserID {
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage("查詢訂單").
WithQuickReplies(linebot.NewQuickReplyItems(
linebot.NewQuickReplyButton(
"",
linebot.NewMessageAction("訂單", "#orderList")),
)),
).Do(); err != nil {
log.Println("err:", err)
return
}
}
}
case strings.EqualFold(message.Text, "#orderList"):
for _, usr := range linkedCustomers {
Doc := ""
rs, err := db.Query("SELECT `userId` FROM `linebot` WHERE `username` = ?", usr.ID)
if err != nil {
panic(err.Error())
}
defer rs.Close()
var udr LinkCustomer
for rs.Next() {
rs.Scan(&udr.userID)
}
if udr.userID == event.Source.UserID {
//取得訂單資料
rs, err := db.Query("SELECT `brandId`, `orderStatus`, `fullName`, `totalPrice` FROM `orderList` WHERE `username` = ? AND (`orderStatus` = 'isReceived' OR `orderStatus` = 'isPreparing') ORDER BY `needTime` DESC", usr.ID)
if err != nil {
panic(err.Error())
}
defer rs.Close()
for rs.Next() {
var or OrderList
//取得店家名稱
rs.Scan(&or.brandId, &or.orderStatus, &or.fullName, &or.totalPrice)
if or.orderStatus == "isReceived" {
or.orderStatus = "已接收"
} else {
or.orderStatus = "準備中"
}
res, err := db.Query("SELECT `brandName` FROM `ownerDetails` WHERE `brandId` = ?", or.brandId)
if err != nil {
panic(err.Error())
}
defer res.Close()
for res.Next() {
res.Scan(&or.brandName)
}
// log.Println("店家:" + or.brandName + "\n訂單狀態:" + or.orderStatus + "\n訂購人:" + or.fullName + "\n總金額:NT# " + or.totalPrice)
if Doc == "" {
Doc = "店家:" + or.brandName + "\n訂單狀態:" + or.orderStatus + "\n訂購人:" + or.fullName + "\n總金額:NT# " + or.totalPrice
} else {
Doc = Doc + "\n\n店家:" + or.brandName + "\n訂單狀態:" + or.orderStatus + "\n訂購人:" + or.fullName + "\n總金額:NT# " + or.totalPrice
}
}
log.Println(Doc)
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage(Doc)).Do(); err != nil {
log.Println("err:", err)
return
}
return
}
}
//Check user if it is linked.
for _, usr := range linkedCustomers {
rs, err := db.Query("SELECT `userId`, `name` FROM linebot WHERE `username` = ?", usr.ID)
if err != nil {
panic(err.Error())
}
defer rs.Close()
var urf LinkCustomer
for rs.Next() {
rs.Scan(&urf.userID, &urf.Name)
}
if urf.LinkUserID == event.Source.UserID {
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage("你好 "+urf.Name+",您已成功綁定帳號!")).Do(); err != nil {
log.Println("err:", err)
return
}
return
}
}
log.Println("source:>>>", event.Source, " group:>>", event.Source.GroupID, " room:>>", event.Source.RoomID)
case strings.EqualFold(message.Text, "#account"):
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage("歡迎使用Foodler BOT,請先綁定帳號,以使用完整功能!").
WithQuickReplies(linebot.NewQuickReplyItems(
linebot.NewQuickReplyButton(
"",
linebot.NewMessageAction("綁定帳號", "#link")),
linebot.NewQuickReplyButton(
"",
linebot.NewMessageAction("解除綁定", "#unlink")),
)),
).Do(); err != nil {
log.Println("err:", err)
return
}
case strings.EqualFold(message.Text, "#news"):
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage("您可以在Foodler進行查詢訂單功能!")).Do(); err != nil {
log.Println("err:", err)
return
}
case strings.EqualFold(message.Text, "#recommend"):
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage("進入目錄後,點擊推薦按鈕即可邀請好友!")).Do(); err != nil {
log.Println("err:", err)
}
}
}
} else if event.Type == linebot.EventTypeAccountLink {
log.Println("EventTypeAccountLink: source=", event.Source, " result=", event.AccountLink.Result)
for _, user := range linkedCustomers {
rs, err := db.Query("SELECT `userId`, `name` FROM linebot WHERE `username` = ?", user.ID)
if err != nil {
panic(err.Error())
}
// log.Println("USERID:" + usr.)
var ur LinkCustomer
for rs.Next() {
rs.Scan(&ur.userID, &ur.Name)
}
if ur.userID == event.Source.UserID {
log.Println("使用者: ", ur.Name, " 的帳號已被綁定!")
return
}
}
//search from all user using nounce.
for _, usr := range customers {
//12. The bot server uses the nonce to acquire the user ID of the provider's service.
if usr.Nounce == event.AccountLink.Nonce {
//Append to linked DB.
USERID := event.Source.UserID
rs, err := db.Exec("UPDATE `linebot` SET `userId`= ? WHERE `nounce` = ?", USERID, usr.Nounce)
if err != nil {
log.Println("exec failed:", err)
return
}
log.Println("update data successd:", rs)
results, err := db.Query("SELECT `username`, `nounce`, `userId`, `name` FROM `linebot` WHERE `nounce` = ?", usr.Nounce)
if err != nil {
panic(err.Error())
}
defer results.Close()
var linkedUser LinkCustomer
for results.Next() {
results.Scan(&linkedUser.ID, &linkedUser.Nounce, &linkedUser.LinkUserID, &linkedUser.Name)
linkedCustomers = append(linkedCustomers, linkedUser)
}
log.Println("Username:" + linkedUser.ID + "\nNounce:" + linkedUser.Nounce + "\nUserId:" + linkedUser.LinkUserID + "\nName:" + linkedUser.Name)
if _, err = bot.ReplyMessage(
event.ReplyToken,
linebot.NewTextMessage("你好,"+linkedUser.Name+",您的帳號已成功綁定!")).Do(); err != nil {
log.Println("err:", err)
return
}
return
}
}
log.Println("Error: no such user:", event.Source.UserID, " nounce=", event.AccountLink.Nonce, " for account link.")
}
}
}