結合先前的
可以開始建立一個伺服器接收由Line官方送過來的資訊,此處假設你使用Heroku進行開發,在Line Developers Console內,將Channel-->Messaging API-->Webhook URL設定為
https://[AppName].herokuapp.com/callback
並將Auto-reply messages 與 Greeting messages同樣設為Disabled,方法為:
此機器人功能:回傳傳給機器人的文字訊息
如果未安裝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 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"
}
]
}
跑完接收與發送,之後要開始把功能逐漸拼起來組成專案了