找回密碼
 註冊
搜索
查看: 56|回復: 0

[教學] 鸚鵡 LINE Chat Bot ( LINE Message API )

[複製鏈接]
發表於 2025-3-7 14:17:14 | 顯示全部樓層 |閱讀模式
Push to Facebook
文章將 LINE 官方範例逐步拆解,實作 echo 聊天機器人,完成時您已結合 Python、Flask、LINE Message API 及網路訊息傳遞等

鸚鵡 LINEChatBot MessageAPI

鸚鵡 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

鸚鵡 LINEChatBot MessageAPI



Messaging API申請好以後
回應設定 ->停用自動回應

  • 加入好友歡迎訊息"依您需求選擇停用/啟用,這邊設停用。
  • 自動回應訊息"建議設定停用,不然罐頭訊息太多。
  • Webhook"必須為啟用。



提取 screct 及channel access token

鸚鵡 LINEChatBot MessageAPI

鸚鵡 LINEChatBot MessageAPI


環境:
win10
pycharm
python 3.9
line bot sdk 3.12

安裝模組

  1. <div>pip install flask
  2. pip install line-bot-sdk==3.12</div>
複製代碼


程式碼
  1. from flask import Flask, request, abort

  2. from linebot.v3 import (
  3.     WebhookHandler
  4. )
  5. from linebot.v3.exceptions import (
  6.     InvalidSignatureError
  7. )
  8. from linebot.v3.messaging import (
  9.     Configuration,
  10.     ApiClient,
  11.     MessagingApi,
  12.     ReplyMessageRequest,
  13.     TextMessage
  14. )
  15. from linebot.v3.webhooks import (
  16.     MessageEvent,
  17.     TextMessageContent
  18. )

  19. app = Flask(__name__)

  20. configuration = Configuration(access_token='your access_token')
  21. handler = WebhookHandler('your screct')


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

  26.     # get request body as text
  27.     body = request.get_data(as_text=True)
  28.     app.logger.info("Request body: " + body)
  29.     print("aaaaa:"+body)
  30.     # handle webhook body
  31.     try:
  32.         handler.handle(body, signature)
  33.     except InvalidSignatureError:
  34.         app.logger.info("Invalid signature. Please check your channel access token/channel secret.")
  35.         abort(400)

  36.     return 'OK'


  37. @handler.add(MessageEvent, message=TextMessageContent)
  38. def handle_message(event):
  39.     with ApiClient(configuration) as api_client:
  40.         line_bot_api = MessagingApi(api_client)
  41.         line_bot_api.reply_message_with_http_info(
  42.             ReplyMessageRequest(
  43.                 reply_token=event.reply_token,
  44.                 messages=[TextMessage(text=event.message.text)]
  45.             )
  46.         )

  47. if __name__ == "__main__":
  48.     app.run()
複製代碼

使用 ngrok 讓外網連接你的 API
ngrok 做為一個轉發的伺服器,他可以把外界的請求轉發到你指定的 Port,使用的背景原理是連接到 ngrok 雲端伺服器,將你本機指定的地址公開,再將由 ngrok 一串公開的網址來存取內容。他的優點是快速而且還提供了 https 的服務讓你使用上更安全,甚至你還可以設置密碼保護。


安裝
官方文件與載點
  • windows 用戶
    到官方網站中對應的位元版本下載解壓縮後直接啟動 ngrok.exe 即可在終端機上打指令執行,例如啟動並監聽 5000 Port。
    ngrok http 5000


先去官網註冊並拿取專屬token
終端機下執行
  1. ngrok config add-authtoken <token>
複製代碼


執行程式
  1. ngrok http 5000
複製代碼

鸚鵡 LINEChatBot MessageAPI

鸚鵡 LINEChatBot MessageAPI


並執行程式碼

鸚鵡 LINEChatBot MessageAPI

鸚鵡 LINEChatBot MessageAPI


提取鏈結
填到webhook

鸚鵡 LINEChatBot MessageAPI

鸚鵡 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

鸚鵡 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


您需要登錄後才可以回帖 登錄 | 註冊

本版積分規則

Archiver|手機版|小黑屋|TShopping

GMT+8, 2025-3-15 02:40 , Processed in 0.028174 second(s), 24 queries .

Powered by Discuz! X3.5

© 2001-2025 Discuz! Team.

快速回復 返回頂部 返回列表