# 鸚鵡 Line Bot ###### tags: `Line Bot 簡易上手教學` {%hackmd S1DMFioCO %} * 先重新建立一隻Line Bot ![](https://i.imgur.com/xk2K19Y.png) * 在Basic Setting 找到 Channel secret ![](https://i.imgur.com/SQCaVZ2.png) * Messaging API settings 的 Channel access token ![](https://i.imgur.com/fRyKjTR.png) ## 安裝 Line Bot SDK ```python= pip install line-bot-sdk==1.18.0 ``` * 使用Flask建立網站 ```python= from flask import Flask app = Flask(__name__) from flask import request, abort from linebot import LineBotApi, WebhookHandler from linebot.exceptions import InvalidSignatureError from linebot.models import MessageEvent, TextMessage, TextSendMessage import json with open('line_bot.json', "r", encoding = 'utf8') as data: jsondata = json.load(data) line_bot_api = LineBotApi(jsondata["Channel_access_token"]) handler = WebhookHandler(jsondata["Channel_secret"]) #檢查路由,確認資料是否正確 @app.route('/callback', methods = ['POST']) def callback(): signature = request.headers['X_Line_Signature'] body = request.get_data(as_text = True) try: handler.handle(body, signature) except InvalidSignatureError: abort(400) return 'OK' #回傳 @handler.add(MessageEvent, message = TextMessage) def handler_message(event): line_bot_api.reply_message(event.reply_token, TextSendMessage(text = event.message.text)) if __name__ == '__main__': app.run(debug = True) ``` * json ```json= { "Channel_access_token":"你的Channel_access_token", "Channel_secret":"你的Channel_secret" } ``` ## 使用ngrok建立https伺服器 * [下載](https://ngrok.com/download) ![](https://i.imgur.com/RSXLCsx.png) * 解壓縮後丟進資料夾 ![](https://i.imgur.com/47jPTnE.png) * 啟動伺服器 ```ngrok= ngrok http 埠位號碼 ``` * 切換到當前資料夾 ```ngrok ngrok http 5000 ``` * 複製最長的那部分的網址 ![](https://i.imgur.com/HSoqYgo.png) * 到Message API ![](https://i.imgur.com/oDnrjKj.png) * 輸入 ```htmlembedded= https://{剛剛複製的網址}/callback ``` * npdate,即啟用 ![](https://i.imgur.com/XpvG7zP.png) * 重設 ```python= # ngrok伺服器重新啟動後,就必須修改一次Webhook URL的值 ``` * 修正 ![](https://i.imgur.com/ziGtREN.png) * Line Bot 實際畫面 ![](https://i.imgur.com/1EChuvw.png)