talent/setup_line.go

90 lines
1.8 KiB
Go

package main
import (
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/line/line-bot-sdk-go/v7/linebot"
"github.com/rs/zerolog/log"
)
var bot *linebot.Client
func setupLine() {
var err error
bot, err = linebot.New(LINE_SECRET, LINE_TOKEN)
if err != nil {
panic(err)
}
}
func webhook(c *gin.Context) {
events, err := bot.ParseRequest(c.Request)
if err != nil {
panic(err)
}
if flagDev {
data, _ := json.MarshalIndent(events, "", " ")
fmt.Println(string(data))
}
for _, event := range events {
if event.Type == linebot.EventTypeFollow {
Follow(event)
}
}
OK(c, "ok")
}
func Follow(event *linebot.Event) {
// add user
uid := event.Source.UserID
usr := &User{
ID: uid,
}
Hit("加入", uid)
reply := event.ReplyToken
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.")
msg := linebot.NewTextMessage("你好!")
if reply != "" {
if _, err := bot.ReplyMessage(reply, msg).Do(); err != nil {
log.Error().Err(err).Caller().Msg("reply error")
}
} else {
if _, err := bot.PushMessage(uid, msg).Do(); err != nil {
log.Error().Err(err).Caller().Msg("push error")
}
}
} else {
// 舊用戶
log.Debug().Str("user", uid).Msg("user unblocked.")
msg := linebot.NewTextMessage("歡迎回來!")
if reply != "" {
if _, err := bot.ReplyMessage(reply, msg).Do(); err != nil {
log.Error().Err(err).Caller().Msg("reply error")
}
} else {
if _, err := bot.PushMessage(uid, msg).Do(); err != nil {
log.Error().Err(err).Caller().Msg("push error")
}
}
}
// Welcome and ask for
}