將官方帳號設定成機器人
登入 LINE Developers 設定機器人的 Webhook 網址
實作 Webhook
機器人主要有兩種模式,如下圖
由機器人主動推播(Push)訊息給使用者
由使用者傳送訊息給機器人,再由機器人回覆(Reply)訊息給使用者
When an event occurs, such as when a user adds your LINE Official Account as a friend or sends a message, the LINE Platform sends an HTTPS POST request to the webhook URL (bot server).
The webhook URL is configured for each channel in the LINE Developers Console.
使用者傳訊息給機器人時,LINE官方伺服器會傳送 HTTP POST格式訊息給 WebHook 伺服器
那我們會收到以下格式( JSON ):
{
"destination": "xxxxxxxxxx",
"events": [
{
"replyToken": "0f3779fba3b349968c5d07db31eab56f",
"type": "message",
"mode": "active",
"timestamp": 1462629479859,
"source": {
"type": "user",
"userId": "U4af4980629..."
},
"message": {
"id": "325708",
"type": "text",
"text": "Hello, world"
}
},
{
"replyToken": "8cf9239d56244f4197887e939187e19e",
"type": "follow",
"mode": "active",
"timestamp": 1462629479859,
"source": {
"type": "user",
"userId": "U4af4980629..."
}
}
]
}
那就看我們寫的WebHook 要推播訊息給其他人,還是要回覆訊息給傳訊息的人
如果要推播,要傳送下面的格式
curl -v -X POST https://api.line.me/v2/bot/message/push \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer {channel access token}' \
-d '{
"to": "U4af4980629...",
"messages":[
{
"type":"text",
"text":"Hello, world1"
},
{
"type":"text",
"text":"Hello, world2"
}
]
}'
如果要回覆要傳送下面的格式
curl -v -X POST https://api.line.me/v2/bot/message/reply \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer {channel access token}' \
-d '{
"replyToken":"nHuyWiB7yP5Zw52FIkcQobQuGDXCTA",
"messages":[
{
"type":"text",
"text":"Hello, user"
},
{
"type":"text",
"text":"May I help you?"
}
]
}
推播(Push)是有限制的,所以可以的話就盡可能先使用回覆(Reply)來傳送訊息。
當Webhook 架設好後,我們到 LINE Developers 去設定機器人的 Webhook
選擇機器人
切換到 Messaging API 頁面
將你架設的伺服器輸入至機器人
一切都順利的話,你的機器人就能開始運作了。