LineBot API串接

使用nodeJS 和 Express 套件架設基礎的http服務。並串接line-bot message API。 實作功能:line官方帳號訊息回覆和紀錄、推播文字和圖片訊息。
demoopen in new window

API docsopen in new window

Message Hook

info

1.官方範例是啟一個express app應來並且監聽https的Post /callback,來接收官方line所收到的訊息。 2.串接line bot message API 需要使用https連線方式 本地開發時,借助ngrok可以建立一個對外的https url 指向給本地的服務對外使用

line bot sdk模組與使用

const line = require("@line/bot-sdk");
const config = {
  channelAccessToken: "來自line developer",
  channelSecret: "來自line developer",
};
const client = new line.Client(config);
// 此client物件可用來回傳訊息

監聽 Post /callback

app.post("/callback", line.middleware(config), (req, res) => {
  Promise.all(req.body.events.map(handleEvent))
    .then((result) => res.json(result))
    .catch((err) => {
      console.error(err);
      res.status(500).end();
    });
});

info

當有line訊息傳給官方line後,需要在line developer設定設有監聽服務的地址 本次實作的例子 Webhook URL 是設置為 https://line-bot-doope.herokuapp.com/callback

圖片推播

參考官方Message API 文件的圖片訊息格式,可以加入靜態資源(圖片)的url 同在express app 做http GET的監聽,並利用express app的res.sendFile()傳送圖檔

info

利用nodeJS 架設能提供靜態資源服務的應用

express API 官方文件 res.sendFileopen in new window


連結

完整程式碼open in new window

豆皮官方line 管理台open in new window

line developer //開發者管理API服務open in new window

使用Node.js建置你的第一個LINE BOTopen in new window讓本地https 服務指向localhost:portopen in new window

官方line bot nodeJS範例open in new window