github.com/line/line-bot-sdk-go/v7@v7.21.0/examples/echo_bot/server.go (about)

     1  // Copyright 2016 LINE Corporation
     2  //
     3  // LINE Corporation licenses this file to you under the Apache License,
     4  // version 2.0 (the "License"); you may not use this file except in compliance
     5  // with the License. You may obtain a copy of the License at:
     6  //
     7  //   http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
    11  // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
    12  // License for the specific language governing permissions and limitations
    13  // under the License.
    14  
    15  package main
    16  
    17  import (
    18  	"fmt"
    19  	"log"
    20  	"net/http"
    21  	"os"
    22  
    23  	"github.com/line/line-bot-sdk-go/v7/linebot"
    24  )
    25  
    26  func main() {
    27  	bot, err := linebot.New(
    28  		os.Getenv("CHANNEL_SECRET"),
    29  		os.Getenv("CHANNEL_TOKEN"),
    30  	)
    31  	if err != nil {
    32  		log.Fatal(err)
    33  	}
    34  
    35  	// Setup HTTP Server for receiving requests from LINE platform
    36  	http.HandleFunc("/callback", func(w http.ResponseWriter, req *http.Request) {
    37  		events, err := bot.ParseRequest(req)
    38  		if err != nil {
    39  			if err == linebot.ErrInvalidSignature {
    40  				w.WriteHeader(400)
    41  			} else {
    42  				w.WriteHeader(500)
    43  			}
    44  			return
    45  		}
    46  		for _, event := range events {
    47  			if event.Type == linebot.EventTypeMessage {
    48  				switch message := event.Message.(type) {
    49  				case *linebot.TextMessage:
    50  					if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(message.Text)).Do(); err != nil {
    51  						log.Print(err)
    52  					}
    53  				case *linebot.StickerMessage:
    54  					replyMessage := fmt.Sprintf(
    55  						"sticker id is %s, stickerResourceType is %s", message.StickerID, message.StickerResourceType)
    56  					if _, err = bot.ReplyMessage(event.ReplyToken, linebot.NewTextMessage(replyMessage)).Do(); err != nil {
    57  						log.Print(err)
    58  					}
    59  				}
    60  			}
    61  		}
    62  	})
    63  	// This is just sample code.
    64  	// For actual use, you must support HTTPS by using `ListenAndServeTLS`, a reverse proxy or something else.
    65  	if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
    66  		log.Fatal(err)
    67  	}
    68  }