iT邦幫忙

2021 iThome 鐵人賽

DAY 14
1
永豐金融APIs

openAPI 對接實務系列 第 14

[day14] 接收使用者的Line訊息

結合先前的

  1. 產生channel access token
  2. 設定heroku

可以開始建立一個伺服器接收由Line官方送過來的資訊,此處假設你使用Heroku進行開發,在Line Developers Console內,將Channel-->Messaging API-->Webhook URL設定為

https://[AppName].herokuapp.com/callback

並將Auto-reply messages 與 Greeting messages同樣設為Disabled,方法為:

  1. 點選右側的Edit
  2. Line Offficial Account Manager-->回應設定
  3. 停用加入好友的歡迎訊息與自動回應訊息

實作並部署回聲機器人

此機器人功能:回傳傳給機器人的文字訊息

如果未安裝line-bot-sdk套件

pip install line-bot-sdk

修改Server.py,加入以下內容

from flask import Flask, request, abort

from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
)
import os

app = Flask(__name__)
api = Api(app)

#LCAT為Channel Access Token
line_bot_api = LineBotApi(os.environ['LCAT'])

#Cst為Channel secret
handler = WebhookHandler(os.environ['Cst'])

@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:
        print("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'

@handler.add(MessageEvent, message=TextMessage)
def handle_message(event):
    line_bot_api.reply_message(
        event.reply_token,
        TextSendMessage(text=event.message.text))

部署:

git add .
git commit -m "Echo Bot"
git push heroku main

此時從Line傳訊息給機器人,你應該就可以收得到來自機器人的回訊

line echo reply bot

加機器人為好友

Line Developers --> Channel Setting --> Messaging API --> Bot information --> Bot basic ID or QR code

使用你的手機搜尋Bot basic ID或掃描QR code加機器人為好友

過程解析

這是一個由Line官方傳送過來的Webhook Sample

{
  "destination": "xxxxxxxxxx",
  "events": [
      {
          "type": "message",
          "message": {
              "type": "text",
              "id": "14353798921116",
              "text": "Hello, world"
          },
          "timestamp": 1625665242211,
          "source": {
              "type": "user",
              "userId": "U80696558e1aa831..."
          },
          "replyToken": "757913772c4646b784d4b7ce46d12671",
          "mode": "active"
      },
      {
          "type": "follow",
          "timestamp": 1625665242214,
          "source": {
              "type": "user",
              "userId": "Ufc729a925b3abef..."
          },
          "replyToken": "bb173f4d9cf64aed9d408ab4e36339ad",
          "mode": "active"
      },
      {
          "type": "unfollow",
          "timestamp": 1625665242215,
          "source": {
              "type": "user",
              "userId": "Ubbd4f124aee5113..."
          },
          "mode": "active"
      }
  ]
}
  1. 手機發訊息給Line
  2. Line傳送通知給bot server(webhook URL)的webhook
  3. WebhookHandler驗證headers中的x-line-signature欄位簽章,除了使用SDK進行驗證,也可以手動進行驗證
  4. 將資料傳送給配對的執行函數,如本次範例中使用的MessageEvent與TextMessage,進行處理
  5. 使用Line SDK回覆訊息,回傳TextSendMessage(text=event.message.text)) 以此範例還說,就是Hello, world

跑完接收與發送,之後要開始把功能逐漸拼起來組成專案了


上一篇
[day13] 設定gunicorn Logging
下一篇
[day15]幾個常用的LineAPI
系列文
openAPI 對接實務30

尚未有邦友留言

立即登入留言