-
Notifications
You must be signed in to change notification settings - Fork 9
/
bot.go
262 lines (229 loc) · 7.19 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
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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"github.com/line/line-bot-sdk-go/v7/linebot"
"github.com/line/line-bot-sdk-go/v8/linebot/messaging_api"
"github.com/line/line-bot-sdk-go/v8/linebot/webhook"
)
// Const variables of Prompts.
const ImagePrompt = "這是一張名片,你是一個名片秘書。請將以下資訊整理成 json 給我。如果看不出來的,幫我填寫 N/A, 只好 json 就好: Name, Title, Address, Email, Phone, Company. 其中 Phone 的內容格式為 #886-0123-456-789,1234. 沒有分機就忽略 ,1234"
// replyText: Reply text message to LINE server.
func replyText(replyToken, text string) error {
if _, err := bot.ReplyMessage(
&messaging_api.ReplyMessageRequest{
ReplyToken: replyToken,
Messages: []messaging_api.MessageInterface{
&messaging_api.TextMessage{
Text: text,
},
},
},
); err != nil {
return err
}
return nil
}
// callbackHandler: Handle callback from LINE server.
func callbackHandler(w http.ResponseWriter, r *http.Request) {
card_prompt := os.Getenv("CARD_PROMPT")
if card_prompt == "" {
card_prompt = ImagePrompt
}
cb, err := webhook.ParseRequest(ChannelSecret, r)
if err != nil {
if err == linebot.ErrInvalidSignature {
w.WriteHeader(400)
} else {
w.WriteHeader(500)
}
return
}
for _, event := range cb.Events {
log.Printf("Got event %v", event)
switch e := event.(type) {
case webhook.MessageEvent:
switch message := e.Message.(type) {
// Handle only on text message
case webhook.TextMessageContent:
if message.Text == "test" {
cards := []Person{
{
Name: "test",
Title: "test",
Address: "test",
Email: "test",
Phone: "test",
},
}
if err := SendFlexMsg(e.ReplyToken, cards, "test card"); err != nil {
log.Print(err)
}
continue
}
// 取得用戶 ID
var uID string
switch source := e.Source.(type) {
case webhook.UserSource:
uID = source.UserId
case webhook.GroupSource:
uID = source.UserId
case webhook.RoomSource:
uID = source.UserId
}
log.Println("Got text msg ID:", message.Id, " UID:", uID)
//using test as keyword to query database
nDB := &NotionDB{
DatabaseID: os.Getenv("NOTION_DB_PAGEID"),
Token: os.Getenv("NOTION_INTEGRATION_TOKEN"),
UID: uID,
}
// Query the database with the provided uID and text
results, err := nDB.QueryDatabaseContains(message.Text)
log.Println("Got results:", results)
// If there's an error or no results, reply with an error message
if err != nil || len(results) == 0 {
ret := "查不到資料,請重新輸入"
if err != nil {
ret = fmt.Sprintf("%s: %s", ret, err.Error())
}
if err := replyText(e.ReplyToken, ret); err != nil {
log.Print(err)
}
continue
}
log.Println("Got results:", results)
err = SendFlexMsg(e.ReplyToken, results, "根據關鍵字查詢結果")
if err != nil {
log.Println("Error send result", err)
}
// Handle only on Sticker message
case webhook.StickerMessageContent:
// log sticker id and package id.
log.Printf("Got sticker message, packageID: %s, stickerID: %s", message.PackageId, message.StickerId)
// Handle only image message
case webhook.ImageMessageContent:
// 取得用戶 ID
var uID string
switch source := e.Source.(type) {
case webhook.UserSource:
uID = source.UserId
case webhook.GroupSource:
uID = source.UserId
case webhook.RoomSource:
uID = source.UserId
}
log.Println("Got img msg ID:", message.Id)
//Get image binary from LINE server based on message ID.
data, err := GetImageBinary(blob, message.Id)
if err != nil {
log.Println("Got GetMessageContent err:", err)
continue
}
// Chat with Image
ret, err := GeminiImage(data, card_prompt)
if err != nil {
ret = "無法辨識圖片內容文字,請重新輸入:" + err.Error()
if err := replyText(e.ReplyToken, ret); err != nil {
log.Print(err)
}
continue
}
log.Println("Got GeminiImage ret:", ret)
// Remove first and last line, which are the backticks.
jsonData := removeFirstAndLastLine(ret)
log.Println("Got jsonData:", jsonData)
// Parse json and insert NotionDB
var person Person
err = json.Unmarshal([]byte(jsonData), &person)
if err != nil {
log.Println("Error parsing JSON:", err)
}
nDB := &NotionDB{
DatabaseID: os.Getenv("NOTION_DB_PAGEID"),
Token: os.Getenv("NOTION_INTEGRATION_TOKEN"),
UID: uID,
}
// Check email first before adding to database.
dbUser, err := nDB.QueryDatabaseByEmail(person.Email)
if err == nil && len(dbUser) > 0 {
log.Println("Already exist in DB", dbUser)
if err := SendFlexMsg(e.ReplyToken, dbUser, "已經存在於資料庫中,請勿重複輸入"); err != nil {
log.Println("Error send result", err)
}
continue
}
// Add namecard to notion database.
err = nDB.AddPageToDatabase(person)
if err != nil {
log.Println("Error adding page to database:", err)
}
if err := SendFlexMsg(e.ReplyToken, []Person{person}, "新增到資料庫"); err != nil {
log.Println("Error send result", err)
}
// Handle only video message
case webhook.VideoMessageContent:
log.Println("Got video msg ID:", message.Id)
default:
log.Printf("Unknown message: %v", message)
}
case webhook.PostbackEvent:
log.Printf("Got postback: %v", e.Postback.Data)
case webhook.JoinEvent:
log.Printf("Got join event")
case webhook.FollowEvent:
log.Printf("message: Got followed event")
case webhook.BeaconEvent:
log.Printf("Got beacon: " + e.Beacon.Hwid)
}
}
}
// ProcessImage: Process an image and reply with a text.
func processImage(target, m_id, prompt, errMsg string, blob *messaging_api.MessagingApiBlobAPI) {
// Get image data
data, err := GetImageBinary(blob, m_id)
if err != nil {
log.Printf("Got GetMessageContent err: %v", err)
return
}
// Chat with Image
ret, err := GeminiImage(data, prompt)
if err != nil {
log.Printf("Got %s err: %v", errMsg, err)
return
}
// Determine the push msg target.
if err := replyText(target, ret); err != nil {
log.Print(err)
}
}
// GetImageBinary: Get image binary from LINE server based on message ID.
func GetImageBinary(blob *messaging_api.MessagingApiBlobAPI, messageID string) ([]byte, error) {
// Get image binary from LINE server based on message ID.
content, err := blob.GetMessageContent(messageID)
if err != nil {
log.Println("Got GetMessageContent err:", err)
}
defer content.Body.Close()
data, err := io.ReadAll(content.Body)
if err != nil {
log.Fatal(err)
}
return data, nil
}
// removeFirstAndLastLine takes a string and removes the first and last lines.
func removeFirstAndLastLine(s string) string {
// Split the string into lines.
lines := strings.Split(s, "\n")
// If there are less than 3 lines, return an empty string because removing the first and last would leave nothing.
if len(lines) < 3 {
return ""
}
// Join the lines back together, skipping the first and last lines.
return strings.Join(lines[1:len(lines)-1], "\n")
}