talent/api_join.go

80 lines
2.0 KiB
Go

package main
import (
"fmt"
"strings"
"time"
"github.com/line/line-bot-sdk-go/v7/linebot"
"github.com/rs/zerolog/log"
)
func Follow(event *linebot.Event) {
// add user
uid := event.Source.UserID
usr := &User{
ID: uid,
}
Hit("加入", uid)
row := DB.Exec("select id from users where id = ?", uid).RowsAffected
if row == 0 {
// 新用戶
if err := DB.Create(usr).Error; err != nil {
log.Error().Err(err).Msg("Follow error.")
return
}
log.Debug().Str("user", uid).Msg("New user.")
} else {
// 舊用戶
log.Debug().Str("user", uid).Msg("user unblocked.")
}
// Welcome and ask for profile
msg := linebot.NewTextMessage("歡迎使用台新人壽智慧聊天服務! 請您協助核對您的身分。")
// get profiles
var profs []Profile
DB.Limit(10).Find(&profs)
columns := make([]*linebot.CarouselColumn, len(profs))
for i, prof := range profs {
columns[i] = linebot.NewCarouselColumn(
prof.Img, prof.Name, prof.Brief,
linebot.NewPostbackAction("我是"+prof.Name, "select="+prof.Name, "我是"+prof.Name, ""),
)
}
template := linebot.NewCarouselTemplate(columns...)
profiles := linebot.NewTemplateMessage("請核對您的身分", template)
if _, err := SendMessage(event.ReplyToken, uid, msg, profiles); err != nil {
panic(err)
}
}
func ApiSelectProfile(event *linebot.Event) {
uid := event.Source.UserID
data := event.Postback.Data
data = strings.TrimPrefix(data, "select=")
prof := &Profile{}
if err := DB.First(prof, "name = ?", data).Error; err != nil {
panic(err)
}
DB.Exec("update users set profile_id = ? where id = ?",
prof.ID, uid)
greet := linebot.NewTextMessage(fmt.Sprintf("歡迎回來! %v", data))
msg := linebot.NewStickerMessage("6325", "10979904")
if _, err := SendMessage(event.ReplyToken, event.Source.UserID,
greet, msg); err != nil {
panic(err)
}
go func(uid string) {
time.Sleep(time.Second * 3)
if _, err := SendMessage("", uid, DefaultMsg()); err != nil {
panic(err)
}
}(event.Source.UserID)
}