Day 05 Line Massaging API- 打造自己的 Chatbot

Line Massaging API- 打造自己的 Chatbot

接下来,如果要在 Azure Web App 上打造 chatbot ,那就必须会用到 Line Massaging API ,透过 Line Massaging API 才能让 chatbot 与使用者沟通。

How it works

  • 使用者发送讯息到 LINE chatbot 帐号
  • LINE platform 发送webhook event到 chatbot server
  • Chatbot server 透过 LINE platform 回应给使用者

建立 Messaging API channel

  • 进入 Line Developers
  • 使用 LINE 帐号登入
  • 找到 Providers
    • 按下 Create
    • 为自己的 Provider name 取名
  • 选择 Create a Messaging API channel

建立 Messaging API channel

  • 填写基本资料
    • Channel name
    • Channel discription
    • Category
    • Subcategory
  • 打勾- I have read and agree ....
  • Create

Chatbot 一定会用到的参数- Secret & Token

  • 取得 Secret & Token

    • 点选 Basic Setting: Channel Secret
    • 点选 Messaging API:按下issue,得到 Channel access token
  • Channel SecretChannel access token 存到config.json上传到 Azure Web App。

    • config.json
    {
    "line": {
        "line_secret": "your line secret",
        "line_token": "your line token",
        }
    }
    
    • 建立连结 Web App 的 tunnel。
    az webapp create-remote-connection \
    -n <你的Web App名称> --resource-group <你的资源群组> &
    
    • 使用scp上传config.json,这边要注意只能上传到/home,这样在 Web App 的 chatbot 才能读到此档案。
    scp -P <port> config.json [email protected]:/home/config.json
    
  • 或者,直接利用az webapp config appsettings set设定环境变数,详情请看Day 04 Azure Web App- 方便部署服务

安装 Line chatbot python package

pip3.7 install line-bot-sdk

Flask + Line Chatbot

把之前的 "hello world" 的Flask网页改写成以下的样子,并且部署到 Azure Web App ,就能让 chatbot 与 Line Platform 沟通。

application.py

import json
from flask import Flask, request, abort
from linebot import LineBotApi, WebhookHandler
from linebot.exceptions import InvalidSignatureError
app = Flask(__name__)

# 读取 config.json,取得 secret 和 token
CONFIG = json.load(open("/home/config.json", "r"))
LINE_SECRET = CONFIG["line"]["line_secret"]
LINE_TOKEN = CONFIG["line"]["line_token"]
LINE_BOT = LineBotApi(LINE_TOKEN)
HANDLER = WebhookHandler(LINE_SECRET)


@app.route("/callback", methods=["POST"])
def callback():
    # X-Line-Signature: 数位签章
    signature = request.headers["X-Line-Signature"]
    print(signature)
    body = request.get_data(as_text=True)
    print(body)
    try:
        HANDLER.handle(body, signature)
    except InvalidSignatureError:
        print("Check the channel secret/access token.")
        abort(400)
    return "OK"

Webhook setting

接着就要到刚刚建立的 Messaging API channel ,设定webhook

  • 进入 Messaging API channel
  • 点选 Messaging API
  • 找到 Webhook URL
    • 点击 Edit
    • 填上 Azure Web APP 的 URL 加上 /callback
      • Example: https://<YOUR WEB APP NAME>.azurewebsites.net/callback
    • 点击 Verify,如果出现的视窗显示 Success,就没有问题了。
  • 开启 Use Webhook

让 Chatbot 回话

讯息种类

application.py加上以下这一段,就可以让chatbot学你说话。透过 HANDLER ,可以辨别 chatbot 接受到的讯息种类,基本的讯息种类有:

  • Text
  • Image
  • Video
  • Audio
  • Location
  • Sticker

我们可以让 chatbot 针对接收到的讯息种类做相对应的动作,在这边是针对文字讯息做处理。收到文字讯息後,如果有收到特定文字,便给予特定答覆,其余则直接学对方说话,回覆相同的文字。要回覆给使用者的字串需要经由TextMessage包装成物件之後,才能透过reply_message回覆给使用者。可以试着在application.py加入以下示范程序,确认效果。

from linebot.models import (
    MessageEvent,
    TextMessage,
    TextSendMessage,
)

# 可以针对收到的讯息种类作出处理,这边是针对 TextMessage
@HANDLER.add(MessageEvent, message=TextMessage)
def handle_message(event):
    url_dict = {
      "ITHOME":"https://www.ithome.com.tw/", 
      "HELP":"https://developers.line.biz/zh-hant/docs/messaging-api/"}
# 将要发出去的文字变成TextSendMessage
    try:
        url = url_dict[event.message.text.upper()]
        message = TextSendMessage(text=url)
    except:
        message = TextSendMessage(text=event.message.text)
# 回覆讯息
    LINE_BOT.reply_message(event.reply_token, message)

Reference


下一篇比较轻松,教大家怎麽美化自己的 Line 讯息。


<<:  铁人赛 Day5 -- 建立属於自己的MySQL资料库

>>:  Day5: [资料结构] - Map

TailwindCSS 从零开始 - 伪类变体 Pseudo-Class Variants

什麽是伪类变体 又来一个专有名词,还没学就心慌慌... 但是发现有一个熟悉名词:伪类(看到这个我就...

使用 Template Message 替 Line Bot 加上同意条款的功能(2)

昨天我们完成了 user sheet 的 query & upsert 功能,今天就要正式将...

解决line图文选单404问题

真的超哭,搞了很久才发现LINE的API有换过,所以URL要换成别的网址。 疯掉XD,这篇文主要分享...

015-登入

今天来简单聊个登入页面。 其实一个简单的登入页面,能思考的事情就很多了。 首先,先聊聊登入最基本的两...

予焦啦!结论与展望(二):铁人赛、正体中文科技写作与杂谈

铁人赛 这是一场疯狂的知识盛宴。有别於第一日提出的特别关注系列清单,今天我则会列出直到最後一天我都还...