Skip to content

Commit

Permalink
Merge pull request #8 from kkdai/validate_and_search
Browse files Browse the repository at this point in the history
refactor: refactor error handling and database queries
  • Loading branch information
kkdai authored Jan 13, 2024
2 parents 1fb6cda + bd50e5e commit 109c6b8
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 96 deletions.
46 changes: 21 additions & 25 deletions bot.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ func callbackHandler(w http.ResponseWriter, r *http.Request) {
// Handle only image message
case webhook.ImageMessageContent:
log.Println("Got img msg ID:", message.Id)
var resultMSg string

//Get image binary from LINE server based on message ID.
data, err := GetImageBinary(blob, message.Id)
Expand All @@ -75,9 +76,14 @@ func callbackHandler(w http.ResponseWriter, r *http.Request) {
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)
Expand All @@ -98,25 +104,26 @@ func callbackHandler(w http.ResponseWriter, r *http.Request) {
Token: os.Getenv("NOTION_INTEGRATION_TOKEN"),
}

// 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[0])
resultMSg = "已經存在於資料庫中,請勿重複輸入"
}

if resultMSg == "" {
if err := replyText(e.ReplyToken, resultMSg+"\n"+jsonData); err != nil {
log.Print(err)
}
continue
}

err = nDB.AddPageToDatabase(person.Name, person.Title, person.Address, person.Email, person.PhoneNumber)
if err != nil {
log.Println("Error adding page to database:", err)
}

// Determine the push msg target.
if _, err := bot.ReplyMessage(
&messaging_api.ReplyMessageRequest{
ReplyToken: e.ReplyToken,
Messages: []messaging_api.MessageInterface{
&messaging_api.TextMessage{
Text: ret,
},
&messaging_api.TextMessage{
Text: jsonData,
},
},
},
); err != nil {
if err := replyText(e.ReplyToken, jsonData+"\n"+"新增到資料庫"); err != nil {
log.Print(err)
}

Expand Down Expand Up @@ -177,17 +184,6 @@ func GetImageBinary(blob *messaging_api.MessagingApiBlobAPI, messageID string) (
return data, nil
}

// extractJSONFromString takes a string that contains JSON with Markdown backticks and returns just the JSON string.
func extractJSONFromString(s string) string {
// Trim the leading and trailing backticks.
s = strings.Trim(s, "`")

// Trim leading and trailing whitespace that may be present after removing backticks.
s = strings.TrimSpace(s)

return s
}

// removeFirstAndLastLine takes a string and removes the first and last lines.
func removeFirstAndLastLine(s string) string {
// Split the string into lines.
Expand Down
102 changes: 33 additions & 69 deletions notion.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,17 +32,16 @@ type NotionDBEntry struct {
ImgURL string
}

// QueryDatabaseByTitleAndName 根據提供的標題和名稱查詢 Notion 資料庫。
func (n *NotionDB) QueryDatabaseByTitleAndName(name string) ([]NotionDBEntry, error) {
// QueryDatabase 根據提供的屬性和值查詢 Notion 資料庫。
func (n *NotionDB) QueryDatabase(property, value string) ([]NotionDBEntry, error) {
client := notionapi.NewClient(notionapi.Token(n.Token))

// 建立查詢過濾條件
filter := &notionapi.DatabaseQueryRequest{
Filter: &notionapi.PropertyFilter{
Property: "Name",
// Replace Text with the correct field based on the notionapi package's documentation or source code
Property: property,
RichText: &notionapi.TextFilterCondition{
Equals: name,
Equals: value,
},
},
}
Expand All @@ -56,46 +55,42 @@ func (n *NotionDB) QueryDatabaseByTitleAndName(name string) ([]NotionDBEntry, er
var entries []NotionDBEntry

for _, page := range result.Results {
entry := NotionDBEntry{}
entry := n.createEntryFromPage(&page)
entries = append(entries, entry)
}
return entries, nil
}

if prop, ok := page.Properties["Name"].(*notionapi.TitleProperty); ok && len(prop.Title) > 0 {
entry.Name = prop.Title[0].PlainText
}
// createEntryFromPage creates a NotionDBEntry from a page.
func (n *NotionDB) createEntryFromPage(page *notionapi.Page) NotionDBEntry {
entry := NotionDBEntry{}

if prop, ok := page.Properties["Title"].(*notionapi.RichTextProperty); ok && len(prop.RichText) > 0 {
entry.Title = prop.RichText[0].PlainText
}
entry.Name = n.getPropertyValue(page, "Name")
entry.Title = n.getPropertyValue(page, "Title")
entry.Address = n.getPropertyValue(page, "Address")
entry.Email = n.getPropertyValue(page, "Email")
entry.PhoneNumber = n.getPropertyValue(page, "Phone Number")

if prop, ok := page.Properties["Address"].(*notionapi.RichTextProperty); ok && len(prop.RichText) > 0 {
entry.Address = prop.RichText[0].PlainText
}

if prop, ok := page.Properties["Email"].(*notionapi.EmailProperty); ok {
entry.Email = prop.Email
}
return entry
}

if prop, ok := page.Properties["Phone Number"].(*notionapi.PhoneNumberProperty); ok {
entry.PhoneNumber = prop.PhoneNumber
}
// getPropertyValue gets the plain text value of a property from a page.
func (n *NotionDB) getPropertyValue(page *notionapi.Page, property string) string {
if prop, ok := page.Properties[property].(*notionapi.RichTextProperty); ok && len(prop.RichText) > 0 {
return prop.RichText[0].PlainText
}

if tagsProp, ok := page.Properties["Tags"].(*notionapi.MultiSelectProperty); ok {
for _, tag := range tagsProp.MultiSelect {
entry.Tags = append(entry.Tags, tag.Name)
}
}
return ""
}

if imgProp, ok := page.Properties["Img"].(*notionapi.FilesProperty); ok {
for _, file := range imgProp.Files {
if file.Type == "external" {
entry.ImgURL = file.External.URL
break
}
}
}
// QueryDatabaseByName 根據提供的標題和名稱查詢 Notion 資料庫。
func (n *NotionDB) QueryDatabaseByName(name string) ([]NotionDBEntry, error) {
return n.QueryDatabase("Name", name)
}

entries = append(entries, entry)
}
return entries, nil
// QueryDatabaseByEmail 根據提供的電子郵件地址查詢 Notion 資料庫。
func (n *NotionDB) QueryDatabaseByEmail(email string) ([]NotionDBEntry, error) {
return n.QueryDatabase("Email", email)
}

// AddPageToDatabase adds a new page with the provided field values to the specified Notion database.
Expand Down Expand Up @@ -144,39 +139,8 @@ func (n *NotionDB) AddPageToDatabase(name string, title string, address string,
},
},
},
// "Phone Number": notionapi.TextProperty{
// Text: []notionapi.RichText{
// {Text: &notionapi.Text{Content: phoneNumber}},
// },
// },
// ... 其他屬性依此類推
}

// // 如果 Tags 不為空,添加 Tags 屬性
// if len(tags) > 0 {
// multiSelect := make([]notionapi.Option, 0, len(tags))
// for _, tag := range tags {
// multiSelect = append(multiSelect, notionapi.Option{Name: tag})
// }
// properties["Tags"] = notionapi.MultiSelectProperty{MultiSelect: multiSelect}
// }

// 如果 ImgURL 不為空,添加 Img 屬性
// if imgURL != "" {
// properties["Img"] = notionapi.FilesProperty{
// Files: []notionapi.File{
// {
// Name: "image.jpg",
// Type: "notionapi.FileTypeImage",
// File: &notionapi.FileObject{
// URL: imgURL,
// ExpiryTime: nil, // or some time.Time value
// },
// },
// },
// }
// }

// 創建一個新頁面的請求
pageRequest := &notionapi.PageCreateRequest{
Parent: notionapi.Parent{
Expand Down
10 changes: 8 additions & 2 deletions notion_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,18 @@ func TestQueryNotionDB(t *testing.T) {
Token: token,
}

entries, err := db.QueryDatabaseByTitleAndName("22")
entries, err := db.QueryDatabaseByName("111")
if err != nil {
t.Fatal(err)
}
fmt.Printf("%+v\n", entries)

fmt.Printf("%+v", entries)
entries, err = db.QueryDatabaseByEmail("[email protected]")
if err != nil {
t.Fatal(err)
}

fmt.Printf("%+v\n", entries)
}

func TestAddNotionDB(t *testing.T) {
Expand Down

0 comments on commit 109c6b8

Please sign in to comment.