【Day 10】Button Template 应用

今天我们来讲怎麽使用 Line Messaging API 的 Button Template

先送上官网传送门 Template Message

Template Message 种类

  1. Buttons,一般的按钮
  2. Confirm,确认按钮
  3. Carousel,可以横向滑动的多选项按钮
  4. Image Carousel,多影像按钮。

我们今天先来看看前两种。

Buttons Template Message

我们做一个 Button,有两个选项:

  1. 是,第一次见面:点选後会回传
  2. 已经见过了:点选後会回传见过了

先直上程序码!

from django.shortcuts import render

from django.shortcuts import render
from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseForbidden
from django.views.decorators.csrf import csrf_exempt
from django.conf import settings

from linebot import LineBotApi, WebhookParser
from linebot.exceptions import InvalidSignatureError, LineBotApiError
from linebot.models import *

line_bot_api = LineBotApi(settings.LINE_CHANNEL_ACCESS_TOKEN)
parser = WebhookParser(settings.LINE_CHANNEL_SECRET)

@csrf_exempt
def callback(request):
    if request.method == 'POST':
        signature = request.META['HTTP_X_LINE_SIGNATURE']
        body = request.body.decode('utf-8')

        try:
            events = parser.parse(body, signature)  # 传入的事件
        except InvalidSignatureError:
            return HttpResponseForbidden()
        except LineBotApiError:
            return HttpResponseBadRequest()

        for event in events:
            print("event", event.message.id)
            # print("event", type(event))
            if isinstance(event, MessageEvent):  # 如果有讯息事件
                print("message", event.message)
                message = []

                if event.message.type == 'text':
                    mtext = event.message.text
                    if "嗨" in mtext:
                        message.append(
                            TemplateSendMessage(
                                alt_text='Buttons template',
                                template=ButtonsTemplate(
                                    title='Hello',
                                    text='第一次见面吗',
                                    actions=[
                                        MessageTemplateAction(
                                            label='是,第一次见面',
                                            text='是',
                                        ),
                                        MessageTemplateAction(
                                            label='已经见过了',
                                            text='见过了',
                                        ),
                                    ]
                                )
                            )
                        )



                    print("type of mtext: {}".format(type(mtext)))

                # 回复传入的讯息文字
                line_bot_api.reply_message( event.reply_token, message )

        return HttpResponse()
    else:
        return HttpResponseBadRequest()

接着我们专心在这块

if "嗨" in mtext:
    message.append(
        TemplateSendMessage(
            alt_text='Buttons template',
                template=ButtonsTemplate(
                    title='Hello',
                    text='第一次见面吗',
                    actions=[
                        MessageTemplateAction(
                            label='是,第一次见面',
                            text='是',
                        ),
                        MessageTemplateAction(
                            label='已经见过了',
                            text='见过了',
                        ),
                    ]
                )
        )
    )

我们顺便来看看 Buttons template 的 json example
这个官方提供的范例显示了所有可以使用的属性(attribute)。

{
  "type": "template",
  "altText": "This is a buttons template",
  "template": {
      "type": "buttons",
      "thumbnailImageUrl": "https://example.com/bot/images/image.jpg",
      "imageAspectRatio": "rectangle",
      "imageSize": "cover",
      "imageBackgroundColor": "#FFFFFF",
      "title": "Menu",
      "text": "Please select",
      "defaultAction": {
          "type": "uri",
          "label": "View detail",
          "uri": "http://example.com/page/123"
      },
      "actions": [
          {
            "type": "postback",
            "label": "Buy",
            "data": "action=buy&itemid=123"
          },
          {
            "type": "postback",
            "label": "Add to cart",
            "data": "action=add&itemid=123"
          },
          {
            "type": "uri",
            "label": "View detail",
            "uri": "http://example.com/page/123"
          }
      ]
  }
}

我们那出想要(或是需要)用到的属性,转成 python 的写法。
那我们就直接介绍比较常见的属性。

  • alt_text:代表电脑如果无法显示时,会在电脑上显示的文字
  • template:这里对应到 json 里的
"template": {
      "type": "buttons",

剩下的 titletextlabel 我们直接用下面这张图片来解释。
应该很清楚!

  • actions:就是包含主体 按钮,还有按下去的要做的动作。有多种选项可以选择。
    • Postback action
    • Message action
    • URI action
    • Datetime picker action
    • Camera action
    • Camera roll action
    • Location action
    • Richmenu Switch Action

不过我主要都使用 Message action 而以,所以我们目前也只针对这个。

MessageTemplateAction(
    label='是,第一次见面',
    text='是',
),

text,表示当你点选按钮後送出之後会传送出去的字。

但是要注意!
按钮最多只能放四个,就是 actions 里面只能有四个。


<<:  [Java Day14] 4.2. 方法

>>:  Day09 - 【概念篇】再谈身份验证与授权

DAY29-VSCODE安装

直接在官网上下载即可。 这边选择自己的系统 这里将这两个打勾就能直接用右键开启 ...

[DAY8]将范例上传(2)

第一步:将昨天下载完的压缩档解压缩,取出line-bot-sdk-python-master\exa...

冲动购物真的是潜意识害的?

透过感觉将外在刺激带给大脑的过程中, 感知系统的敏感程度可以用绝对阀值显示, 代表着能感受到刺激的最...

MLOps专案关於安全性与合规性的10件注意事项

在ML的专案中,从资料的收集、建构模型、测试到部署到产品。这个流程除了需要自动化之外,也需要保有该行...

I Want To Know React - PropTypes & DefaultProps

此文件纪录 React PropTypes 的使用方式与语法 相信读者在使用纯 JavaScript...