(本文作者是ALPHA Camp全端Web App開發課程的學生 Gary Wu,文章轉載自他的部落格)
Line是台灣滲透率最高的通訊軟體,月活躍用戶超過2000萬。很多商家也開發Line聊天機器人,做自動化客服和資訊查詢的功能。ALPHA Camp全端開發的學生 Gary Wu 透過在AC學會的後端開發能力,自己著手研究如何開發出簡單的Line chatbot。這篇文章有詳細實作步驟指南,帶你做出自己的第一個Line聊天機器人。
為什麼要做 chatbot?
上個月去聽 LINE chatbot 的講座,聽完後,想試試看 chatbot 到底可以做到什麼程度,雖然是機械式的聊天,但應該可以達到某種效果!也許可以幫助我解決我現在遇到的一些問題。
開始吧
因為是 LINE 提供的服務,所以需要先到 LINE Develpers 登入及註冊。
先到 https://developers.line.biz/en/ 登入

登入後,註冊,填寫 Name 、Email,並發送信箱認證信

信箱認證完成 =>

選擇要使用的服務: Messaging API

Create new channel
Select provider:可以勾選已經存在的 provider,若沒有則新增一個 provider。
好了,就按 〈Next Page〉
輸入 provider name

完成相關資料輸入 => App icon、App name、Description、Category、 Subcategory、 Email address、 Privacy Policy URL、 Terms Of Use URL

Confirm:確認輸入資料正確性

channel 建立成功

更改 channel setting

Channel ID 及 Channel Secret 很重要,不要外洩!

這邊不用填 =>

最下面那個選項 Channel access token ,點選 Issue 可以產生 Channel access token

設定 Time until token 有效時間

點選 Issue ,產生 token,這串 token 可用於 專案中。需要用到時再來查詢也可以。

Messaging settings:
- Use webhooks 切換成 Enabled
- Webhook URL :先留空白,等建立 Webhook URL 後,再回頭設定

這邊不用設定,最下面有 chatbot 的 QR code ,用於加入好友。

點選 Set message 會連到 LINE official Account Manager,有下面幾個畫面:

主頁 可以設定:群發訊息、貼文串、加入好友的觀迎訊息、自動訊息……

到此,已完成 Channel 的基本設定。接下來,要建立 Webhook URL
建立 Webhook URL
建立專案資料夾
mkdir XXXXXX
建立 package.json
npm init -y
安裝套件 express、linebot
npm install express linebot dotenv
linebot 套件說明: https://www.npmjs.com/package/linebot
安裝後,package.json dependencies 多了二個套件 express、 linebot、dotenv

建立 app.js
const express = require(‘express’)
const app = express()const linebot = require(‘linebot’);// 判別開發環境
if (process.env.NODE_ENV !== ‘production’) { // 如果不是 production 模式
require(‘dotenv’).config() // 使用 dotenv 讀取 .env 檔案
}const bot = linebot({
channelId: process.env.CHANNEL_ID,
channelSecret: process.env.CHANNEL_SECRET,
channelAccessToken: process.env.CHANNEL_ACCESS_TOKEN
});
const linebotParser = bot.parser();bot.on(‘message’, function (event) {
console.log(event);event.reply(event.message.text).then(function (data) {
// success
}).catch(function (error) {
// error
});
});app.post(‘/’, linebotParser);app.listen(process.env.PORT || 3000, () => {
console.log(‘Express server start’)
});
佈署到 heroku
在專案資料夾新增名稱為 Procfile 的檔案
web: node app.js

如果電腦有安裝 heroku CLI,則可以於專案資料夾路徑執行下面指令:
heroku login
會與連結到 heroku 網站,點選 log in

再回到 CLI,已登入 heroku

建立一個 heroku app
heroku create
成功建立,左邊是 app 網址,右邊是 git push 位址
可用 git remote -v 指令來查詢

將專案 push heroku master
git push heroku master
push 後,會偵測哪一種語言撰寫的 app、建置 runtime environment、Installing binaries、Installing dependencies(相關套件)

Discover process type(因為我們在專案中有建立 Procfile,讀取到 web)、Compressing、Lauching 、發行版次

查看 heroku logs
heroku logs –tail

這裡出現二次同樣的錯誤訊息:使用 npm start 來啟動卻失敗

原因是,我們在 package.json 沒有在 scripts 中定義 start。
所以我們來更改 package.json 設定:在 scripts 中增加二個屬性 dev 及 start。開發時可以 npm run dev 來啟動 server ,佈署時至 heroku 後,heroku 會以 npm run start 來啟動 server。
“scripts”: {
“dev”: “nodemon app.js”,
“start”: “node app.js”,
“test”: “echo “Error: no test specified”” && exit 1″”
}