talent/setup_line.go

62 lines
1.0 KiB
Go
Raw Normal View History

2021-12-30 09:16:20 +00:00
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,
}
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.")
}
} else {
// 舊用戶
log.Debug().Str("user", uid).Msg("user unblocked.")
}
// Welcome and ask for
}