Echo Line Bot

日期:2020/2/11

講者:王譽錚

Outline

  • 申請line developer
  • DNS、https、webhook
  • Ngrok安裝與操作
  • Line bot SDK
  • 環境變數
  • Echo bot
  • 參考資源

申請line developer

1. 按下Providers > create 創立line bot

2. 選擇Create a message API channel

申請好後的畫面

DNS、https、webhook

DNS

https://www.google.com

8.8.8.8

DNS

Https

Webhook

收到訊息

回傳訊息

訂閱者

通知者

收到訊息

回傳訊息

Ngrok 安裝與操作

Line bot SDK

pipenv shell
pipenv install line_bot_sdk

安裝 line-bot-sdk

安裝完的結果

環境變數

建立一個檔案,取名為 .env

pipenv shell

重啟pipenv 以載入環境變數

Echo bot

import os
from flask import Flask, request, abort

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

引入所有要用的套件

app = Flask(__name__)

line_bot_api = LineBotApi(os.environ.get('CHANNEL_ACCESS_TOKEN'))
handler = WebhookHandler(os.environ.get('CHANNEL_SECRET'))

@app.route("/callback", methods=['POST'])
def callback():
    signature = request.headers['X-Line-Signature']
    body = request.get_data(as_text=True)
    app.logger.info("Request body: " + body)
    try:
        handler.handle(body, signature)
    except InvalidSignatureError:
        print("Invalid signature. Please check your channel access token/channel secret.")
        abort(400)

    return 'OK'
  
if __name__ == "__main__":
    app.run()

接收訊息

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

回傳訊息

import os
from flask import Flask, request, abort

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

app = Flask(__name__)

line_bot_api = LineBotApi(os.environ.get('CHANNEL_ACCESS_TOKEN'))
handler = WebhookHandler(os.environ.get('CHANNEL_SECRET'))

@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))


if __name__ == "__main__":
    app.run()

完整程式碼

填寫 Webhook URL

確認設定

參考資源

郭佳甯(2017)。第四天:認識 Webhook。檢索自:https://ithelp.ithome.com.tw/articles/10193212
Penguin(2015)。Flask 使用日志紀錄到文件範例。檢索自:https://reurl.cc/rlmnz1
Augustin Wang(2017)。開發LINE聊天機器人不可不知的十件事。檢索自:https://engineering.linecorp.com/zh-hant/blog/line-device-10/

Thanks for listening.

Made with Slides.com