Skip to content

Instantly share code, notes, and snippets.

@k2wanko k2wanko/app.go
Last active Feb 4, 2017

Embed
What would you like to do?
package linebot
import (
"encoding/base64"
"encoding/json"
"net/http"
"net/url"
"os"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/log"
"google.golang.org/appengine/taskqueue"
"google.golang.org/appengine/urlfetch"
"github.com/joho/godotenv"
"github.com/line/line-bot-sdk-go/linebot"
"github.com/line/line-bot-sdk-go/linebot/httphandler"
)
var botHandler *httphandler.WebhookHandler
func init() {
err := godotenv.Load("line.env")
if err != nil {
panic(err)
}
botHandler, err = httphandler.New(
os.Getenv("LINE_BOT_CHANNEL_SECRET"),
os.Getenv("LINE_BOT_CHANNEL_TOKEN"),
)
botHandler.HandleEvents(handleCallback)
http.Handle("/callback", botHandler)
http.HandleFunc("/task", handleTask)
}
// Webhook を受け取って TaskQueueに詰める関数
func handleCallback(evs []*linebot.Event, r *http.Request) {
c := appengine.NewContext(r)
ts := make([]*taskqueue.Task, len(evs))
for i, e := range evs {
j, err := json.Marshal(e)
if err != nil {
log.Errorf(c, "json.Marshal: %v", err)
return
}
data := base64.StdEncoding.EncodeToString(j)
t := taskqueue.NewPOSTTask("/task", url.Values{"data": {data}})
ts[i] = t
}
taskqueue.AddMulti(c, ts, "")
}
// 受け取ったメッセージを処理する関数
func handleTask(w http.ResponseWriter, r *http.Request) {
c := appengine.NewContext(r)
data := r.FormValue("data")
if data == "" {
log.Errorf(c, "No data")
return
}
j, err := base64.StdEncoding.DecodeString(data)
if err != nil {
log.Errorf(c, "base64 DecodeString: %v", err)
return
}
e := new(linebot.Event)
err = json.Unmarshal(j, e)
if err != nil {
log.Errorf(c, "json.Unmarshal: %v", err)
return
}
bot, err := newLINEBot(c)
if err != nil {
log.Errorf(c, "newLINEBot: %v", err)
return
}
log.Infof(c, "EventType: %s\nMessage: %#v", e.Type, e.Message)
var msg linebot.Message = linebot.NewTextMessage("ok")
switch m := e.Message.(type) {
case *linebot.TextMessage:
msg = linebot.NewTextMessage(m.Text)
if m.Text == "スタンプ" {
msg = &linebot.StickerMessage{
PackageID: "1",
StickerID: "1",
}
}
}
if _, err = bot.ReplyMessage(e.ReplyToken, msg).WithContext(c).Do(); err != nil {
log.Errorf(c, "ReplayMessage: %v", err)
return
}
w.WriteHeader(200)
}
func newLINEBot(c context.Context) (*linebot.Client, error) {
return botHandler.NewClient(
linebot.WithHTTPClient(urlfetch.Client(c)),
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.