# 本地ngrok作法: ## 1.創立虛擬環境並下載必要程式 ``` venv test cd test act ``` ``` pip install line-bot-sdk pip install gunicorn pip install flask ``` ## 2.linebot 主程式 ### (token and secret記得改) ``` nano echobot.py ``` ``` LINE_CHANNEL_ACCESS_TOKEN='Your channel token' LINE_CHANNEL_SECRET='Your channel secret' 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_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(LINE_CHANNEL_SECRET) @app.route("/", methods=["POST"]) def webhook_handler(): # verify signature if needed # add logic to handle the request signature = request.headers['X-Line-Signature'] body = request.get_data(as_text=True) try: handler.handle(body, signature) except InvalidSignatureError: abort(code=400,description="An error has been raised") # 或是 abort(400) 也可以... 目的是要回報 Bad Request,至於為什麼是400...請看文章下方... return 'OK' @handler.add(MessageEvent, message=TextMessage) def handling_message(event): line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text)) ``` ## 3.驗證ngrok ### 去官網拿token!![螢幕擷取畫面 2023-11-08 223600.png](https://hackmd.io/_uploads/HkAVafYXa.png) ## 4.開服 ``` gunicorn -w 1 -b 0.0.0.0:531xx echobot:app --daemon ``` ``` ngrok http 531xx ``` ![螢幕擷取畫面 2023-11-08 224450.png](https://hackmd.io/_uploads/rJ3qJXFXa.png) ### 複製並放到webhook url --- # 雲端做法 ## 1.創立虛擬環境並下載必要程式 ``` venv test cd test act ``` ``` pip install line-bot-sdk pip install gunicorn pip isnstall flask ``` ## 2.linebot 主程式 ### (token and secret記得改) ``` nano echobot.py ``` ``` LINE_CHANNEL_ACCESS_TOKEN='Your channel token' LINE_CHANNEL_SECRET='Your channel secret' 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_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN) handler = WebhookHandler(LINE_CHANNEL_SECRET) @app.route("/", methods=["POST"]) def webhook_handler(): # verify signature if needed # add logic to handle the request signature = request.headers['X-Line-Signature'] body = request.get_data(as_text=True) try: handler.handle(body, signature) except InvalidSignatureError: abort(code=400,description="An error has been raised") # 或是 abort(400) 也可以... 目的是要回報 Bad Request,至於為什麼是400...請看文章下方... return 'OK' @handler.add(MessageEvent, message=TextMessage) def handling_message(event): line_bot_api.reply_message(event.reply_token, TextSendMessage(text=event.message.text)) ``` ## 3.開服 ``` gunicorn -w 1 -b 0.0.0.0:531xx echobot:app ``` ### 複製以下程式到webhook url ``` https://app1.mirai.tw/531xx/ ``` # 注意事項 ## echobot,test都只是範例名稱 考試時依照老師為主 ## port一定是531xx 不要用錯