文章將 LINE 官方範例逐步拆解,實作 echo 聊天機器人,完成時您已結合 Python、Flask、LINE Message API 及網路訊息傳遞等
鸚鵡 LINEChatBot MessageAPI
相關的知識點: - HTTPS。 LINE Message API 只容許超文本傳輸協定https作為溝通的方式, https 需要有經過認證安全的網域才行,可採行的作法如下:
- 建立一個雲端伺服器,申請網域及 https 憑證。
- 由本機透過 ngrok 等程式建立具 https 憑證的臨時通道。
- API。 LINE、Google、Facebook 等服務為了管理開發者如何存取該服務/伺服器的內容,建立應用程式介面(Application Programming Interface,API)來進行資料交換,現今多半以JSON檔案進行傳輸,有些API需要申請後取得授權token,並且查閱API文件使用符合規範的呼叫方式,不然會呼叫失敗。
- webhook URL。 每個 LINE Bot Channels只能綁定一個webhook URL作為Line bot與你的程式傳遞資訊的橋樑,自學者常遇到 webhook 連結失敗的問題,請試著動手做喔! 參閱官方文件設定webhook URL。
實作 LINE Messaging API
line developer 申請新的 Messaging API 網路上已有很多相關文章,不在贅述
官方網址 https://developers.line.biz/console/
鸚鵡 LINEChatBot MessageAPI
Messaging API申請好以後
回應設定 ->停用自動回應
- 加入好友歡迎訊息"依您需求選擇停用/啟用,這邊設停用。
- 自動回應訊息"建議設定停用,不然罐頭訊息太多。
- Webhook"必須為啟用。
提取 screct 及channel access token
鸚鵡 LINEChatBot MessageAPI
環境:
win10
pycharm
python 3.9
line bot sdk 3.12
安裝模組
- <div>pip install flask
- pip install line-bot-sdk==3.12</div>
複製代碼
程式碼- 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 access_token')
- handler = WebhookHandler('your screct')
- @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)
- print("aaaaa:"+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()
複製代碼
使用 ngrok 讓外網連接你的 API
ngrok 做為一個轉發的伺服器,他可以把外界的請求轉發到你指定的 Port,使用的背景原理是連接到 ngrok 雲端伺服器,將你本機指定的地址公開,再將由 ngrok 一串公開的網址來存取內容。他的優點是快速而且還提供了 https 的服務讓你使用上更安全,甚至你還可以設置密碼保護。
安裝
先去官網註冊並拿取專屬token
終端機下執行
- ngrok config add-authtoken <token>
複製代碼
執行程式
鸚鵡 LINEChatBot MessageAPI
並執行程式碼
鸚鵡 LINEChatBot MessageAPI
提取鏈結
填到webhook
鸚鵡 LINEChatBot MessageAPI
壓確認line develop 會出現Success
ngrok 終端機會出現ok
最後到 Line Bot 打字,就會出現你說的文字了
問題排除
開發時出現錯誤訊息
Authentication failed. Confirm that the access token in the authorization header is valid
google後發現到官方網頁說明,Token used to get a new access token (refresh token). Valid for 90 days after the access token is issued.
意思是access token 90天後要重新申請一次 token(90天期限)
鸚鵡 LINEChatBot MessageAPI
參考文章
https://github.com/line/line-bot-sdk-python/blob/master/README.rst
https://ithelp.ithome.com.tw/articles/10197345
https://ithelp.ithome.com.tw/m/articles/10234877
|