def test_quick_reply_button(self):
     arg = {'action': CameraRollAction(label='Send photo')}
     self.assertEqual(self.serialize_as_dict(arg, type=self.ACTION),
                      QuickReplyButton(**arg).as_json_dict())
Пример #2
0
def handle_text_message(event):
    text = event.message.text
    profile = line_bot_api.get_profile(event.source.user_id)
    userInfo = checkLineUserID(event.source.user_id)
    if text == 'info':
        if isinstance(event.source, SourceUser):
            if userInfo:
                # line_bot_api.reply_message(
                #     event.reply_token, [
                #         ImageSendMessage(
                #             original_content_url=ifNoneValue(profile.picture_url,"https://www.aaa.com/aa"),
                #             preview_image_url=ifNoneValue(profile.picture_url,"https://www.aaa.com/aa"),
                #         )
                #     ]
                # )

                f = open("ChatBotTemplate/user_info.json", "r")
                bubble_string = f.read()
                f.close()

                bubble_string = bubble_string.replace(
                    "/*picture_url*/",
                    ifNoneValue(profile.picture_url, "https://www.aaa.com/aa"))
                bubble_string = bubble_string.replace(
                    "/*first_name*/", ifNoneValue(userInfo["first_name"], " "))
                bubble_string = bubble_string.replace(
                    "/*last_name*/", ifNoneValue(userInfo["last_name"], " "))
                bubble_string = bubble_string.replace(
                    "/*email*/", ifNoneValue(userInfo["email"], "-"))
                bubble_string = bubble_string.replace(
                    "/*phone*/", ifNoneValue(userInfo["phone"], "-"))
                message = FlexSendMessage(alt_text="User Info",
                                          contents=json.loads(bubble_string))
                line_bot_api.reply_message(event.reply_token, message)

                # line_bot_api.push_message(
                #     event.source.user_id, [
                #         TextSendMessage(
                #             text='คุณ {} {}\nEmail {}\nTel {}'
                #             .format(userInfo["first_name"],userInfo["last_name"],userInfo["email"],userInfo["phone"])
                #         )
                #     ]
                # )
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't use profile API without user ID"))
    elif text == 'tel':
        if isinstance(event.source, SourceUser):
            line_bot_api.reply_message(event.reply_token,
                                       TextMessage(text="tel:0868905463"))
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't use profile API without user ID"))
    elif text == 'Clinical':
        if isinstance(event.source, SourceUser):
            labOrdersUser = getClinicalUserID(event.source.user_id)
            if labOrdersUser:
                first_name = ''
                lastt_name = ''
                if userInfo:
                    first_name = userInfo["first_name"]
                    # last_name = userInfo["last_name"]
                    # line_bot_api.push_message(
                    #     event.source.user_id, [
                    #         ImageSendMessage(
                    #             original_content_url=profile.picture_url,
                    #             preview_image_url=profile.picture_url
                    #         )
                    #     ]
                    # )
                    # line_bot_api.push_message(
                    #     event.source.user_id, [
                    #         TextMessage(text="คุณ {} {}\nผล Clinical 5 ครั้งล่าสุด".format(userInfo["first_name"],userInfo["last_name"]))
                    #     ]
                    # )
                for labOrder in labOrdersUser:
                    f = open("ChatBotTemplate/clinical_result.json", "r")
                    bubble_string = f.read()
                    f.close()

                    bubble_string = bubble_string.replace(
                        "/*order_id*/", labOrder["order_id"])
                    bubble_string = bubble_string.replace(
                        "/*patient_name*/", labOrder["patient_name"])
                    bubble_string = bubble_string.replace(
                        "/*received_date*/",
                        labOrder["received_date"].strftime(
                            '%Y-%m-%d-%H:%M:%S'))
                    bubble_string = bubble_string.replace(
                        "/*hn*/", ifNoneValue(labOrder["hn"], " "))
                    bubble_string = bubble_string.replace(
                        "/*sex_desc*/", labOrder["sex_desc"])
                    bubble_string = bubble_string.replace(
                        "/*test_item_desc_list*/",
                        labOrder["test_item_desc_list"])
                    message = FlexSendMessage(
                        alt_text="Lab Result",
                        contents=json.loads(bubble_string))

                    # line_bot_api.push_message(
                    #     event.source.user_id,message)

                    line_bot_api.reply_message(event.reply_token, message)
                    # TextSendMessage(
                    #     text='Lab Order {}\nReceived Date {}\nline://app/1654084194-9JVnOQEb?order_id={}'
                    #     .format(labOrder["order_id"],labOrder["received_date"],labOrder["order_id"],labOrder["order_id"]))
            else:
                first_name = ''
                lastt_name = ''
                if userInfo:
                    first_name = userInfo["first_name"]
                    last_name = userInfo["last_name"]

                line_bot_api.reply_message(
                    event.reply_token,
                    TextMessage(text="คุณ {} {}\nไม่มีผล Clinical".format(
                        userInfo["first_name"], userInfo["last_name"])))
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextMessage(text="Bot can't use profile API without user ID"))
    elif text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(text='Display name: ' + profile.display_name),
                TextSendMessage(text='Status message: ' +
                                str(profile.status_message))
            ])
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text="Bot can't use profile API without user ID"))
    elif text == 'quota':
        quota = line_bot_api.get_message_quota()
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='type: ' + quota.type),
            TextSendMessage(text='value: ' + str(quota.value))
        ])
    elif text == 'quota_consumption':
        quota_consumption = line_bot_api.get_message_quota_consumption()
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='total usage: ' +
                            str(quota_consumption.total_usage)),
        ])
    elif text == 'push':
        line_bot_api.push_message(event.source.user_id, [
            TextSendMessage(text='PUSH!'),
        ])
    elif text == 'multicast':
        line_bot_api.multicast([event.source.user_id], [
            TextSendMessage(text='THIS IS A MULTICAST MESSAGE'),
        ])
    elif text == 'broadcast':
        line_bot_api.broadcast([
            TextSendMessage(text='THIS IS A BROADCAST MESSAGE'),
        ])
    elif text.startswith('broadcast '):  # broadcast 20190505
        date = text.split(' ')[1]
        print("Getting broadcast result: " + date)
        result = line_bot_api.get_message_delivery_broadcast(date)
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='Number of sent broadcast messages: ' + date),
            TextSendMessage(text='status: ' + str(result.status)),
            TextSendMessage(text='success: ' + str(result.success)),
        ])
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='Leaving group'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'image':
        url = request.url_root + '/static/logo.png'
        app.logger.info("url=" + url)
        line_bot_api.reply_message(event.reply_token,
                                   ImageSendMessage(url, url))
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?',
                                           actions=[
                                               MessageAction(label='Yes',
                                                             text='Yes!'),
                                               MessageAction(label='No',
                                                             text='No!'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'buttons':
        buttons_template = ButtonsTemplate(
            title='My buttons sample',
            text='Hello, my buttons',
            actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping'),
                PostbackAction(label='ping with text',
                               data='ping',
                               text='ping'),
                MessageAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1',
                           title='fuga1',
                           actions=[
                               URIAction(label='Go to line.me',
                                         uri='https://line.me'),
                               PostbackAction(label='ping', data='ping')
                           ]),
            CarouselColumn(text='hoge2',
                           title='fuga2',
                           actions=[
                               PostbackAction(label='ping with text',
                                              data='ping',
                                              text='ping'),
                               MessageAction(label='Translate Rice', text='米')
                           ]),
        ])
        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerAction(label='datetime',
                                            data='datetime_postback',
                                            mode='datetime')),
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerAction(
                    label='date', data='date_postback', mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text',
            template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    elif text == 'flex':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(url='https://example.com/cafe.jpg',
                                size='full',
                                aspect_ratio='20:13',
                                aspect_mode='cover',
                                action=URIAction(uri='http://example.com',
                                                 label='label')),
            body=BoxComponent(
                layout='vertical',
                contents=[
                    # title
                    TextComponent(text='Brown Cafe', weight='bold', size='xl'),
                    # review
                    BoxComponent(
                        layout='baseline',
                        margin='md',
                        contents=[
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/grey_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/grey_star.png'),
                            TextComponent(text='4.0',
                                          size='sm',
                                          color='#999999',
                                          margin='md',
                                          flex=0)
                        ]),
                    # info
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        spacing='sm',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Place',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=1),
                                    TextComponent(text='Shinjuku, Tokyo',
                                                  wrap=True,
                                                  color='#666666',
                                                  size='sm',
                                                  flex=5)
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Time',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=1),
                                    TextComponent(
                                        text="10:00 - 23:00",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                        ],
                    )
                ],
            ),
            footer=BoxComponent(
                layout='vertical',
                spacing='sm',
                contents=[
                    # callAction, separator, websiteAction
                    SpacerComponent(size='sm'),
                    # callAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='CALL', uri='tel:000000'),
                    ),
                    # separator
                    SeparatorComponent(),
                    # websiteAction
                    ButtonComponent(style='link',
                                    height='sm',
                                    action=URIAction(
                                        label='WEBSITE',
                                        uri="https://example.com"))
                ]),
        )
        message = FlexSendMessage(alt_text="hello", contents=bubble)
        line_bot_api.reply_message(event.reply_token, message)
    elif text == 'flex_update_1':
        bubble_string = """
        {
          "type": "bubble",
          "body": {
            "type": "box",
            "layout": "vertical",
            "contents": [
              {
                "type": "image",
                "url": "https://scdn.line-apps.com/n/channel_devcenter/img/flexsnapshot/clip/clip3.jpg",
                "position": "relative",
                "size": "full",
                "aspectMode": "cover",
                "aspectRatio": "1:1",
                "gravity": "center"
              },
              {
                "type": "box",
                "layout": "horizontal",
                "contents": [
                  {
                    "type": "box",
                    "layout": "vertical",
                    "contents": [
                      {
                        "type": "text",
                        "text": "Brown Hotel",
                        "weight": "bold",
                        "size": "xl",
                        "color": "#ffffff"
                      },
                      {
                        "type": "box",
                        "layout": "baseline",
                        "margin": "md",
                        "contents": [
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png"
                          },
                          {
                            "type": "text",
                            "text": "4.0",
                            "size": "sm",
                            "color": "#d6d6d6",
                            "margin": "md",
                            "flex": 0
                          }
                        ]
                      }
                    ]
                  },
                  {
                    "type": "box",
                    "layout": "vertical",
                    "contents": [
                      {
                        "type": "text",
                        "text": "¥62,000",
                        "color": "#a9a9a9",
                        "decoration": "line-through",
                        "align": "end"
                      },
                      {
                        "type": "text",
                        "text": "¥42,000",
                        "color": "#ebebeb",
                        "size": "xl",
                        "align": "end"
                      }
                    ]
                  }
                ],
                "position": "absolute",
                "offsetBottom": "0px",
                "offsetStart": "0px",
                "offsetEnd": "0px",
                "backgroundColor": "#00000099",
                "paddingAll": "20px"
              },
              {
                "type": "box",
                "layout": "vertical",
                "contents": [
                  {
                    "type": "text",
                    "text": "SALE",
                    "color": "#ffffff"
                  }
                ],
                "position": "absolute",
                "backgroundColor": "#ff2600",
                "cornerRadius": "20px",
                "paddingAll": "5px",
                "offsetTop": "10px",
                "offsetEnd": "10px",
                "paddingStart": "10px",
                "paddingEnd": "10px"
              }
            ],
            "paddingAll": "0px"
          }
        }
        """
        message = FlexSendMessage(alt_text="hello",
                                  contents=json.loads(bubble_string))
        line_bot_api.reply_message(event.reply_token, message)
    elif text == 'quick_reply':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Quick reply',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=PostbackAction(label="label1", data="data1")),
                    QuickReplyButton(
                        action=MessageAction(label="label2", text="text2")),
                    QuickReplyButton(action=DatetimePickerAction(
                        label="label3", data="data3", mode="date")),
                    QuickReplyButton(action=CameraAction(label="label4")),
                    QuickReplyButton(action=CameraRollAction(label="label5")),
                    QuickReplyButton(action=LocationAction(label="label6")),
                ])))
    elif text == 'link_token' and isinstance(event.source, SourceUser):
        link_token_response = line_bot_api.issue_link_token(
            event.source.user_id)
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='link_token: ' +
                            link_token_response.link_token)
        ])
    elif text == 'insight_message_delivery':
        today = datetime.date.today().strftime("%Y%m%d")
        response = line_bot_api.get_insight_message_delivery(today)
        if response.status == 'ready':
            messages = [
                TextSendMessage(text='broadcast: ' + str(response.broadcast)),
                TextSendMessage(text='targeting: ' + str(response.targeting)),
            ]
        else:
            messages = [TextSendMessage(text='status: ' + response.status)]
        line_bot_api.reply_message(event.reply_token, messages)
    elif text == 'insight_followers':
        today = datetime.date.today().strftime("%Y%m%d")
        response = line_bot_api.get_insight_followers(today)
        if response.status == 'ready':
            messages = [
                TextSendMessage(text='followers: ' + str(response.followers)),
                TextSendMessage(text='targetedReaches: ' +
                                str(response.targeted_reaches)),
                TextSendMessage(text='blocks: ' + str(response.blocks)),
            ]
        else:
            messages = [TextSendMessage(text='status: ' + response.status)]
        line_bot_api.reply_message(event.reply_token, messages)
    elif text == 'insight_demographic':
        response = line_bot_api.get_insight_demographic()
        if response.available:
            messages = [
                "{gender}: {percentage}".format(gender=it.gender,
                                                percentage=it.percentage)
                for it in response.genders
            ]
        else:
            messages = [TextSendMessage(text='available: false')]
        line_bot_api.reply_message(event.reply_token, messages)
    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=event.message.text))
Пример #3
0
    def test_push_text_message_with_quick_reply(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push',
                      json={},
                      status=200)

        self.tested.push_message(
            'to',
            TextSendMessage(
                text='Hello, world',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(image_url='https://example.com',
                                     action=PostbackAction(label="label1",
                                                           data="data1")),
                    QuickReplyButton(
                        action=MessageAction(label="label2", text="text2")),
                    QuickReplyButton(action=DatetimePickerAction(
                        label="label3", data="data3", mode="date")),
                    QuickReplyButton(action=CameraAction(label="label4")),
                    QuickReplyButton(action=CameraRollAction(label="label5")),
                    QuickReplyButton(action=LocationAction(label="label6")),
                ])))

        request = responses.calls[0].request
        self.assertEqual(request.method, 'POST')
        self.assertEqual(
            request.url,
            LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push')
        self.assertEqual(
            json.loads(request.body), {
                "to":
                "to",
                'notificationDisabled':
                False,
                "messages": [{
                    "type": "text",
                    "text": "Hello, world",
                    "quickReply": {
                        "items": [
                            {
                                "type": "action",
                                "imageUrl": "https://example.com",
                                "action": {
                                    "type": "postback",
                                    "label": "label1",
                                    "data": "data1",
                                }
                            },
                            {
                                "type": "action",
                                "action": {
                                    "type": "message",
                                    "label": "label2",
                                    "text": "text2",
                                }
                            },
                            {
                                "type": "action",
                                "action": {
                                    "type": "datetimepicker",
                                    "label": "label3",
                                    "data": "data3",
                                    "mode": "date",
                                }
                            },
                            {
                                "type": "action",
                                "action": {
                                    "type": "camera",
                                    "label": "label4",
                                }
                            },
                            {
                                "type": "action",
                                "action": {
                                    "type": "cameraRoll",
                                    "label": "label5",
                                }
                            },
                            {
                                "type": "action",
                                "action": {
                                    "type": "location",
                                    "label": "label6",
                                }
                            },
                        ]
                    }
                }]
            })
Пример #4
0
import control_session

backend = backend_aws  # ここを指定して、モジュールを差し替えることが可能

line_bot_api = LineBotApi(
    os.getenv('LINE_CHANNEL_ACCESS_TOKEN', 'YOUR_CHANNEL_ACCESS_TOKEN'))
handler = WebhookHandler(
    os.getenv('LINE_CHANNEL_SECRET', 'YOUR_CHANNEL_SECRET'))
tmp_dir = Path(os.getenv("TMPDIR", "/tmp"))

logger = logging.getLogger(__name__)

# *SendMessage 利用時に共通して使うクリックリプライボタン (カメラで更新等のクイックボタンを毎度、つける)
DEFAULT_QUICK_REPLY = QuickReply(items=[
    QuickReplyButton(action=CameraAction(label="カメラで更新")),
    QuickReplyButton(action=CameraRollAction(label="写真で更新")),
    QuickReplyButton(action=LocationAction(label="場所を設定")),
])
quick_reply_dict = {
    None: DEFAULT_QUICK_REPLY,
    "no_menu": None,
}

WELLCOME_MESSAGE = """
{nickname_call}はじめまして!😃
友だち追加ありがとうございます。firsttest001 です。

さっそくお店の登録から、始めていきましょう!
""".strip()
# このトークからの通知を受け取らない場合は、画面右上のメニューから通知をオフにしてください。
Пример #5
0
def handle_text_message(event):
    text = event.message.text

    if text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(text='Display name: ' + profile.display_name),
                    TextSendMessage(text='Status message: ' + profile.status_message)
                ]
            )
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't use profile API without user ID"))
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text='Leaving group'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?', actions=[
            MessageAction(label='Yes', text='Yes!'),
            MessageAction(label='No', text='No!'),
        ])
        template_message = TemplateSendMessage(
            alt_text='Confirm alt text', template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'buttons':
        buttons_template = ButtonsTemplate(
            title='My buttons sample', text='Hello, my buttons', actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping'),
                PostbackAction(label='ping with text', data='ping', text='ping'),
                MessageAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(
            alt_text='Buttons alt text', template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1', title='fuga1', actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping')
            ]),
            CarouselColumn(text='hoge2', title='fuga2', actions=[
                PostbackAction(label='ping with text', data='ping', text='ping'),
                MessageAction(label='Translate Rice', text='米')
            ]),
        ])
        template_message = TemplateSendMessage(
            alt_text='Carousel alt text', template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerAction(label='datetime',
                                                            data='datetime_postback',
                                                            mode='datetime')),
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerAction(label='date',
                                                            data='date_postback',
                                                            mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    elif text == 'flex':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(
                url='https://example.com/cafe.jpg',
                size='full',
                aspect_ratio='20:13',
                aspect_mode='cover',
                action=URIAction(uri='http://example.com', label='label')
            ),
            body=BoxComponent(
                layout='vertical',
                contents=[
                    # title
                    TextComponent(text='Brown Cafe', weight='bold', size='xl'),
                    # review
                    BoxComponent(
                        layout='baseline',
                        margin='md',
                        contents=[
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/grey_star.png'),
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/grey_star.png'),
                            TextComponent(text='4.0', size='sm', color='#999999', margin='md',
                                          flex=0)
                        ]
                    ),
                    # info
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        spacing='sm',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(
                                        text='Place',
                                        color='#aaaaaa',
                                        size='sm',
                                        flex=1
                                    ),
                                    TextComponent(
                                        text='Shinjuku, Tokyo',
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5
                                    )
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(
                                        text='Time',
                                        color='#aaaaaa',
                                        size='sm',
                                        flex=1
                                    ),
                                    TextComponent(
                                        text="10:00 - 23:00",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                        ],
                    )
                ],
            ),
            footer=BoxComponent(
                layout='vertical',
                spacing='sm',
                contents=[
                    # callAction, separator, websiteAction
                    SpacerComponent(size='sm'),
                    # callAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='CALL', uri='tel:000000'),
                    ),
                    # separator
                    SeparatorComponent(),
                    # websiteAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='WEBSITE', uri="https://example.com")
                    )
                ]
            ),
        )
        message = FlexSendMessage(alt_text="hello", contents=bubble)
        line_bot_api.reply_message(
            event.reply_token,
            message
        )
    elif text == 'quick_reply':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Quick reply',
                quick_reply=QuickReply(
                    items=[
                        QuickReplyButton(
                            action=PostbackAction(label="label1", data="data1")
                        ),
                        QuickReplyButton(
                            action=MessageAction(label="label2", text="text2")
                        ),
                        QuickReplyButton(
                            action=DatetimePickerAction(label="label3",
                                                        data="data3",
                                                        mode="date")
                        ),
                        QuickReplyButton(
                            action=CameraAction(label="label4")
                        ),
                        QuickReplyButton(
                            action=CameraRollAction(label="label5")
                        ),
                        QuickReplyButton(
                            action=LocationAction(label="label6")
                        ),
                    ])))
    else:
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text=event.message.text))
Пример #6
0
def handle_text_message(event):
    text = event.message.text

    if text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(text='Display name: ' + profile.display_name),
                TextSendMessage(text='Status message: ' +
                                str(profile.status_message))
            ])
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text="Bot can't use profile API without user ID"))
    elif text == 'quota':
        quota = line_bot_api.get_message_quota()
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='type: ' + quota.type),
            TextSendMessage(text='value: ' + str(quota.value))
        ])
    elif text == 'quota_consumption':
        quota_consumption = line_bot_api.get_message_quota_consumption()
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='total usage: ' +
                            str(quota_consumption.total_usage)),
        ])
    elif text == 'push':
        line_bot_api.push_message(event.source.user_id, [
            TextSendMessage(text='PUSH!'),
        ])
    elif text == 'multicast':
        line_bot_api.multicast([event.source.user_id], [
            TextSendMessage(text='THIS IS A MULTICAST MESSAGE'),
        ])
    elif text == 'broadcast':
        line_bot_api.broadcast([
            TextSendMessage(text='THIS IS A BROADCAST MESSAGE'),
        ])
    elif text.startswith('broadcast '):  # broadcast 20190505
        date = text.split(' ')[1]
        print("Getting broadcast result: " + date)
        result = line_bot_api.get_message_delivery_broadcast(date)
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='Number of sent broadcast messages: ' + date),
            TextSendMessage(text='status: ' + str(result.status)),
            TextSendMessage(text='success: ' + str(result.success)),
        ])
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='Leaving group'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'image':
        url = request.url_root + '/static/logo.png'
        app.logger.info("url=" + url)
        line_bot_api.reply_message(event.reply_token,
                                   ImageSendMessage(url, url))
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?',
                                           actions=[
                                               MessageAction(label='Yes',
                                                             text='Yes!'),
                                               MessageAction(label='No',
                                                             text='No!'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'buttons':
        buttons_template = ButtonsTemplate(
            title='My buttons sample',
            text='Hello, my buttons',
            actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping'),
                PostbackAction(label='ping with text',
                               data='ping',
                               text='ping'),
                MessageAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1',
                           title='fuga1',
                           actions=[
                               URIAction(label='Go to line.me',
                                         uri='https://line.me'),
                               PostbackAction(label='ping', data='ping')
                           ]),
            CarouselColumn(text='hoge2',
                           title='fuga2',
                           actions=[
                               PostbackAction(label='ping with text',
                                              data='ping',
                                              text='ping'),
                               MessageAction(label='Translate Rice', text='米')
                           ]),
        ])
        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerAction(label='datetime',
                                            data='datetime_postback',
                                            mode='datetime')),
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerAction(
                    label='date', data='date_postback', mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text',
            template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    elif text == 'flex':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(url='https://example.com/cafe.jpg',
                                size='full',
                                aspect_ratio='20:13',
                                aspect_mode='cover',
                                action=URIAction(uri='http://example.com',
                                                 label='label')),
            body=BoxComponent(
                layout='vertical',
                contents=[
                    # title
                    TextComponent(text='Brown Cafe', weight='bold', size='xl'),
                    # review
                    BoxComponent(
                        layout='baseline',
                        margin='md',
                        contents=[
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/grey_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/grey_star.png'),
                            TextComponent(text='4.0',
                                          size='sm',
                                          color='#999999',
                                          margin='md',
                                          flex=0)
                        ]),
                    # info
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        spacing='sm',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Place',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=1),
                                    TextComponent(text='Shinjuku, Tokyo',
                                                  wrap=True,
                                                  color='#666666',
                                                  size='sm',
                                                  flex=5)
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Time',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=1),
                                    TextComponent(
                                        text="10:00 - 23:00",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                        ],
                    )
                ],
            ),
            footer=BoxComponent(
                layout='vertical',
                spacing='sm',
                contents=[
                    # callAction, separator, websiteAction
                    SpacerComponent(size='sm'),
                    # callAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='CALL', uri='tel:000000'),
                    ),
                    # separator
                    SeparatorComponent(),
                    # websiteAction
                    ButtonComponent(style='link',
                                    height='sm',
                                    action=URIAction(
                                        label='WEBSITE',
                                        uri="https://example.com"))
                ]),
        )
        message = FlexSendMessage(alt_text="hello", contents=bubble)
        line_bot_api.reply_message(event.reply_token, message)
    elif text == 'quick_reply':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Quick reply',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=PostbackAction(label="label1", data="data1")),
                    QuickReplyButton(
                        action=MessageAction(label="label2", text="text2")),
                    QuickReplyButton(action=DatetimePickerAction(
                        label="label3", data="data3", mode="date")),
                    QuickReplyButton(action=CameraAction(label="label4")),
                    QuickReplyButton(action=CameraRollAction(label="label5")),
                    QuickReplyButton(action=LocationAction(label="label6")),
                ])))
    elif text == 'link_token' and isinstance(event.source, SourceUser):
        link_token_response = line_bot_api.issue_link_token(
            event.source.user_id)
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='link_token: ' +
                            link_token_response.link_token)
        ])
    elif text == 'insight_message_delivery':
        today = datetime.date.today().strftime("%Y%m%d")
        response = line_bot_api.get_insight_message_delivery(today)
        if response.status == 'ready':
            messages = [
                TextSendMessage(text='broadcast: ' + str(response.broadcast)),
                TextSendMessage(text='targeting: ' + str(response.targeting)),
            ]
        else:
            messages = [TextSendMessage(text='status: ' + response.status)]
        line_bot_api.reply_message(event.reply_token, messages)
    elif text == 'insight_followers':
        today = datetime.date.today().strftime("%Y%m%d")
        response = line_bot_api.get_insight_followers(today)
        if response.status == 'ready':
            messages = [
                TextSendMessage(text='followers: ' + str(response.followers)),
                TextSendMessage(text='targetedReaches: ' +
                                str(response.targeted_reaches)),
                TextSendMessage(text='blocks: ' + str(response.blocks)),
            ]
        else:
            messages = [TextSendMessage(text='status: ' + response.status)]
        line_bot_api.reply_message(event.reply_token, messages)
    elif text == 'insight_demographic':
        response = line_bot_api.get_insight_demographic()
        if response.available:
            messages = [
                "{gender}: {percentage}".format(gender=it.gender,
                                                percentage=it.percentage)
                for it in response.genders
            ]
        else:
            messages = [TextSendMessage(text='available: false')]
        line_bot_api.reply_message(event.reply_token, messages)
    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=event.message.text))
Пример #7
0
secretFileContentJson = json.load(
    open("./line_secret_key", "r", encoding="utf8"))

# 設定 Server 啟用細節
app = Flask(__name__, static_url_path="/images", static_folder="./images/")

# 生成實體物件
line_bot_api = LineBotApi(
    secretFileContentJson.get("LINE_CHANNEL_ACCESS_TOKEN"))
handler = WebhookHandler(secretFileContentJson.get("LINE_CHANNEL_SECRET"))

# 創建 QuickReplyButton
## 點擊後,開啟相機
cameraQuickReplyButton = QuickReplyButton(action=CameraAction(label="拍照"))
## 點擊後,切換至照片相簿選擇
cameraRollQRB = QuickReplyButton(action=CameraRollAction(label="相簿"))
## 設計 QuickReplyButton 的 List
quickReplyList = QuickReply(items=[cameraQuickReplyButton, cameraRollQRB])
## 將 quickReplyList 塞入 TextSendMessage 中
quickReplyTextSendMessage = TextSendMessage(text='請選擇功能',
                                            quick_reply=quickReplyList)

# 建立 quickReply 關鍵字字典
template_message_dict = {"@功能": quickReplyTextSendMessage}


# 取得現在時間
def get_time():
    pacific = pytz.timezone('Asia/Taipei')
    d = datetime.datetime.now(pacific)
Пример #8
0
def handle_text_message(event):
    text = event.message.text

    if text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(text='Display name: ' + profile.display_name),
                    TextSendMessage(text='Status message: ' + str(profile.status_message))
                ]
            )
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't use profile API without user ID"))
    elif text == 'emojis':
        emojis = [
            {
                "index": 0,
                "productId": "5ac1bfd5040ab15980c9b435",
                "emojiId": "001"
            },
            {
                "index": 13,
                "productId": "5ac1bfd5040ab15980c9b435",
                "emojiId": "002"
            }
        ]
        text_message = TextSendMessage(text='$ LINE emoji $', emojis=emojis)
        line_bot_api.reply_message(
            event.reply_token, [
                text_message
            ]
        )
    elif text == 'quota':
        quota = line_bot_api.get_message_quota()
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text='type: ' + quota.type),
                TextSendMessage(text='value: ' + str(quota.value))
            ]
        )
    elif text == 'quota_consumption':
        quota_consumption = line_bot_api.get_message_quota_consumption()
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text='total usage: ' + str(quota_consumption.total_usage)),
            ]
        )
    elif text == 'push':
        line_bot_api.push_message(
            event.source.user_id, [
                TextSendMessage(text='PUSH!'),
            ]
        )
    elif text == 'multicast':
        line_bot_api.multicast(
            [event.source.user_id], [
                TextSendMessage(text='THIS IS A MULTICAST MESSAGE'),
            ]
        )
    elif text == 'broadcast':
        line_bot_api.broadcast(
            [
                TextSendMessage(text='THIS IS A BROADCAST MESSAGE'),
            ]
        )
    elif text.startswith('broadcast '):  # broadcast 20190505
        date = text.split(' ')[1]
        print("Getting broadcast result: " + date)
        result = line_bot_api.get_message_delivery_broadcast(date)
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text='Number of sent broadcast messages: ' + date),
                TextSendMessage(text='status: ' + str(result.status)),
                TextSendMessage(text='success: ' + str(result.success)),
            ]
        )
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text='Leaving group'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'image':
        url = request.url_root + '/static/logo.png'
        app.logger.info("url=" + url)
        line_bot_api.reply_message(
            event.reply_token,
            ImageSendMessage(url, url)
        )
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?', actions=[
            MessageAction(label='Yes', text='Yes!'),
            MessageAction(label='No', text='No!'),
        ])
        template_message = TemplateSendMessage(
            alt_text='Confirm alt text', template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'buttons':
        buttons_template = ButtonsTemplate(
            title='My buttons sample', text='Hello, my buttons', actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping'),
                PostbackAction(label='ping with text', data='ping', text='ping'),
                MessageAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(
            alt_text='Buttons alt text', template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1', title='fuga1', actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping')
            ]),
            CarouselColumn(text='hoge2', title='fuga2', actions=[
                PostbackAction(label='ping with text', data='ping', text='ping'),
                MessageAction(label='Translate Rice', text='米')
            ]),
        ])
        template_message = TemplateSendMessage(
            alt_text='Carousel alt text', template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerAction(label='datetime',
                                                            data='datetime_postback',
                                                            mode='datetime')),
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerAction(label='date',
                                                            data='date_postback',
                                                            mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    elif text == 'flex':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(
                url='https://example.com/cafe.jpg',
                size='full',
                aspect_ratio='20:13',
                aspect_mode='cover',
                action=URIAction(uri='http://example.com', label='label')
            ),
            body=BoxComponent(
                layout='vertical',
                contents=[
                    # title
                    TextComponent(text='Brown Cafe', weight='bold', size='xl'),
                    # review
                    BoxComponent(
                        layout='baseline',
                        margin='md',
                        contents=[
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/grey_star.png'),
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/grey_star.png'),
                            TextComponent(text='4.0', size='sm', color='#999999', margin='md',
                                          flex=0)
                        ]
                    ),
                    # info
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        spacing='sm',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(
                                        text='Place',
                                        color='#aaaaaa',
                                        size='sm',
                                        flex=1
                                    ),
                                    TextComponent(
                                        text='Shinjuku, Tokyo',
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5
                                    )
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(
                                        text='Time',
                                        color='#aaaaaa',
                                        size='sm',
                                        flex=1
                                    ),
                                    TextComponent(
                                        text="10:00 - 23:00",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                        ],
                    )
                ],
            ),
            footer=BoxComponent(
                layout='vertical',
                spacing='sm',
                contents=[
                    # callAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='CALL', uri='tel:000000'),
                    ),
                    # separator
                    SeparatorComponent(),
                    # websiteAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='WEBSITE', uri="https://example.com")
                    )
                ]
            ),
        )
        message = FlexSendMessage(alt_text="hello", contents=bubble)
        line_bot_api.reply_message(
            event.reply_token,
            message
        )
    elif text == 'flex_update_1':
        bubble_string = """
        {
          "type": "bubble",
          "body": {
            "type": "box",
            "layout": "vertical",
            "contents": [
              {
                "type": "image",
                "url": "https://scdn.line-apps.com/n/channel_devcenter/img/flexsnapshot/clip/clip3.jpg",
                "position": "relative",
                "size": "full",
                "aspectMode": "cover",
                "aspectRatio": "1:1",
                "gravity": "center"
              },
              {
                "type": "box",
                "layout": "horizontal",
                "contents": [
                  {
                    "type": "box",
                    "layout": "vertical",
                    "contents": [
                      {
                        "type": "text",
                        "text": "Brown Hotel",
                        "weight": "bold",
                        "size": "xl",
                        "color": "#ffffff"
                      },
                      {
                        "type": "box",
                        "layout": "baseline",
                        "margin": "md",
                        "contents": [
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gold_star_28.png"
                          },
                          {
                            "type": "icon",
                            "size": "sm",
                            "url": "https://scdn.line-apps.com/n/channel_devcenter/img/fx/review_gray_star_28.png"
                          },
                          {
                            "type": "text",
                            "text": "4.0",
                            "size": "sm",
                            "color": "#d6d6d6",
                            "margin": "md",
                            "flex": 0
                          }
                        ]
                      }
                    ]
                  },
                  {
                    "type": "box",
                    "layout": "vertical",
                    "contents": [
                      {
                        "type": "text",
                        "text": "¥62,000",
                        "color": "#a9a9a9",
                        "decoration": "line-through",
                        "align": "end"
                      },
                      {
                        "type": "text",
                        "text": "¥42,000",
                        "color": "#ebebeb",
                        "size": "xl",
                        "align": "end"
                      }
                    ]
                  }
                ],
                "position": "absolute",
                "offsetBottom": "0px",
                "offsetStart": "0px",
                "offsetEnd": "0px",
                "backgroundColor": "#00000099",
                "paddingAll": "20px"
              },
              {
                "type": "box",
                "layout": "vertical",
                "contents": [
                  {
                    "type": "text",
                    "text": "SALE",
                    "color": "#ffffff"
                  }
                ],
                "position": "absolute",
                "backgroundColor": "#ff2600",
                "cornerRadius": "20px",
                "paddingAll": "5px",
                "offsetTop": "10px",
                "offsetEnd": "10px",
                "paddingStart": "10px",
                "paddingEnd": "10px"
              }
            ],
            "paddingAll": "0px"
          }
        }
        """
        message = FlexSendMessage(alt_text="hello", contents=json.loads(bubble_string))
        line_bot_api.reply_message(
            event.reply_token,
            message
        )
    elif text == 'quick_reply':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Quick reply',
                quick_reply=QuickReply(
                    items=[
                        QuickReplyButton(
                            action=PostbackAction(label="label1", data="data1")
                        ),
                        QuickReplyButton(
                            action=MessageAction(label="label2", text="text2")
                        ),
                        QuickReplyButton(
                            action=DatetimePickerAction(label="label3",
                                                        data="data3",
                                                        mode="date")
                        ),
                        QuickReplyButton(
                            action=CameraAction(label="label4")
                        ),
                        QuickReplyButton(
                            action=CameraRollAction(label="label5")
                        ),
                        QuickReplyButton(
                            action=LocationAction(label="label6")
                        ),
                    ])))
    elif text == 'link_token' and isinstance(event.source, SourceUser):
        link_token_response = line_bot_api.issue_link_token(event.source.user_id)
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text='link_token: ' + link_token_response.link_token)
            ]
        )
    elif text == 'insight_message_delivery':
        today = datetime.date.today().strftime("%Y%m%d")
        response = line_bot_api.get_insight_message_delivery(today)
        if response.status == 'ready':
            messages = [
                TextSendMessage(text='broadcast: ' + str(response.broadcast)),
                TextSendMessage(text='targeting: ' + str(response.targeting)),
            ]
        else:
            messages = [TextSendMessage(text='status: ' + response.status)]
        line_bot_api.reply_message(event.reply_token, messages)
    elif text == 'insight_followers':
        today = datetime.date.today().strftime("%Y%m%d")
        response = line_bot_api.get_insight_followers(today)
        if response.status == 'ready':
            messages = [
                TextSendMessage(text='followers: ' + str(response.followers)),
                TextSendMessage(text='targetedReaches: ' + str(response.targeted_reaches)),
                TextSendMessage(text='blocks: ' + str(response.blocks)),
            ]
        else:
            messages = [TextSendMessage(text='status: ' + response.status)]
        line_bot_api.reply_message(event.reply_token, messages)
    elif text == 'insight_demographic':
        response = line_bot_api.get_insight_demographic()
        if response.available:
            messages = ["{gender}: {percentage}".format(gender=it.gender, percentage=it.percentage)
                        for it in response.genders]
        else:
            messages = [TextSendMessage(text='available: false')]
        line_bot_api.reply_message(event.reply_token, messages)
    else:
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text=event.message.text))
def process_postback_event(event):
    user_profile = line_bot_api.get_profile(event.source.user_id)
    print(user_profile)

    # 解析data
    query_string_dict = parse_qs(event.postback.data)

    print(query_string_dict)
    # 在data欄位裡面有找到folder
    # folder=abcd&tag=xxx
    if 'folder' in query_string_dict:
        print(query_string_dict.get('folder')[0])
        result_message_array = []

        # 去素材資料夾下,找abcd資料夾內的reply,json
        replyJsonPath = 'dynamic_reply/' + query_string_dict.get(
            'folder')[0] + "/reply.json"
        result_message_array = detect_json_array_to_new_message_array(
            replyJsonPath)

        line_bot_api.reply_message(event.reply_token, result_message_array)
    elif 'menu' in query_string_dict:

        linkRichMenuId = open(
            "./richmenu/" + query_string_dict.get('menu')[0] + '/rich_menu_id',
            'r').read()
        line_bot_api.link_rich_menu_to_user(event.source.user_id,
                                            linkRichMenuId)

    elif 'model' in query_string_dict:
        if query_string_dict.get('model')[0] == 'yolo_leaf':
            cameraQuickReplyButton = QuickReplyButton(action=CameraAction(
                label="立即拍照"))
            cameraRollQRB = QuickReplyButton(action=CameraRollAction(
                label="選擇照片"))
            quickReplyList = QuickReply(
                items=[cameraRollQRB, cameraQuickReplyButton])
            quickReplyTextSendMessage = TextSendMessage(
                text='選擇物件偵測來源:葉子', quick_reply=quickReplyList)
            line_bot_api.reply_message(event.reply_token,
                                       quickReplyTextSendMessage)

            @handler.add(MessageEvent, message=ImageMessage)
            def handle_image_message(event):
                # 取出消息內User的資料
                user_profile = line_bot_api.get_profile(event.source.user_id)

                # 將用戶資訊存在檔案內
                with open("./users.txt", "a") as myfile:
                    myfile.write(json.dumps(vars(user_profile),
                                            sort_keys=True))
                    myfile.write('\r\n')

                # 儲存圖片
                message_content = line_bot_api.get_message_content(
                    event.message.id)
                with open('./images/' + event.message.id + '.jpg', 'wb') as fd:
                    for chunk in message_content.iter_content():
                        fd.write(chunk)

                # yolov3處理圖片
                input_path_leaf = "./images/" + event.message.id + ".jpg"
                yolo3expe_predict(config_path_leaf, input_path_leaf,
                                  output_path_leaf, yolomodel_leaf, graph_leaf)
                print("Yolo葉子啟動")

                # 回覆文字消息與 回傳照片
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='物件偵測結果:葉子'),
                    ImageSendMessage(
                        original_content_url='https://' + server_url +
                        '/images/yolov3_output/' + event.message.id + '.jpg',
                        preview_image_url='https://' + server_url +
                        '/images/yolov3_output/' + event.message.id + '.jpg')
                ])

        if query_string_dict.get('model')[0] == 'yolo_tree':
            cameraQuickReplyButton = QuickReplyButton(action=CameraAction(
                label="立即拍照"))
            cameraRollQRB = QuickReplyButton(action=CameraRollAction(
                label="選擇照片"))
            quickReplyList = QuickReply(
                items=[cameraRollQRB, cameraQuickReplyButton])
            quickReplyTextSendMessage = TextSendMessage(
                text='選擇物件偵測來源:樹形', quick_reply=quickReplyList)
            line_bot_api.reply_message(event.reply_token,
                                       quickReplyTextSendMessage)

            @handler.add(MessageEvent, message=ImageMessage)
            def handle_image_message(event):
                # 取出消息內User的資料
                user_profile = line_bot_api.get_profile(event.source.user_id)

                # 將用戶資訊存在檔案內
                with open("./users.txt", "a") as myfile:
                    myfile.write(json.dumps(vars(user_profile),
                                            sort_keys=True))
                    myfile.write('\r\n')

                # 儲存圖片
                message_content = line_bot_api.get_message_content(
                    event.message.id)
                with open('./images/' + event.message.id + '.jpg', 'wb') as fd:
                    for chunk in message_content.iter_content():
                        fd.write(chunk)

                # yolov3處理圖片
                input_path_tree = "./images/" + event.message.id + ".jpg"
                yolo3expe_predict(config_path_tree, input_path_tree,
                                  output_path_tree, yolomodel_tree, graph_tree)
                print("Yolo樹形啟動")

                # 回覆文字消息與 回傳照片
                line_bot_api.reply_message(event.reply_token, [
                    TextSendMessage(text='物件偵測結果:樹形'),
                    ImageSendMessage(
                        original_content_url='https://' + server_url +
                        '/images/yolov3_output/' + event.message.id + '.jpg',
                        preview_image_url='https://' + server_url +
                        '/images/yolov3_output/' + event.message.id + '.jpg')
                ])

        if query_string_dict.get('model')[0] == 'cnn_tree':
            print("CNN樹")
            cameraQuickReplyButton = QuickReplyButton(action=CameraAction(
                label="立即拍照"))
            cameraRollQRB = QuickReplyButton(action=CameraRollAction(
                label="選擇照片"))
            quickReplyList = QuickReply(
                items=[cameraRollQRB, cameraQuickReplyButton])
            quickReplyTextSendMessage = TextSendMessage(
                text='選擇影像辨識來源:樹形', quick_reply=quickReplyList)
            line_bot_api.reply_message(event.reply_token,
                                       quickReplyTextSendMessage)

        if query_string_dict.get('model')[0] == 'cnn_leaf':
            print("CNN葉子")
            cameraQuickReplyButton = QuickReplyButton(action=CameraAction(
                label="立即拍照"))
            cameraRollQRB = QuickReplyButton(action=CameraRollAction(
                label="選擇照片"))
            quickReplyList = QuickReply(
                items=[cameraRollQRB, cameraQuickReplyButton])
            quickReplyTextSendMessage = TextSendMessage(
                text='選擇影像辨識來源:葉子', quick_reply=quickReplyList)
            line_bot_api.reply_message(event.reply_token,
                                       quickReplyTextSendMessage)
Пример #10
0
def handle_text_message(event):
    text = (event.message.text).lower()

    if text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(text='Display name: ' + profile.display_name),
                TextSendMessage(text='Status message: ' +
                                profile.status_message),
                TextSendMessage(text='Picture: ' + profile.picture_url)
            ])
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text="Bot can't use profile API without user ID"))
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='Leaving group'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?',
                                           actions=[
                                               MessageAction(label='Yes',
                                                             text='Yes!'),
                                               MessageAction(label='No',
                                                             text='No!'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'navigation':
        buttons_template = ButtonsTemplate(
            title='Navigation Bot vers.1',
            text='Hello, ada yang bisa saya bantu...?',
            actions=[
                MessageAction(label='Info Grapari', text='cari info Grapari'),
                URIAction(label='About Dev.',
                          uri='http://line.me/ti/p/~primaananda_')
            ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'cari info grapari' or text == 'cari grapari' or text == 'grapari':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='Daftar grapari wilayah Denpasar',
                           title='Denpasar',
                           actions=[
                               MessageAction(label='Grapari Teuku Umar',
                                             text='grapari teuku umar'),
                               MessageAction(label='grapari renon',
                                             text='grapari renon')
                           ]),
            CarouselColumn(text='Daftar grapari wilayah Bangli',
                           title='Bangli',
                           actions=[
                               PostbackAction(
                                   label='Status Grapari',
                                   data='tidak terdapat Grapari di Bangli',
                                   text=' '),
                               MessageAction(label=' ', text=' ')
                           ]),
            CarouselColumn(text='Daftar grapari wilayah Buleleng',
                           title='Buleleng',
                           actions=[
                               MessageAction(label='grapari Buleleng',
                                             text='grapari buleleng'),
                               MessageAction(label=' ', text=' ')
                           ]),
            CarouselColumn(text='Daftar grapari wilayah Gianyar',
                           title='Gianyar',
                           actions=[
                               MessageAction(label='grapari Gianyar',
                                             text='grapari gianyar'),
                               MessageAction(label=' ', text=' ')
                           ]),
            CarouselColumn(text='Daftar grapari wilayah Jembrana',
                           title='Jembrana',
                           actions=[
                               MessageAction(label='graPARI Negara',
                                             text='grapari negara'),
                               MessageAction(label=' ', text=' ')
                           ]),
            CarouselColumn(text='Daftar grapari wilayah Karangasem',
                           title='Karangasem',
                           actions=[
                               MessageAction(label='graPARI Karangasem',
                                             text='grapari karangasem'),
                               MessageAction(label=' ', text=' ')
                           ]),
            CarouselColumn(text='Daftar grapari wilayah Klungkung',
                           title='Klungkung',
                           actions=[
                               PostbackAction(
                                   label='Status Grapari',
                                   data='tidak terdapat Grapari di Klungkung',
                                   text=' '),
                               MessageAction(label=' ', text=' ')
                           ]),
            CarouselColumn(text='Daftar grapari wilayah Tabanan',
                           title='Tabanan',
                           actions=[
                               MessageAction(label='Grapari Tabanan',
                                             text='grapari tabanan'),
                               MessageAction(label=' ', text=' ')
                           ]),
        ])
        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'alamat grapari renon':
        line_bot_api.reply_message(event.reply_token, [
            LocationSendMessage(
                title='My GraPARI Denpasar Renon',
                address=
                'Jl. Raya Puputan No.33, Panjer, Denpasar Sel., Kota Denpasar, Bali 80234',
                latitude=-8.672262,
                longitude=115.228615)
        ])
    elif text == 'alamat grapari teuku umar':
        line_bot_api.reply_message(event.reply_token, [
            LocationSendMessage(
                title='My GraPARI Denpasar Teuku Umar',
                address=
                'Jl. Teuku Umar No.6, Dauh Puri Klod, Denpasar Bar., Kota Denpasar, Bali 80114',
                latitude=-8.669041,
                longitude=115.214185)
        ])
    elif text == 'alamat grapari buleleng':
        line_bot_api.reply_message(event.reply_token, [
            LocationSendMessage(
                title='My GraPARI Buleleng',
                address=
                'Jl. A. Yani No.72, Kaliuntu, Kec. Buleleng, Kabupaten Buleleng, Bali 81114',
                latitude=-8.111648,
                longitude=115.085734)
        ])
    elif text == 'alamat grapari gianyar':
        line_bot_api.reply_message(event.reply_token, [
            LocationSendMessage(
                title='My GraPARI Gianyar',
                address=
                'Jl. A. Yani No.72, Kaliuntu, Kec. Buleleng, Kabupaten Buleleng, Bali 81114',
                latitude=-8.111648,
                longitude=115.085734)
        ])
    elif text == 'alamat grapari mbg':
        line_bot_api.reply_message(event.reply_token, [
            LocationSendMessage(
                title='My graPARI Mall Bali Galeria',
                address=
                'JL. by Pass I Gusti Ngurah Rai , 80361 Denpasar , Bali, Kuta, Badung Regency, Bali 80361',
                latitude=-8.723316,
                longitude=115.184888)
        ])
    elif text == 'alamat grapari karangasem':
        line_bot_api.reply_message(event.reply_token, [
            LocationSendMessage(
                title='My graPARI Karangasem',
                address=
                'Jl. PB. Sudirman 98 C, Amlapura, Kec. Karangasem, Kab. Karangasem, Bali 80811',
                latitude=-8.451645,
                longitude=115.603835)
        ])
    elif text == 'alamat grapari negara':
        line_bot_api.reply_message(event.reply_token, [
            LocationSendMessage(
                title='GraPARI Telkomsel Negara',
                address=
                'Jl. Ngurah Rai, Pendem, Kec. Jembrana, Kabupaten Jembrana, Bali 82218',
                latitude=-8.360644,
                longitude=114.629995)
        ])
    elif text == 'alamat grapari tabanan':
        line_bot_api.reply_message(event.reply_token, [
            LocationSendMessage(
                title='GraPARI Telkomsel Tabanan',
                address=
                'Jl. Dr. Ir. Soekarno, Banjar Anyar, Kediri, Kabupaten Tabanan, Bali 82121',
                latitude=-8.552806,
                longitude=115.135258)
        ])
    elif text == 'grapari teuku umar':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(url='https://i.imgur.com/G18bDUi.jpg',
                                size='full',
                                aspect_ratio='20:13',
                                aspect_mode='cover',
                                action=URIAction(
                                    uri='https://i.imgur.com/G18bDUi.jpg',
                                    label='label')),
            body=BoxComponent(
                layout='vertical',
                contents=[
                    # title
                    TextComponent(text='My GraPARI Teuku Umar',
                                  weight='bold',
                                  size='xl'),
                    # info
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        spacing='sm',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Alamat',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=3),
                                    TextComponent(
                                        text=
                                        'Jl. Teuku Umar No.6, Dauh Puri Klod, Denpasar Bar., Kota Denpasar, Bali 80114',
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5)
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text="Waktu Buka",
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=3),
                                    TextComponent(
                                        text=
                                        "Senin, 08.00–17.00\nSelasa, 08.00–17.00\nRabu, 08.00–17.00\nKamis, 08.00–17.00\nJumat, 08.00–17.00\nSabtu, 08.00–12.00\nMinggu, Tutup",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='No. Telp',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=3),
                                    TextComponent(
                                        text="0811-3940-500",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                        ],
                    )
                ],
            ),
            footer=BoxComponent(
                layout='vertical',
                spacing='sm',
                contents=[
                    # callAction, separator, websiteAction
                    SpacerComponent(size='sm'),
                    # callAction
                    ButtonComponent(
                        style='primary',
                        color='#00b300',
                        height='sm',
                        action=URIAction(label='Call', uri='tel:08113940500'),
                    ),
                    # websiteAction
                    ButtonComponent(style='secondary',
                                    height='sm',
                                    action=PostbackAction(
                                        label='Alamat GraPARI',
                                        data='alamat grapari teuku umar',
                                        text='alamat grapari teuku umar'))
                ]),
        )
        message = FlexSendMessage(alt_text="grapari teuku umar",
                                  contents=bubble)
        line_bot_api.reply_message(event.reply_token, message)
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1',
                           title='fuga1',
                           actions=[
                               URIAction(label='Go to line.me',
                                         uri='https://line.me'),
                               PostbackAction(label='ping', data='ping')
                           ]),
            CarouselColumn(text='hoge2',
                           title='fuga2',
                           actions=[
                               PostbackAction(label='ping with text',
                                              data='ping',
                                              text='ping'),
                               MessageAction(label='Translate Rice', text='米')
                           ]),
            CarouselColumn(text='hoge1',
                           title='fuga1',
                           actions=[
                               URIAction(label='Go to line.me',
                                         uri='https://line.me'),
                               PostbackAction(label='ping', data='ping')
                           ]),
        ])
        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerAction(label='datetime',
                                            data='datetime_postback',
                                            mode='datetime')),
            ImageCarouselColumn(
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerAction(
                    label='date', data='date_postback', mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text',
            template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    elif text == 'flex':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(url='https://example.com/cafe.jpg',
                                size='full',
                                aspect_ratio='20:13',
                                aspect_mode='cover',
                                action=URIAction(uri='http://example.com',
                                                 label='label')),
            body=BoxComponent(
                layout='vertical',
                contents=[
                    # title
                    TextComponent(text='Brown Cafe', weight='bold', size='xl'),
                    # review
                    BoxComponent(
                        layout='baseline',
                        margin='md',
                        contents=[
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/grey_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/gold_star.png'),
                            IconComponent(
                                size='sm',
                                url='https://example.com/grey_star.png'),
                            TextComponent(text='4.0',
                                          size='sm',
                                          color='#999999',
                                          margin='md',
                                          flex=0)
                        ]),
                    # info
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        spacing='sm',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Place',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=1),
                                    TextComponent(text='Shinjuku, Tokyo',
                                                  wrap=True,
                                                  color='#666666',
                                                  size='sm',
                                                  flex=5)
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(text='Time',
                                                  color='#aaaaaa',
                                                  size='sm',
                                                  flex=1),
                                    TextComponent(
                                        text="10:00 - 23:00",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                        ],
                    )
                ],
            ),
            footer=BoxComponent(
                layout='vertical',
                spacing='sm',
                contents=[
                    # callAction, alamatAction
                    SpacerComponent(size='sm'),
                    # callAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='CALL', uri='tel:000000'),
                    ),
                    # alamatAction
                    ButtonComponent(style='link',
                                    height='sm',
                                    action=URIAction(
                                        label='WEBSITE',
                                        uri="https://example.com"))
                ]),
        )
        message = FlexSendMessage(alt_text="hello", contents=bubble)
        line_bot_api.reply_message(event.reply_token, message)
    elif text == 'quick_reply':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Quick reply',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=PostbackAction(label="label1", data="data1")),
                    QuickReplyButton(
                        action=MessageAction(label="label2", text="text2")),
                    QuickReplyButton(action=DatetimePickerAction(
                        label="label3", data="data3", mode="date")),
                    QuickReplyButton(action=CameraAction(label="label4")),
                    QuickReplyButton(action=CameraRollAction(label="label5")),
                    QuickReplyButton(action=LocationAction(label="label6")),
                ])))
    elif text == '.help':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text=
                'Berikut merupakan command yang terdapat pada BOT ini: \n1. info_grapari\n2. profile\n3. bye\n4. confirm\n5. buttons\n6. carousel\n7 image\n8 image carousel\n9 imagemap\n10 flex\n11 quick_reply\n12 info\n13 about\n14 ip',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=MessageAction(label="profile", text="profile")),
                    QuickReplyButton(
                        action=MessageAction(label="bye", text="bye")),
                    QuickReplyButton(
                        action=MessageAction(label="confirm", text="confirm")),
                    QuickReplyButton(
                        action=MessageAction(label="buttons", text="buttons")),
                    QuickReplyButton(action=MessageAction(label="carousel",
                                                          text="carousel")),
                    QuickReplyButton(
                        action=MessageAction(label="image", text="image")),
                    QuickReplyButton(action=MessageAction(
                        label="image carousel", text="image carousel")),
                    QuickReplyButton(action=MessageAction(label="imagemap",
                                                          text="imagemap")),
                    QuickReplyButton(
                        action=MessageAction(label="flex", text="flex")),
                    QuickReplyButton(action=MessageAction(label="quick_reply",
                                                          text="quick_reply")),
                    QuickReplyButton(
                        action=MessageAction(label="info", text="info")),
                    QuickReplyButton(
                        action=MessageAction(label="about", text="about")),
                    QuickReplyButton(
                        action=MessageAction(label="your ip", text="ip"))
                ])))
    elif text == 'info':
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text=''))
    elif text == 'about':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Ini merupakan bot yang masih dalam proses pengembangan.')
        )
    elif text == 'ip':
        res = requests.get('https://ipinfo.io/')
        data = res.json()
        # your_ip = data['ip']
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text=('alamat IP : ' + data['ip'] + '\nhostname : ' +
                      data['hostname'] + '\nKota : ' + data['city'] +
                      '\nNegara : ' + data['country'] + '\nLokasi : ' +
                      data['loc'] + '\nOrganisasi : ' + data['org'])))
    else:
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Need help? click this button .help',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=MessageAction(label="help", text=".help"))
                ])))
Пример #11
0
def process_postback_event(event):
    result_message_array = []
    replyJsonPath = r"./static/material/{0}/reply.json".format(
        event.postback.data)
    #print("replyJsonPath:", replyJsonPath)
    #print("answer:", event.postback.data.find(":::Q"))
    user_profile = line_bot_api.get_profile(event.source.user_id)
    #print("user_profile:", type(json.dumps(vars(user_profile),sort_keys=True)))
    userName = json.loads(json.dumps(vars(user_profile),
                                     sort_keys=True))["display_name"]
    cityMapping = {"TPE": "雙北", "KL": "基隆市", "IL": "宜蘭縣", "TY": "桃園市"}
    if event.postback.data == "question":
        replyJsonPath = r"./static/material/Question1/reply.json"
        result_message_array = detect_json_array_to_new_message_array(
            replyJsonPath)
        line_bot_api.reply_message(event.reply_token, result_message_array)
    elif event.postback.data.find(":::Q") >= 1:
        idx = event.postback.data[5:6]
        #print("idx:", idx)
        #if idx == "5":
        if idx == "4":
            #print("return result")
            timestamp = datetime.datetime.now().strftime("%Y%m%d")
            answer = event.postback.data[9:]
            key = "{0}-{1}".format(userName, timestamp)
            try:
                util.redisLPush(key, answer)

                allAnswer = util.redisLRange(key, 0, -1)
                # print("allAnswer:", allAnswer)
                doc = {}
                score = 0
                for an in allAnswer:
                    score += 1
                    doc[util.answerMapping[score - 1][an]] = score
                util.sendKafkaMsg("questionaire", doc, key)

                elkDoc = {}
                elkDoc["key"] = key
                elkDoc["UserName"] = userName
                elkDoc["DateTime"] = datetime.datetime.now()
                mappingList = util.getMappingList()
                for i, an in enumerate(allAnswer):
                    elkDoc["item{0}".format(i + 1)] = mappingList[i][an]

                util.insertELK("questionaire-2", elkDoc)
            except Exception as e:
                print(e)
            finally:
                #把redis資料清空
                util.redisLPopAll(key)
        else:
            timestamp = datetime.datetime.now().strftime("%Y%m%d")
            answer = event.postback.data[9:]
            util.redisLPush("{0}-{1}".format(userName, timestamp), answer)

            replyJsonPath = r"./static/material/Question{0}/reply.json".format(
                int(idx) + 1)
            result_message_array = detect_json_array_to_new_message_array(
                replyJsonPath)
            line_bot_api.reply_message(event.reply_token, result_message_array)
    elif event.postback.data.find(":::R") >= 1:
        areaList = ["臺北市", "新北市", "基隆市", "宜蘭縣", "桃園市"]
        idx = int(event.postback.data[5:6])
        #print("idx:", idx)
        siteList = util.getSiteListByArea(areaList[idx])
        urlList = util.getUrlList()
        randomlist = random.sample([x for x in range(len(siteList))], 5)
        # print("randomlist:", randomlist)
        replyJsonPath = r"./static/material/recommedation/reply.json"
        with open(replyJsonPath, 'r', encoding="utf-8") as f:
            replyMsg = f.read()

        # print("replyMsg:", replyMsg)
        for i, r in enumerate(randomlist):
            replyMsg = replyMsg.replace("site{}".format(i + 1), siteList[r])
            try:
                replyMsg = replyMsg.replace("http://{}".format(i + 1),
                                            urlList[r])
            except:
                print("index out of range")

        # print("replyMsg:", replyMsg)
        line_bot_api.reply_message(
            event.reply_token,
            TemplateSendMessage.new_from_json_dict(json.loads(replyMsg)))

    elif event.postback.data.find("Photo") > 1:
        ## 點擊後,切換至照片相簿選擇
        cameraRollQRB = QuickReplyButton(action=CameraRollAction(label="選擇照片"))

        quickReplyList = QuickReply(items=[cameraRollQRB])
        key = "{0}-Photo".format(userName)
        util.redisDelKey(key)
        city = event.postback.data.split("_")[0]
        util.redisSetData(key, cityMapping[city])

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='選擇照片', quick_reply=quickReplyList))
    elif event.postback.data.find("Camera") > 1:
        ## CameraAction
        cameraQuickReplyButton = QuickReplyButton(action=CameraAction(
            label="拍照"))
        quickReplyList = QuickReply(items=[cameraQuickReplyButton])

        key = "{0}-Photo".format(userName)
        util.redisDelKey(key)
        city = event.postback.data.split("_")[0]
        util.redisSetData(key, cityMapping[city])

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='拍照上傳', quick_reply=quickReplyList))
    elif event.postback.data == "recommedation":
        siteList = util.getSiteList()
        urlList = util.getUrlList()
        #randomlist = random.sample([x for x in range(1000)], 5)
        #print("randomlist:", randomlist)
        with open(replyJsonPath, 'r', encoding="utf-8") as f:
            replyMsg = f.read()

        timestamp = datetime.datetime.now().strftime("%Y%m%d")
        key = "{0}-{1}-re".format(userName, timestamp)

        if util.getRedis(True).exists(key):
            reSite = util.redisLRange(key, 0, -1)

            # print("reSite:", reSite)
            # for i, r in enumerate(randomlist):
            for i, r in enumerate(reSite):
                # replyMsg = replyMsg.replace("site{}".format(i + 1), siteList[r])
                # replyMsg = replyMsg.replace("http://{}".format(i + 1), urlList[r])
                replyMsg = replyMsg.replace("site{}".format(i + 1), r)
                replyMsg = replyMsg.replace("http://{}".format(i + 1),
                                            urlList[siteList.index(r)])
            # print("replyMsg:", replyMsg)
            line_bot_api.reply_message(
                event.reply_token,
                TemplateSendMessage.new_from_json_dict(json.loads(replyMsg)))
        else:
            replyJsonPath = r"./static/material/Question1/reply.json"
            result_message_array = detect_json_array_to_new_message_array(
                replyJsonPath)
            line_bot_api.reply_message(event.reply_token, result_message_array)
    else:
        result_message_array = detect_json_array_to_new_message_array(
            replyJsonPath)
        line_bot_api.reply_message(event.reply_token, result_message_array)
Пример #12
0
    def handle_message(self, event):
        self._message_data_save(event)

        text = event.message.text
        if text == 'finished':
            try:
                user_data = LineInputData.objects.filter(user_id=event.source.user)
                user = User.create(
                    first_name=user_data.object.filter(question='first_name').answer,
                    last_name=user_data.object.filter(question='last_name').answer,
                )
                user_info = UserInfo.create(
                    user=user,
                    motive=user_data.object.filter(question='motive').answer,
                )
                job_histories_count = user_data.filter(question__startwith='job_history').count
                for i in range(job_histories_count):
                    JobHistory.create(
                        user_info=user_info,
                        start_date=user_data.object.filter(question=f'start_date_{i}').answer,
                        end_date=user_data.object.filter(question=f'end_date_{i}').answer,
                        history=user_data.object.filter(question=f'job_history_{i}').answer,
                    )
                logger.info(f'Create user:{user.id} user_info:{user_info.id}')
            except Exception:
                raise DataError

        elif text == 'profile':
            if isinstance(event.source, SourceUser):
                profile = self.line_bot_api.get_profile(event.source.user_id)
                self.line_bot_api.reply_message(
                    event.reply_token, [
                        TextSendMessage(text='Display name: ' +
                                        profile.display_name),
                        TextSendMessage(text='Status message: ' +
                                        profile.status_message)
                    ]
                )
            else:
                self.line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text="Bot can't use profile API without user ID"))
        elif text == 'bye':
            if isinstance(event.source, SourceGroup):
                self.line_bot_api.reply_message(
                    event.reply_token, TextSendMessage(text='Leaving group'))
                self.line_bot_api.leave_group(event.source.group_id)
            elif isinstance(event.source, SourceRoom):
                self.line_bot_api.reply_message(
                    event.reply_token, TextSendMessage(text='Leaving group'))
                self.line_bot_api.leave_room(event.source.room_id)
            else:
                self.line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(text="Bot can't leave from 1:1 chat"))
        elif text == 'confirm':
            confirm_template = ConfirmTemplate(text='Do it?', actions=[
                MessageAction(label='Yes', text='Yes!'),
                MessageAction(label='No', text='No!'),
            ])
            template_message = TemplateSendMessage(
                alt_text='Confirm alt text', template=confirm_template)
            self.line_bot_api.reply_message(event.reply_token, template_message)
        elif text == 'buttons':
            buttons_template = ButtonsTemplate(
                title='My buttons sample', text='Hello, my buttons', actions=[
                    URIAction(label='Go to line.me', uri='https://line.me'),
                    PostbackAction(label='ping', data='ping'),
                    PostbackAction(label='ping with text', data='ping', text='ping'),
                    MessageAction(label='Translate Rice', text='米')
                ])
            template_message = TemplateSendMessage(
                alt_text='Buttons alt text', template=buttons_template)
            self.line_bot_api.reply_message(event.reply_token, template_message)
        elif text == 'carousel':
            carousel_template = CarouselTemplate(columns=[
                CarouselColumn(text='hoge1', title='fuga1', actions=[
                    URIAction(label='Go to line.me', uri='https://line.me'),
                    PostbackAction(label='ping', data='ping')
                ]),
                CarouselColumn(text='hoge2', title='fuga2', actions=[
                    PostbackAction(label='ping with text', data='ping', text='ping'),
                    MessageAction(label='Translate Rice', text='米')
                ]),
            ])
            template_message = TemplateSendMessage(
                alt_text='Carousel alt text', template=carousel_template)
            self.line_bot_api.reply_message(event.reply_token, template_message)
        elif text == 'image_carousel':
            image_carousel_template = ImageCarouselTemplate(columns=[
                ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                    action=DatetimePickerAction(label='datetime',
                                                                data='datetime_postback',
                                                                mode='datetime')),
                ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                    action=DatetimePickerAction(label='date',
                                                                data='date_postback',
                                                                mode='date'))
            ])
            template_message = TemplateSendMessage(
                alt_text='ImageCarousel alt text', template=image_carousel_template)
            self.line_bot_api.reply_message(event.reply_token, template_message)
        elif text == 'imagemap':
            pass
        elif text == 'flex':
            bubble = BubbleContainer(
                direction='ltr',
                hero=ImageComponent(
                    url='https://example.com/cafe.jpg',
                    size='full',
                    aspect_ratio='20:13',
                    aspect_mode='cover',
                    action=URIAction(uri='http://example.com', label='label')
                ),
                body=BoxComponent(
                    layout='vertical',
                    contents=[
                        # title
                        TextComponent(text='Brown Cafe', weight='bold', size='xl'),
                        # review
                        BoxComponent(
                            layout='baseline',
                            margin='md',
                            contents=[
                                IconComponent(
                                    size='sm', url='https://example.com/gold_star.png'),
                                IconComponent(
                                    size='sm', url='https://example.com/grey_star.png'),
                                IconComponent(
                                    size='sm', url='https://example.com/gold_star.png'),
                                IconComponent(
                                    size='sm', url='https://example.com/gold_star.png'),
                                IconComponent(
                                    size='sm', url='https://example.com/grey_star.png'),
                                TextComponent(text='4.0', size='sm', color='#999999', margin='md', flex=0)
                            ]
                        ),
                        # info
                        BoxComponent(
                            layout='vertical',
                            margin='lg',
                            spacing='sm',
                            contents=[
                                BoxComponent(
                                    layout='baseline',
                                    spacing='sm',
                                    contents=[
                                        TextComponent(
                                            text='Place',
                                            color='#aaaaaa',
                                            size='sm',
                                            flex=1
                                        ),
                                        TextComponent(
                                            text='Shinjuku, Tokyo',
                                            wrap=True,
                                            color='#666666',
                                            size='sm',
                                            flex=5
                                        )
                                    ],
                                ),
                                BoxComponent(
                                    layout='baseline',
                                    spacing='sm',
                                    contents=[
                                        TextComponent(
                                            text='Time',
                                            color='#aaaaaa',
                                            size='sm',
                                            flex=1
                                        ),
                                        TextComponent(
                                            text="10:00 - 23:00",
                                            wrap=True,
                                            color='#666666',
                                            size='sm',
                                            flex=5,
                                        ),
                                    ],
                                ),
                            ],
                        )
                    ],
                ),
                footer=BoxComponent(
                    layout='vertical',
                    spacing='sm',
                    contents=[
                        # callAction, separator, websiteAction
                        SpacerComponent(size='sm'),
                        # callAction
                        ButtonComponent(
                            style='link',
                            height='sm',
                            action=URIAction(label='CALL', uri='tel:000000'),
                        ),
                        # separator
                        SeparatorComponent(),
                        # websiteAction
                        ButtonComponent(
                            style='link',
                            height='sm',
                            action=URIAction(
                                label='WEBSITE', uri="https://example.com")
                        )
                    ]
                ),
            )
            message = FlexSendMessage(alt_text="hello", contents=bubble)
            self.line_bot_api.reply_message(
                event.reply_token,
                message
            )
        elif text == 'quick_reply':
            self.line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text='Quick reply',
                    quick_reply=QuickReply(
                        items=[
                            QuickReplyButton(
                                action=PostbackAction(label="label1", data="data1")
                            ),
                            QuickReplyButton(
                                action=MessageAction(label="label2", text="text2")
                            ),
                            QuickReplyButton(
                                action=DatetimePickerAction(label="label3", data="data3",
                                                            mode="date")
                            ),
                            QuickReplyButton(
                                action=CameraAction(label="label4")
                            ),
                            QuickReplyButton(
                                action=CameraRollAction(label="label5")
                            ),
                            QuickReplyButton(
                                action=LocationAction(label="label6")
                            ),
                        ])))
        elif text == "liff":
            self.line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(
                        text='https://line.me/R/app/1615588360-p4vKyQMV'),
                ]
            )
        elif text == "purchase":
            previous_bot_message = "question"
            self.line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(text='商品の購入ですね!\nそれではいくつか質問させてもらいますね。'),
                    TextSendMessage(text='これから購入のための情報をお聞きしますが、'),
                    ConfirmTemplate(
                        action=[
                            MessageAction(
                                label='chat',
                                text='ちゃっとで答える'
                            ),
                            MessageAction(
                                label='webpage',
                                text='Webページで入力する'
                            ),
                        ]
                    )
                ]
            )
        elif previous_bot_message == "question" and text == "chat":
            previous_bot_message = "name"
            self.line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(text='ありがとうございます!!'),
                    TextSendMessage(text='さっそくお名前を教えてもらえますか?'),

                ]
            )
Пример #13
0
def create_richmenu():
    """
    Create richmenu.

    Parameters
    ----------
    None

    Returns
    -------
    None

    Raises
    ------
    None
    """

    rich_menu_to_create = RichMenu(
        size=RichMenuSize(width=2500, height=1686),
        selected=False,
        name='richmenu',
        chat_bar_text='Menu',
        areas=[
            RichMenuArea(bounds=RichMenuBounds(x=W * 0,
                                               y=H * 0,
                                               width=W,
                                               height=H),
                         action=URIAction(uri=f"{ENDPOINT}/bookmark",
                                          label="bookmark")),
            RichMenuArea(bounds=RichMenuBounds(x=W * 1,
                                               y=H * 0,
                                               width=W,
                                               height=H),
                         action=URIAction(uri=f"{ENDPOINT}/history",
                                          label="history")),
            RichMenuArea(bounds=RichMenuBounds(x=W * 2,
                                               y=H * 0,
                                               width=W,
                                               height=H),
                         action=CameraRollAction(label="cameraroll")),
            RichMenuArea(bounds=RichMenuBounds(x=W * 0,
                                               y=H * 1,
                                               width=W,
                                               height=H),
                         action=URIAction(uri=f"{ENDPOINT}/library",
                                          label="library")),
            RichMenuArea(bounds=RichMenuBounds(x=W * 1,
                                               y=H * 1,
                                               width=W,
                                               height=H),
                         action=URIAction(uri=f"{ENDPOINT}/option",
                                          label="option")),
            RichMenuArea(bounds=RichMenuBounds(x=W * 2,
                                               y=H * 1,
                                               width=W,
                                               height=H),
                         action=MessageAction(text="help"))
        ])
    richMenuId = line_bot_api.create_rich_menu(rich_menu=rich_menu_to_create)

    # upload an image for rich menu
    path = "flaskr/static/images/richmenu/image.jpg"

    with open(path, 'rb') as f:
        line_bot_api.set_rich_menu_image(richMenuId, "image/jpeg", f)

    # set the default rich menu
    line_bot_api.set_default_rich_menu(richMenuId)
Пример #14
0
# 設定 Server 啟用細節
app = Flask(__name__, static_url_path="/images", static_folder="./images/")

# 生成實體物件
line_bot_api = LineBotApi(secretFileContentJson.get("LINE_CHANNEL_ACCESS_TOKEN"))
handler = WebhookHandler(secretFileContentJson.get("LINE_CHANNEL_SECRET"))

# 創建 QuickReplyButton
## 點擊後,開啟相機
cameraQuickReplyButton = QuickReplyButton(
    action=CameraAction(label="拍照")
)

## 點擊後,切換至照片相簿選擇
cameraRollQRB = QuickReplyButton(
    action=CameraRollAction(label="相簿")
)

## 設計 QuickReplyButton 的 List
quickReplyList = QuickReply(
    items = [cameraQuickReplyButton, cameraRollQRB]
)

## 將 quickReplyList 塞入 TextSendMessage 中
quickReplyTextSendMessage = TextSendMessage(text='請選擇功能', quick_reply=quickReplyList)

# 建立 quickReply 關鍵字字典
template_message_dict = {
    "@功能": quickReplyTextSendMessage
}