--- tags: 第三方串接 --- # Line bot 部署到 Heroku ## 建立 Line bot channel 1. 登入 [Line 開發人員網站](https://developers.line.biz/zh-hant/) 2. 新建 provider (公司、品牌等的群組,可邀請多位成員,底下包含多個 channel) 3. 新建 channel (Line 應用程式,目前有 登入、訊息、語音助理、區塊鏈 四種功能) - channel 不可包含 `Line` 字樣 - App types 選擇 `Messaging API` - 選填可先跳過 --- ## 建立專案 ```bash= mkdir your_proj_name cd your_proj_name npm init ``` ### 安裝所需套件 ```bash= npm i --save linebot express ``` - **linebot** SDK for the LINE Messaging API for Node.js - **express** Node.js server 模組 ### `.gitignore` ``` node_modules/ ``` ### `package.json` heroku 預設執行 `npm run start` ```json= "scripts": { + "start": "node ." } ``` ### 同步至 Github --- ## 本機安裝 Heroku CLI (Mac OS) ```bash brew install heroku/brew/heroku ``` --- ## 建立 Heroku App 1. heroku app 網站上選擇跟 Github repo 連結,並設定自動同步 2. heroku app 網站上的 `Settings` -> `Config Vars` 設定 `.env` 環境變數 也可以透過 terminal 在專案進行設定 ```bash heroku config:set CHANNEL_ACCESS_TOKEN=your_channel_access_token heroku config:set CHANNEL_ID=your_channel_id heroku config:set CHANNEL_SECRET=your_channel_secret ``` 3. 將 heroku app 網址填入 Line APP 的 `Webhook URL` 並啟用及取消自動回應 --- ## 範例程式碼 ```javascript= const linebot = require('linebot'); const express = require('express'); const bot = linebot({ channelId: process.env.CHANNEL_ID, channelSecret: process.env.CHANNEL_SECRET, channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN }); const app = express(); const linebotParser = bot.parser(); app.post('/', linebotParser); // 當有人傳送訊息給 Bot 時 bot.on('message', event => { // 回覆訊息給使用者 (一問一答所以是回覆不是推送) event.reply(`你說了 ${event.message.text}`); }); //因為 express 預設走 port 3000,而 heroku 上預設卻不是,要透過下列程式轉換 const server = app.listen(process.env.PORT || 8080, () => { const port = server.address().port; console.log("App now running on port", port); }); ``` --- ## 參考資料 - [linebot 套件](https://github.com/boybundit/linebot#readme) - [Node + Heroku 打造 Line 聊天機器人](https://medium.com/rd-tw/node-heroku-%E6%89%93%E9%80%A0-line-%E8%81%8A%E5%A4%A9%E6%A9%9F%E5%99%A8%E4%BA%BA-d81fe6dba1f) - [LINE BOT 實戰 ( 原理篇 )](https://www.oxxostudio.tw/articles/201701/line-bot.html)