LoginSignup
2
2

More than 5 years have passed since last update.

LINE messageAPI richmenu小技

Posted at

はじめに

会社の後輩から、LINEのmessageAPIを使ってちょっとした受付けBOTみたいなものを
作れないかと相談されて、作ってる時に思いついたrichmenuの小技です。(大したことないですが)

ドキュメントの中にある下記の一文で思いつきました(即時に反映されるんだ~)

14.png

前提

・BOTがすでにある(Flaskで組んである)

コード

main.py
# -*- coding: utf-8 -*-

#  Licensed under the Apache License, Version 2.0 (the "License"); you may
#  not use this file except in compliance with the License. You may obtain
#  a copy of the License at
#
#       https://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#  License for the specific language governing permissions and limitations
#  under the License.

import os
import sys
from argparse import ArgumentParser

from flask import Flask, request, abort,render_template,redirect,url_for
from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,FollowEvent,UnfollowEvent,CarouselTemplate, CarouselColumn,URIAction,PostbackAction,MessageAction,TemplateSendMessage,ConfirmTemplate,PostbackEvent,StickerMessage, StickerSendMessage, LocationMessage,LocationSendMessage,ImageMessage, VideoMessage, AudioMessage, FileMessage)



import os
import time

def richmenu(userID):

    r=YOUR_richmenuId_1
    default=YOUR_richmenuId_2


    line_bot_api.link_rich_menu_to_user(userID,r)
    time.sleep(1)
    line_bot_api.link_rich_menu_to_user(userID,default)

app = Flask(__name__)

line_bot_api = LineBotApi('YOUR_LINE_CHANNEL_ACCESS_TOKEN')
handler = WebhookHandler('YOUR_LINE_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(PostbackEvent)
def handle_postback(event):
    profile=line_bot_api.get_profile(event.source.user_id)
    userID=event.source.user_id
    name=profile.display_name
    url="https://api.line.me/v2/bot/message/push"
    if (event.postback.data=="r"):
        richmenu(userID)

    else:
        line_bot_api.reply_message(event.reply_token,TextSendMessage(text="Check"))
        pass

if __name__=="__main__":
    app.debug=True
    app.run(host="0.0.0.0")

richmenu

rich.sh
 curl -v -X POST https://api.line.me/v2/bot/richmenu \
  -H 'Authorization: Bearer YOUR_LINE_CHANNEL_ACCESS_TOKEN' \
  -H 'Content-Type:application/json' \
  -d \
  '{
    "size":{
        "width":2500,
        "height":843
    },
    "selected":true,
    "name":"default2",
    "chatBarText":"menu",
    "areas":[
        {
          "bounds":{
              "x":91,
              "y":258,
              "width":430,
              "height":583
          },
          "action":{
              "type":"postback",
              "data":"r"
          }
        },
        {
          "bounds":{
              "x":697,
              "y":258,
              "width":430,
              "height":583
          },
          "action":{
              "type":"postback",
              "data":"b"
          }
        },
        {
          "bounds":{
              "x":1303,
              "y":258,
              "width":430,
              "height":583
          },
          "action":{
              "type":"postback",
              "data":"w"
          }
        },
        {
          "bounds":{
              "x":1909,
              "y":258,
              "width":430,
              "height":583
          },
          "action":{
              "type":"postback",
              "data":"s"
          }
        }
       ] 
  }'

画像

default

2222.jpg

r

recruit.jpg

説明

richmenuの左端のアイコンをタップすると、postbackで「r」を送るようにします。
(※richmenuからのデータ送信はpostbackでやった方が余分なメッセージがトーク画面に出てこないからいいかなと思います)

postbackを受信すると、送ってくれたユーザーのrichmenuをYOUR_richmenuId_1(画像はr)に登録されたものします。
その一秒後にYOUR_richmenuId_2(画像はdefault)に変えます.

そうするとタップされたらそのタップされた部分のアイコンが動いたような表現になります。

最後に

LINEBotは作ってみると面白いです!(UIを考えなくてもいいので)

もう一つどうでもいい小技(技というほどの物でもないですが)は、リファレンスにはカルーセルテンプレートの
サムネイルはjpegかpngとありますがGIFのURLを指定しても大丈夫なようです(webkit使ってるからかな。richmenuの画像ももしかしたら
GIFでもいいのかな)

image.png

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2