106 lines
2.1 KiB
Go
106 lines
2.1 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"encoding/json"
|
|
"fmt"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/line/line-bot-sdk-go/v7/linebot"
|
|
"github.com/rs/zerolog/log"
|
|
)
|
|
|
|
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)
|
|
}
|
|
if event.Type == linebot.EventTypeMessage {
|
|
controller(event)
|
|
}
|
|
}
|
|
|
|
OK(c, "ok")
|
|
}
|
|
|
|
func controller(event *linebot.Event) {
|
|
|
|
msg, ok := event.Message.(*linebot.TextMessage)
|
|
if !ok {
|
|
log.Error().Msg("controller not impemented")
|
|
return
|
|
}
|
|
Hit(msg.Text, event.Source.UserID)
|
|
|
|
switch {
|
|
case msg.Text == "我的保單":
|
|
ApiMyOrders(event)
|
|
case strings.HasPrefix(msg.Text, "幫我介紹"):
|
|
|
|
default:
|
|
// route to watson
|
|
if err := watson(event); err != nil {
|
|
log.Error().Caller().Err(err).Msg("watson error")
|
|
}
|
|
}
|
|
|
|
}
|
|
|
|
func watson(event *linebot.Event) error {
|
|
input, _ := event.Message.(*linebot.TextMessage)
|
|
payload := fmt.Sprintf(`{"input":{"text": "%v"}}`, input.Text)
|
|
|
|
url := fmt.Sprintf("https://api.jp-tok.assistant.watson.cloud.ibm.com/instances/%v/v2/assistants/%v/message?version=2022-06-14",
|
|
IBM_INSTANCE, IBM_ASSISTANT)
|
|
req, err := http.NewRequest("POST", url, bytes.NewReader([]byte(payload)))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
req.Header.Set("Content-Type", "application/json")
|
|
req.Header.Set("Authorization", IBM_API)
|
|
client := &http.Client{
|
|
Timeout: time.Second * 10,
|
|
}
|
|
res, err := client.Do(req)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
defer res.Body.Close()
|
|
data, err := ioutil.ReadAll(res.Body)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
resData := struct {
|
|
Output struct {
|
|
Generic []struct {
|
|
Text string `json:"text"`
|
|
} `json:"generic"`
|
|
} `json:"output"`
|
|
}{}
|
|
json.Unmarshal(data, &resData)
|
|
|
|
var msg *linebot.TextMessage
|
|
if len(resData.Output.Generic) > 0 {
|
|
msg = linebot.NewTextMessage(resData.Output.Generic[0].Text)
|
|
} else {
|
|
msg = DefaultMsg()
|
|
}
|
|
|
|
_, err = SendMessage(event.ReplyToken, event.Source.UserID, msg)
|
|
return err
|
|
}
|