# 在 raspberry pi 4 上建立 LINE Bot
### 創建機器人帳號
到 LINE Developers 官方網站申請一隻機器人帳號
取得 Channel access token、Channel secret
>建立帳號詳細可參考以下連結教學
>---
>[卡米狗 LINE Bot](https://ithelp.ithome.com.tw/articles/10192928)
>[LINE BOT SDK:註冊](https://ithelp.ithome.com.tw/articles/10216620)
### 在 raspberry pi 4 上架設網頁
Step 1. 安裝所需套件
於終端機輸入以下指令:
1. 安裝 Flask:
`pip3 install Flask`
2. 安裝 LINE Bot SDK:
`pip3 install line-bot-sdk`
Step 2. 主程式碼(app.py)
```python=
from __future__ import unicode_literals
from typing import Text
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
from linebot.models import MessageEvent, TextMessage, TextSendMessage
app = Flask(__name__)
# LINE 聊天機器人的基本資料
line_bot_api = LineBotApi('你的Channel access token')
handler = WebhookHandler('你的Channel secret')
# 接收 LINE 的資訊
@app.route("/callback", methods=['POST'])
def callback():
signature = request.headers['X-Line-Signature']
body = request.get_data(as_text=True)
app.logger.info("Request body: " + body)
try:
handler.handle(body, signature)
except InvalidSignatureError:
abort(400)
return 'OK'
# 接收訊息的路由
@handler.add(MessageEvent, message=TextMessage)
def reply_message(event):
line_bot_api.reply_message(
event.reply_token,
TextSendMessage(text=event.message.text)
)
if __name__ == "__main__":
app.run()
```
完成後在終端機按下執行,可看到 app 運行的 port(預設為 5000)
### 使用 ngrok 將 raspberry pi 4 與外網連接
step 1. 於 raspberry pi 4 安裝 ngrok
在終端機中輸入:
`sudo wget https://bin.equinox.io/c/4VmDzA7iaHb/ngrok-stable-linux-arm.zip`
step 2. 解壓縮檔案
在終端機中輸入:
`sudo unzip ngrok-stable-linux-arm.zip`
step 3. 註冊並登入 [ngrok](https://ngrok.com/) 網站
step 4. 登入後選擇側欄 **Your Authtoken**
按下 copy 取得 Authtoken

step 5. 使用 Authtoken 連線
在終端機中輸入:
`./ngrok authtoken "你的Authtoken"`
接著在終端機中輸入:
`./ngrok http 5000`
會看到以下畫面:

step 6. 連接 Webhook
複製 fowarding 的網址,前往 [LINE Developers 官方網站](
https://developers.line.biz/)
點擊你的機器人帳號,進入設定選擇 Messaging API,輸入剛剛複製的網址,並加上 "/callback":

點擊 Verify 後即可連接完成。
## References
1. [【 Tools 】外部網路存取 Raspberry Pi (learningsky.io)](https://learningsky.io/access-raspberry-pi-from-outside-network/)
2. [六小時AIoT專題實作:樹莓派管家. feat. LINE Messaging API & OLAMI… | by Phil Alive | 十百千實驗室 | Medium](https://medium.com/%E5%8D%81%E7%99%BE%E5%8D%83%E5%AF%A6%E9%A9%97%E5%AE%A4/%E5%85%AD%E5%B0%8F%E6%99%82aiot%E5%B0%88%E9%A1%8C%E5%AF%A6%E4%BD%9C-%E6%A8%B9%E8%8E%93%E6%B4%BE%E7%AE%A1%E5%AE%B6-39fddf4b949c)
3. [LINE BOT 實作 - 在樹莓派上架設linebot @ 松桓科技-敏健的部落格 :: 痞客邦 :: (pixnet.net)](https://mrsitdownplz.pixnet.net/blog/post/403024232-line-bot-%E5%AF%A6%E4%BD%9C---%E5%9C%A8%E6%A8%B9%E8%8E%93%E6%B4%BE%E4%B8%8A%E6%9E%B6%E8%A8%ADlinebot)
4. [【Chatbot】(全圖文說明) ngrok 本地伺服器設定方法 - LINE bot local server (wongwonggoods.com)](https://www.wongwonggoods.com/python/linebot-local-server-ngork/)