---
# System prepended metadata

title: AI LINE Bot練功坊-L4 Echo Bot製作
tags: [Python, Line Bot]

---

AI LINE Bot練功坊-L4 Echo Bot製作
===
## 1. 選擇運行環境



### **開啟並新增檔案**
* 用Visual Studio Code開啟專案資料夾
![image](https://hackmd.io/_uploads/Hk0bsVm06.png)

* 開啟後新增一個附檔名為.py的python檔案
![image](https://hackmd.io/_uploads/S1j-uIbRa.png)

    ![image](https://hackmd.io/_uploads/SyMPuIZ0p.png)

### **選擇上次建立的虛擬環境**
* 點擊右下角切換環境
![image](https://hackmd.io/_uploads/ByLXFUZCa.png)

* 點擊輸入環境路徑
![image](https://hackmd.io/_uploads/BkJFFLWA6.png)

* 繼續點擊即可從檔案系統尋找資料夾
![image](https://hackmd.io/_uploads/S1YjKLZCT.png)

* 尋找上次建立環境的資料夾
![image](https://hackmd.io/_uploads/Hy6ecUbCa.png)

    ![image](https://hackmd.io/_uploads/BJ0N9I-CT.png)

* 點進資料夾後尋找Scripts的資料夾並點擊python的執行檔
![image](https://hackmd.io/_uploads/SktLc8-Aa.png)

    ![image](https://hackmd.io/_uploads/HJjD9LWCT.png)

* 右下角可檢查環境已被更改為上次建立的虛擬環境囉
![image](https://hackmd.io/_uploads/HyehcLbCT.png)

### MacOS操作 <img src="https://cdn.jsdelivr.net/gh/devicons/devicon@latest/icons/apple/apple-original.svg" width=20px style="margin-bottom:8px "/>
1. 於資料中心-Finder中找到 使用者>{用戶名稱}>{環境名稱資料夾}>bin>python3.XX.X
    ![image](https://hackmd.io/_uploads/SyQPpds5A.png)

2. 將其路徑複製下來
    ![image](https://hackmd.io/_uploads/BJwLaui50.png)

3. 於VSCode開啟專案資料夾
    ![image](https://hackmd.io/_uploads/S19h5do90.png)

4. 點擊右下角python套件選擇環境
    ![image](https://hackmd.io/_uploads/rkbUiuj9C.png)

5. 點擊輸入解譯器路徑
    ![image](https://hackmd.io/_uploads/ByFLsdoqR.png)

6. 將複製的路徑貼上
    ![image](https://hackmd.io/_uploads/r1gjpuj9C.png)

7. 即完成環境匯入
    ![image](https://hackmd.io/_uploads/ryK66uic0.png)



## 2. 程式撰寫
* 點擊進入[Line Bot SDK PyPi](https://pypi.org/project/line-bot-sdk/)的官方網站
![image](https://hackmd.io/_uploads/H13_CIbCa.png)

* 往下滑動後找到官方文件給出的基本用法(Synopsis中Usage的部分)全選並複製
![image](https://hackmd.io/_uploads/BkNmT470a.png)

```python=
from flask import Flask, request, abort

from linebot.v3 import (
    WebhookHandler
)
from linebot.v3.exceptions import (
    InvalidSignatureError
)
from linebot.v3.messaging import (
    Configuration,
    ApiClient,
    MessagingApi,
    ReplyMessageRequest,
    TextMessage
)
from linebot.v3.webhooks import (
    MessageEvent,
    TextMessageContent
)

app = Flask(__name__)

configuration = Configuration(access_token='YOUR_CHANNEL_ACCESS_TOKEN')
handler = WebhookHandler('YOUR_CHANNEL_SECRET')


@app.route("/callback", methods=['POST'])
def callback():
    # get X-Line-Signature header value
    signature = request.headers['X-Line-Signature']

    # get request body as text
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)

    # handle webhook body
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        app.logger.info("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'


@handler.add(MessageEvent, message=TextMessageContent)
def handle_message(event):
    with ApiClient(configuration) as api_client:
        line_bot_api = MessagingApi(api_client)
        line_bot_api.reply_message_with_http_info(
            ReplyMessageRequest(
                reply_token=event.reply_token,
                messages=[TextMessage(text=event.message.text)]
            )
        )

if __name__ == "__main__":
    app.run()
```

* 貼上在剛剛建立好的python檔案中
![image](https://hackmd.io/_uploads/BJZDpNXR6.png)

* 找到第23、24行，設定自己的Secret和Channel Access Token
![image](https://hackmd.io/_uploads/BJumbP-Rp.png)

### **在程式中設定自己的Secret**
* 找到Line Dvelopers後台中Basic settings的頁籤
![image](https://hackmd.io/_uploads/SJeRH_-Ap.png)

* 往下滑找到自己的Channel secret並複製
![image](https://hackmd.io/_uploads/SJG-I_ZCa.png)

* 貼上到程式中取代原本的'YOUR_CHANNEL_SCRECT'
![image](https://hackmd.io/_uploads/BymOI_b0T.png)

### **在程式中設定自己的Channel Access Token**
* 找到Line Dvelopers後台中Messaging API的頁籤
![image](https://hackmd.io/_uploads/Hyoq8O-Ca.png)

* 往下滑找到自己的Channel Access Token並複製
![image](https://hackmd.io/_uploads/SktzP_ZA6.png)

* 貼上到程式中取代原本的'YOUR_CHANNEL_ACCESS_TOKEN'
![image](https://hackmd.io/_uploads/SJmOD_WCp.png)



## 3. 啟動Web應用程式
### **利用Visual Studio Code的偵錯模式來啟動Flask的Web應用程式**
* 點擊左方執行與偵錯(Run and Debug)
![image](https://hackmd.io/_uploads/ByoC9dWAT.png)

* 建立一個執行的json檔案
![image](https://hackmd.io/_uploads/H1y2iOW0p.png)

* 選擇Python Debugger
![image](https://hackmd.io/_uploads/B1SvnOWA6.png)

* 選擇Flask
![image](https://hackmd.io/_uploads/ByCnhubRp.png)

* 執行Python Debugger
![image](https://hackmd.io/_uploads/rJruwTG0p.png)

* 啟動完成後可看到執行在本地端的伺服器5000port(若沒設定參數預設都為5000)
![image](https://hackmd.io/_uploads/BkKND6M0p.png)

* 如果是Mac版本，5000port可能已被占用，此時可手動設定port參數(這裡設置為5001)
![image](https://hackmd.io/_uploads/SJWVupM0p.png)

* 執行後可檢查port已變為自己設定的埠號(5001)
![image](https://hackmd.io/_uploads/BJDud6fRT.png)

## 4. 設定Webhook
* 啟動ngrok的執行檔
![image](https://hackmd.io/_uploads/rkjqfezA6.png)

* 輸入指令ngrok http 5000(自己設定的埠號)建立連線
![image](https://hackmd.io/_uploads/Hk_zmgzC6.png)

* 複製其中Forwarding的網址
![image](https://hackmd.io/_uploads/H1ya7aG0p.png)

* 按下Webhook URL的Edit
![image](https://hackmd.io/_uploads/Hk38XgGAa.png)

* 貼上剛剛複製的網址，先不要按下Update
![image](https://hackmd.io/_uploads/rJpNETGRp.png)

* 回到程式中，複製27行route中的/callback
![image](https://hackmd.io/_uploads/S1UaBTMAa.png)

* 貼上在剛剛的網址後
![image](https://hackmd.io/_uploads/HJhgB6f0T.png)

* 按下Update
![image](https://hackmd.io/_uploads/SkFJX6fCp.png)

* 啟用Use webhook
![image](https://hackmd.io/_uploads/SJU3XxfCa.png)

* 可以按下Verify驗證是否有連接成功
![image](https://hackmd.io/_uploads/H1IPfaGAT.png)

* 跳出以下視窗後代表成功與本地端連線了！
![image](https://hackmd.io/_uploads/rJsQ7pzAT.png)


## 5. Echo Bot測試
* 打開Line找到自己的機器人就可以測試是否成功啦！
![image](https://hackmd.io/_uploads/Bymbh4X0p.png)

>Reference：https://developers.line.biz/en/docs/messaging-api/building-bot/


Youtube 課程影片
---
<iframe width="560" height="315" src="https://www.youtube.com/embed/4eiOBj075CM?si=jCXyRkGni6eW9KFy" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe>

{%hackmd @ntuebigdata/about %}

## 相關教材連結

<div style="display: flex; justify-content:space-between;">
  <div>
    <a class="btn btn-warning" href="https://hackmd.io/@ntuebigdata/setup-linebot-development-environment" style="color:white;width:300px;text-overflow:ellipsis;overflow:hidden">◀◀◀ L03 開發環境建置 ◀◀◀</a>
  </div>
  <div>
    <a class="btn btn-info" href="https://hackmd.io/@ntuebigdata/webhook-event-type" style="color:white;width:300px;text-overflow:ellipsis;overflow:hidden">▶▶▶ L05 Webhook Event Type ▶▶▶</a>
  </div>
</div>