Photo by Jono / Unsplash

Background

最近聊天機器人很火紅. 也蠻多建立在上面的新應用出來. 所以繼之前研究過Telegram Bot之後. 接著來玩一下 LineBot. 並且記錄一下.

Creating a channel

Follow 下列 line 官方的教學創一個developer的帳號 & create a channel

https://developers.line.me/en/docs/messaging-api/getting-started/

Start

官方Python的github寫的鳥鳥的. 所以自己多查了一些資訊來結合在一起.

Set Flask

參考這篇 https://blog.taiker.space/python-build-flask-applications-with-uwsgi-and-nginx-on-ubuntu-14-04/ 把 Flask & Nginx & uwsgi設定好.

Basic Setting

好了之後要去 line developer 設定你的bot

  • Use webhooks: 改成 Enabled
  • Webhook URL Requires SSL: 填入你的callback網址. 記得一定要是https. ex. https:://URL/callback
  • Auto-reply messages: Disabled. 不然你會一直收到 感謝您傳送訊息給我!很抱歉,這個帳號沒有辦法對用戶個別回覆。敬請期待下次的訊息內容!

Main

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

CHANNEL_ACCESS_TOKEN = 'YOUR_CHANNEL_ACCESS_TOKEN'
CHANNEL_SECRET = 'YOUR_CHANNEL_SECRET'

line_bot_api = LineBotApi(CHANNEL_ACCESS_TOKEN)
handler = WebhookHandler(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:
        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))

@app.route('/')
def hello():
    return "Hello Bot User!"


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

好了之後可以掃描QR code加入你的bot為朋友. 會得到以下功能: bot會一直重複你說過的話. 基本的example大致上就這樣. 剩下的功能就看各自的需求了.

photo6147560697526069253

Reference