Esempio n. 1
0
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 = './ai_tree/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(
            "./ai_tree/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:
        model_type = query_string_dict.get('model')[0].split('_')[0]
        clr_type = query_string_dict.get('model')[0].split('_')[1]

        cameraQuickReplyButton = QuickReplyButton(action=CameraAction(
            label="カメラ"))
        cameraRollQRB = QuickReplyButton(action=CameraRollAction(label="写真"))
        quickReplyList = QuickReply(
            items=[cameraRollQRB, cameraQuickReplyButton])
        quickReplyTextSendMessage = TextSendMessage(text='写真をお送りください:' + \
                                                   ('樹形' if clr_type == 'tree' else '葉子')
                                                    , 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("./ai_tree/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('./static/images/' + event.message.id + '.jpg',
                      'wb') as fd:
                for chunk in message_content.iter_content():
                    fd.write(chunk)

            # model處理圖片
            input_path = "./static/images/" + event.message.id + ".jpg"
            conf_path = './ai_tree/ai_model/' + model_type + '/config_' + clr_type + '.json'
            if model_type == 'yolov3':
                output_path = "./static/images/yolov3_output/"
                image_url = 'https://' + server_url + '/static/images/yolov3_output/' + event.message.id + '.jpg'
                yolo_predict(conf_path, input_path, output_path,
                             infer_models['yolov3_' + clr_type])
                reply = ImageSendMessage(original_content_url=image_url,
                                         preview_image_url=image_url)
            else:
                ans = clr_pred(input_path, conf_path,
                               infer_models['clr_' + clr_type])
                reply = TextSendMessage(text='これは:' + ans + 'です')
            print(model_type + ('樹形' if clr_type == 'tree' else '葉') + "スタート")

            # 回覆文字消息與 回傳照片
            line_bot_api.reply_message(
                event.reply_token,
                [
                    TextSendMessage(text='物体検出の結果:' if model_type == 'yolov3' \
                                                        else '画像認識の結果:'+ \
                                        ('樹形' if clr_type == 'tree' else '葉')),
                    reply
                ]
            )
Esempio n. 2
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",
                "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",
                                }
                            },
                        ]
                    }
                }]
            })
Esempio n. 3
0
def handle_text_message(event):
    text = event.message.text
    if text == 'Hello':
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage('Hi There!!'))
    elif text.lower() == 'getridch':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                text='What you can do',
                title='Seller',
                actions=[
                    CameraAction(label='Take a photo'),
                    # CameraRollAction(label='Choose a photo'),
                ]),
            CarouselColumn(
                text='What you can do',
                title='Buyer',
                actions=[
                    PostbackAction(label='Get near by trash',
                                   data='getNearbyLocation',
                                   text='Show location'),
                    # 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 == 'menu':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Quick reply',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(action=PostbackAction(label="getridch",
                                                           data="getridch")),
                    QuickReplyButton(action=CameraAction(label="Camera")),
                    QuickReplyButton(action=CameraRollAction(
                        label="Camera Roll")),
                    QuickReplyButton(action=LocationAction(label="Location")),
                    QuickReplyButton(action=DatetimePickerAction(
                        label="Date", data="data3", mode="date")),
                ])))
    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.user_id))
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text="Bot can't use profile API without user ID"))
    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 == '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 == 'list':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='What you can do',
                           title='Seller',
                           actions=[
                               CameraAction(label='Take a photo'),
                               PostbackAction(label='ping', data='ping')
                           ]),
            CarouselColumn(text='Options',
                           title='Buyer',
                           actions=[
                               PostbackAction(label='Test 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 == 'KBTG':
        confirm_template = ConfirmTemplate(text='Confirm Address : KBTG ?',
                                           actions=[
                                               PostbackAction(
                                                   label='Confirm',
                                                   data='cfaddress'),
                                               PostbackAction(label='cancel',
                                                              data='getridch',
                                                              text='cancel'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
Esempio n. 4
0
# 載入 line secret key
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')
Esempio n. 5
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='さっそくお名前を教えてもらえますか?'),

                ]
            )
        CarouselColumn(
            thumbnail_image_url=
            'https://media.istockphoto.com/photos/womens-clothes-set-isolatedfemale-clothing-collage-picture-id1067767654',  # noqa:E501
            title='今月のおススメ商品',
            text='これがあれば困らない!',
            actions=[
                MessageAction(label='Recommended', text='Choose Recommended')
            ]),
        CarouselColumn(
            thumbnail_image_url=
            'https://media.istockphoto.com/photos/clothes-hanging-on-rail-in-white-wardrobe-picture-id518597694',  # noqa:E501
            title='スッキリ収納特集',
            text='大切なお洋服をスッキリ簡単に収納します',
            actions=[
                MessageAction(label='To receive clothes',
                              text='Choose receive clothes')
            ])
    ]))

const.QUICK_REPLY_ITEMS = [
    QuickReplyButton(action=LocationAction(label='位置情報')),
    QuickReplyButton(action=CameraAction(label='カメラ起動')),
    QuickReplyButton(action=CameraRollAction(label='カメラロール起動')),
]

const.MENU_LIST = {
    'message': os.getenv('RICH_MENU_MESSAGE', None),
    'carousel': os.getenv('RICH_MENU_CAROUSEL', None),
    'flex': os.getenv('RICH_MENU_FLEX', None)
}
Esempio n. 7
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 == '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")),
                ])))
    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=event.message.text))
Esempio n. 8
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)
                try:
                    if urlList[siteList.index(r)] == "":
                        assert ("url is empty")
                    replyMsg = replyMsg.replace("http://{}".format(i + 1),
                                                urlList[siteList.index(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)))
        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)
    elif event.postback.data == "hotsite":
        areaList = ["臺北市", "新北市", "基隆市", "宜蘭縣", "桃園市"]
        placeDic = {
            "新北市": [
                "九份老街", "野柳地質公園", "淡水老街", "猴硐車站", "紅毛城", "鶯歌老街", "金瓜寮魚蕨步道",
                "朱銘美術館", "烏來風景區", "福隆海水浴場"
            ],
            "臺北市": [
                "士林官邸", "饒河街觀光夜市", "北投圖書館", "國立故宮博物院", "中正紀念堂", "台北101",
                "軍艦岩親山步道", "陽明山夜景", "四四南村", "關渡碼頭", "士林觀光夜市"
            ],
            "基隆市": [
                "和平島", "基隆廟口", "情人湖濱海大道", "阿根納造船廠", "白米甕砲台", "正濱漁港", "潮境公園",
                "劉銘傳隧道", "八斗子公園", "大武崙砲台"
            ],
            "桃園市": [
                "小烏來天空步道", "石門水庫", "大溪老街", "拉拉山巨木群", "角板山行館", "東眼山森林遊樂區",
                "巴陵古道生態園區", "中原夜市", "小人國", "馬祖新村眷村文創園區"
            ],
            "宜蘭縣": [
                "金車咖啡城堡", "外澳沙灘", "蘭陽博物館", "礁溪溫泉", "望龍埤", "福山植物園", "羅東夜市",
                "太平山森林遊樂區", "東澳灣‧粉鳥林漁港", "幾米主題廣場"
            ]
        }
        siteList = util.getSiteList()
        urlList = util.getUrlList()

        with open(replyJsonPath, 'r', encoding="utf-8") as f:
            replyMsg = f.read()

        idx = 1
        for area in areaList:
            for i in range(3):
                r = placeDic[area][i]
                print(r)
                if idx == 1:
                    replyMsg = replyMsg.replace("siteA", r)
                    replyMsg = replyMsg.replace("https://A",
                                                urlList[siteList.index(r)])
                elif idx == 2:
                    replyMsg = replyMsg.replace("siteB", r)
                    replyMsg = replyMsg.replace("https://B",
                                                urlList[siteList.index(r)])
                else:
                    replyMsg = replyMsg.replace("site{}".format(idx), r)
                    replyMsg = replyMsg.replace("https://{}".format(idx),
                                                urlList[siteList.index(r)])
                idx += 1

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

    else:
        result_message_array = detect_json_array_to_new_message_array(
            replyJsonPath)
        line_bot_api.reply_message(event.reply_token, result_message_array)
Esempio n. 9
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"))
    if text == 'how':
        how = 'Available Commands \n /guide'
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=how))
    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(
                thumbnail_image_url=
                'https://1.bp.blogspot.com/-NRqCUkKHH-Q/VW6EUFzLiII/AAAAAAAAUNQ/DlcsA2ETA6k/s640/Brown%2BLINE%2Ba.jpe',
                image_background_color='#FFFFFF',
                text=
                'Enjoy delicious food with a great atmoshpere at our place',
                title='Brown Cafe',
                actions=[
                    URIAction(label='Reserve', uri='https://line.me'),
                    PostbackAction(label='Call', data='ping')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://1.bp.blogspot.com/-NRqCUkKHH-Q/VW6EUFzLiII/AAAAAAAAUNQ/DlcsA2ETA6k/s640/Brown%2BLINE%2Ba.jpe',
                image_background_color='#FFFFFF',
                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 == '/guide':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(
                image_url=
                'https://image.flaticon.com/icons/png/512/229/229374.png',
                action=PostbackAction(label='Restauran',
                                      data='search_restaurant',
                                      text='Cari Restauran')),
            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 == 'lokasi':
        line_bot_api.reply_message(
            event.reply_token,
            LocationMessage(
                text='Lokasi Kamu',
                title='Lokasi Kamu',
                type='location',
                address=
                'Pasaraya Blok M Gedung B Lt. 6, Jalan Iskandarsyah II No.7',
                latitude='-6.2439966',
                longitude='106.8033883'))
    else:
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=event.message.text))
Esempio n. 10
0
def handle_text_message(event):
    text = event.message.text
    user_dict = get_user_identity(event.source.user_id)
    if user_dict['time'] > 10800:
        change_situation(event.source.user_id, 0)
        user_dict['situation'] = 0
    if text == 'getid':
        if isinstance(event.source, SourceUser):
            user_dict = get_user_identity(event.source.user_id)
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(text='id: ' + str(user_dict['id'])),
                TextSendMessage(text='situation: ' +
                                str(user_dict['situation'])),
                TextSendMessage(text='status: ' + str(user_dict['status'])),
            ])
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Cannot connect to the server"))
    elif user_dict['situation'] == 0:
        profile = line_bot_api.get_profile(event.source.user_id)
        change_situation(event.source.user_id, 1)
        temp_text = str(profile.display_name
                        ) + 'さん初めまして、私はお料理お姉さんよ。もしかして、今晩のメニューに悩んでいるんじゃない?'
        confirm_template = ConfirmTemplate(text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif user_dict['situation'] == 1 and text == 'いいえ':
        change_situation(event.source.user_id, 0)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="あら、そうなの。また料理に困ったら声をかけてね!"))
    elif user_dict['situation'] == 1 and text == 'はい':
        change_situation(event.source.user_id, 3)
        temp_text = 'じゃあ私があなたの気分からお料理を提案してあげるわ!今日はお肉の気分?'
        confirm_template = ConfirmTemplate(text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif user_dict['situation'] == 3 and text == 'いいえ':
        change_situation(event.source.user_id, 4)
        temp_text = 'じゃあ海鮮の気分?'
        confirm_template = ConfirmTemplate(text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif user_dict['situation'] == 3 and text == 'はい':
        change_situation(event.source.user_id, 5)
        temp_text = 'ちょっと凝った料理に挑戦してみる?'
        confirm_template = ConfirmTemplate(text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif user_dict['situation'] == 4 and text == 'いいえ':
        change_situation(event.source.user_id, 12)
        temp_text = 'あなたは今日はベジタリアンなのね!じゃあこのお肉を使わない豆腐ハンバーグはどうかな?'
        recipe_dict = get_recipe(6)
        img_url = 'https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/Tofu_Hamburg_steak_20141107.jpg/200px-Tofu_Hamburg_steak_20141107.jpg'
        buttons_template = ButtonsTemplate(thumbnail_image_url=img_url,
                                           title='豆腐ハンバーグ',
                                           text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, [
            template_message,
        ])
    elif user_dict['situation'] == 4 and text == 'はい':
        change_situation(event.source.user_id, 13)
        temp_text = 'じゃあこの「海鮮アボカド」を作ってみない?'
        recipe_dict = get_recipe(7)
        img_url = recipe_dict['img_url']
        buttons_template = ButtonsTemplate(thumbnail_image_url=img_url,
                                           title='海鮮アボカド',
                                           text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, [
            template_message,
        ])
    elif user_dict['situation'] == 5 and text == 'いいえ':
        change_situation(event.source.user_id, 6)
        temp_text = 'がっつりしたものが食べたいの?'
        confirm_template = ConfirmTemplate(text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif user_dict['situation'] == 5 and text == 'はい':
        change_situation(event.source.user_id, 8)
        temp_text = 'じゃあこの「ビーフウェリントン」を作ってみない? とっても豪華なイギリスの肉料理よ!'
        buttons_template = ButtonsTemplate(
            thumbnail_image_url=
            'https://upload.wikimedia.org/wikipedia/commons/thumb/a/ac/Beef_Wellington_-_Crosscut.jpg/800px-Beef_Wellington_-_Crosscut.jpg',
            title='ビーフウェリントン',
            text=temp_text,
            actions=[
                MessageAction(label='はい', text='はい'),
                MessageAction(label='いいえ', text='いいえ'),
            ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, [
            template_message,
        ])
    elif user_dict['situation'] == 6 and text == 'いいえ':
        change_situation(event.source.user_id, 9)
        temp_text = 'じゃあこの「タコライス」はいかが?'
        buttons_template = ButtonsTemplate(
            thumbnail_image_url=
            'https://upload.wikimedia.org/wikipedia/commons/4/45/Taco_Rice1.JPG',
            title='タコライス',
            text=temp_text,
            actions=[
                MessageAction(label='はい', text='はい'),
                MessageAction(label='いいえ', text='いいえ'),
            ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, [
            template_message,
        ])
    elif user_dict['situation'] == 6 and text == 'はい':
        change_situation(event.source.user_id, 7)
        temp_text = 'じゃあこの「ビーフステーキ」がいいんじゃないかしら?'
        buttons_template = ButtonsTemplate(
            thumbnail_image_url=
            'https://upload.wikimedia.org/wikipedia/commons/thumb/4/4c/150418_Awaji_beef_at_Sumoto_Hyogo_pref_Japan02s5.jpg/800px-150418_Awaji_beef_at_Sumoto_Hyogo_pref_Japan02s5.jpg',
            title='ビーフステーキ',
            text=temp_text,
            actions=[
                MessageAction(label='はい', text='はい'),
                MessageAction(label='いいえ', text='いいえ'),
            ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, [
            template_message,
        ])
    elif user_dict['situation'] == 7 and text == 'いいえ':
        change_situation(event.source.user_id, 0)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="う〜ん、難しい子ねえ。また気が向いたら話しかけるのよ!"))
    elif user_dict['situation'] == 7 and text == 'はい':
        change_situation(event.source.user_id, 11)
        recipe_dict = get_recipe(4)
        temp_text = recipe_dict['recipe_text']
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text="やっぱりステーキだよね!じゃあこのレシピにしたがって作ってみるのよ!できたら写真を送ってね〜"),
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] == 8 and text == 'いいえ':
        change_situation(event.source.user_id, 0)
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text="あら、残念。じゃあまた今度ね!"))
    elif user_dict['situation'] == 8 and text == 'はい':
        change_situation(event.source.user_id, 11)
        recipe_dict = get_recipe(2)
        temp_text = recipe_dict['recipe_text']
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text="やった〜!じゃあこのレシピにしたがって作ってみるのよ!できたら写真を送ってね〜"),
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] == 9 and text == 'いいえ':
        change_situation(event.source.user_id, 10)
        temp_text = 'それなら「青椒肉絲」ならどう?'
        buttons_template = ButtonsTemplate(
            thumbnail_image_url=
            'https://upload.wikimedia.org/wikipedia/commons/9/9d/Pepper_steak.jpg',
            title='青椒肉絲',
            text=temp_text,
            actions=[
                MessageAction(label='はい', text='はい'),
                MessageAction(label='いいえ', text='いいえ'),
            ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, [
            template_message,
        ])
    elif user_dict['situation'] == 9 and text == 'はい':
        change_situation(event.source.user_id, 11)
        recipe_dict = get_recipe(3)
        temp_text = recipe_dict['recipe_text']
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text="そうこなくっちゃ!じゃあこのレシピにしたがって作ってみるのよ!できたら写真を送ってね〜"),
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] == 10 and text == 'いいえ':
        change_situation(event.source.user_id, 0)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="う〜ん、難しい子ねえ。また気が向いたら話しかけるのよ!"))
    elif user_dict['situation'] == 10 and text == 'はい':
        change_situation(event.source.user_id, 11)
        recipe_dict = get_recipe(5)
        temp_text = recipe_dict['recipe_text']
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text="今日は中華に挑戦よ!じゃあこのレシピにしたがって作ってみるのよ!できたら写真を送ってね〜"),
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] == 12 and text == 'いいえ':
        change_situation(event.source.user_id, 14)
        temp_text = 'じゃあこのナスとチーズのベジタリアン料理でどうだ〜!!'
        recipe_dict = get_recipe(8)
        img_url = recipe_dict['img_url']
        buttons_template = ButtonsTemplate(thumbnail_image_url=img_url,
                                           title='ナスとチーズのベジタリアン',
                                           text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, [
            template_message,
        ])
    elif user_dict['situation'] == 12 and text == 'はい':
        change_situation(event.source.user_id, 11)
        recipe_dict = get_recipe(6)
        temp_text = recipe_dict['recipe_text']
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text="そうこなくっちゃ! じゃあこのレシピにしたがって作ってみるのよ。完成したら写真を送ってね〜"),
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] == 13 and text == 'いいえ':
        change_situation(event.source.user_id, 15)
        temp_text = 'じゃあこの「ガーリックシュリンプ」ならどうだ!!'
        recipe_dict = get_recipe(9)
        img_url = recipe_dict['img_url']
        buttons_template = ButtonsTemplate(thumbnail_image_url=img_url,
                                           title='ガーリックシュリンプ',
                                           text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Buttons alt text',
                                               template=buttons_template)
        line_bot_api.reply_message(event.reply_token, [
            template_message,
        ])
    elif user_dict['situation'] == 13 and text == 'はい':
        change_situation(event.source.user_id, 11)
        recipe_dict = get_recipe(7)
        temp_text = recipe_dict['recipe_text']
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text="そうこなくっちゃ!じゃあこのレシピにしたがって作ってみるのよ!完成したら写真を送ってね〜"),
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] == 14 and text == 'いいえ':
        change_situation(event.source.user_id, 0)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="もう! 難しいんだから! 勝手にしなさい(≧ヘ≦ )プイッ!!"))
    elif user_dict['situation'] == 14 and text == 'はい':
        change_situation(event.source.user_id, 11)
        recipe_dict = get_recipe(8)
        temp_text = recipe_dict['recipe_text']
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text="じゃあこのレシピにしたがって作ってね!完成したら写真を送るのよ〜"),
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] == 15 and text == 'いいえ':
        change_situation(event.source.user_id, 0)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="もう! 難しいんだから! 勝手にしなさい(≧ヘ≦ )プイッ!!"))
    elif user_dict['situation'] == 15 and text == 'はい':
        change_situation(event.source.user_id, 11)
        recipe_dict = get_recipe(9)
        temp_text = recipe_dict['recipe_text']
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text="じゃあこのレシピにしたがって作ってね!完成したら写真を送るのよ〜"),
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] == 11:
        temp_text = 'できたら写真を送ってね〜'
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text=temp_text),
        ])
    elif user_dict['situation'] >= 1 and user_dict['situation'] <= 15:
        temp_text = '「はい」か「いいえ」で答えてね!'
        confirm_template = ConfirmTemplate(text=temp_text,
                                           actions=[
                                               MessageAction(label='はい',
                                                             text='はい'),
                                               MessageAction(label='いいえ',
                                                             text='いいえ'),
                                           ])
        template_message = TemplateSendMessage(alt_text='Confirm alt text',
                                               template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    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))
Esempio n. 11
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))
Esempio n. 12
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))
Esempio n. 13
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"))
                ])))
Esempio n. 14
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)
Esempio n. 15
0
def process_postback_event(event):
    result_message_array = []
    replyJsonPath = r"./素材/{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"]

    if event.postback.data == "回答幾個問題讓我們更了解您的旅遊喜好吧":
        replyJsonPath = r"./素材/Q1/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":
            print("return result")
            timestamp = datetime.datetime.now().strftime("%Y%m%d")
            answer = event.postback.data[9:]
            key = "{0}-{1}".format(userName, timestamp)
            util.redisLPush(key, answer)

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

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

            util.insertELK("questionaire", elkDoc)
            #把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"./素材/Q{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("Photo") > 1:
        ## 點擊後,切換至照片相簿選擇
        cameraRollQRB = QuickReplyButton(action=CameraRollAction(label="上傳照片"))

        quickReplyList = QuickReply(items=[cameraRollQRB])

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

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='拍照解鎖旅遊成就', quick_reply=quickReplyList))

    else:
        result_message_array = detect_json_array_to_new_message_array(
            replyJsonPath)
        line_bot_api.reply_message(event.reply_token, result_message_array)
Esempio n. 16
0
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)
import backend_aws
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}はじめまして!😃
友だち追加ありがとうございます。Udemy EE LineBot001 です。

顔写真を投稿してね!
""".strip()
# このトークからの通知を受け取らない場合は、画面右上のメニューから通知をオフにしてください。
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 == 'スケジュールを確認':

        #Googleカレンダーからフットサル情報を取得
        events = getSchedule()
        strEvents = ""
        for ev in events:
            JST = datetime.timezone(datetime.timedelta(hours=+9), 'JST')
            jst_time_start = dateutil.parser.parse(
                ev["start"]["dateTime"]).astimezone(JST)
            jst_time_end = dateutil.parser.parse(
                ev["end"]["dateTime"]).astimezone(JST)
            summary = ev["summary"]

            date = jst_time_start.strftime("%Y/%m/%d")  #"2020/4/26"
            date_str = jst_time_start.strftime(
                "%-m/%-d(%a) %-H~") + jst_time_end.strftime(
                    "%-H時")  # '4/26(日) 19時~21時'

            strEvents += date_str + summary + "\n"

        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=strEvents))

    elif text == '参加申込する':
        #Googleカレンダーからフットサル情報を取得
        events = getSchedule()
        cols = []

        for ev in events:
            JST = datetime.timezone(datetime.timedelta(hours=+9), 'JST')
            jst_time_start = dateutil.parser.parse(
                ev["start"]["dateTime"]).astimezone(JST)
            jst_time_end = dateutil.parser.parse(
                ev["end"]["dateTime"]).astimezone(JST)
            summary = ev["summary"]

            date = jst_time_start.strftime("%Y/%m/%d")  #"2020/4/26"
            time_from = jst_time_start.strftime("%H:%M")  #"19:00"
            time_to = jst_time_end.strftime("%H:%M")  #"21:00"
            date_str = jst_time_start.strftime(
                "%-m/%-d(%a) %-H~") + jst_time_end.strftime(
                    "%-H時")  # '4/26(日) 19時~21時'

            column = CarouselColumn(alt_text='参加予約はこちら',
                                    text=summary,
                                    title=date_str,
                                    actions=[
                                        MessageAction(label='予約',
                                                      text='予約する:' + date_str +
                                                      ' ' + summary)
                                    ])
            cols.append(column)

        carousel_template = CarouselTemplate(columns=cols,
                                             imageAspectRatio='square')

        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)

    elif text.startswith('予約する:'):
        #例:予約する:03/22(日) 11時~14時 フットサル@千鳥町
        reserve_date = text.split(':')[1]

        #プロフィール取得
        profile = line_bot_api.get_profile(event.source.user_id)
        name = profile.display_name

        #予約完了:True、予約取り消し:False
        ret = reserveFutsal(name, reserve_date)
        ret_txt = ''

        if ret:
            ret_txt = name + 'さん\n\n' + '【' + reserve_date + '】の予約を完了しました❗\n\n'
        else:
            ret_txt = name + 'さん\n' + '【' + reserve_date + '】の予約を取り消しました❗\n\n'

        ret_txt = ret_txt + '予約状況の確認はメニューの「参加状況確認」をタップ⚽'

        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text=ret_txt),
        ])

    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))
Esempio n. 19
0
def message_type(event):
    # ตอบ user ที่ user พิมพ์เข้ามาเป็น Text
    # print(event)
    # texts = event['message']['type']
    texts = event.message.text
    print("Your Message :",texts)
    # userId = event_handler_add()[0]
    userId = event.message.id
    print("Your UserId :",userId)
    replyToken = event.reply_token
    print("Your replyToken :",replyToken)
    # TextSendMessage(text= 'สวัสดี 😀')
    if texts == "ไง":
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='กรุณาเลือกหัวข้อ',
                               quick_reply=QuickReply(items=[
                                   QuickReplyButton(image_url="https://media2.giphy.com/media/R3IxJW14a3QNa/giphy.gif?cid=ecf05e47ptuw3dl3x03u0i97mqhit3ryu9m5zipi90sokouz&rid=giphy.gif",action=MessageAction(label="สวัสดี", text="ยินดีต้อนรับ")),
                                  QuickReplyButton(image_url="https://static.wixstatic.com/media/afc648_7e70f2fcc96443efaa236f0fe18ac3d0~mv2.gif",action=CameraAction(label="ถ่ายภาพ"))
                               ])))
    elif texts:
        word = chatBot(texts)
        line_bot_api.reply_message(replyToken, TextSendMessage(text=word))
Esempio n. 20
0
 def test_camera(self):
     arg = {'label': 'camera'}
     self.assertEqual(self.serialize_as_dict(arg, type=self.CAMERA),
                      CameraAction(**arg).as_json_dict())
Esempio n. 21
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),
                TextSendMessage(text='user_id: ' + profile.user_id),
                TextSendMessage(text='test picture url: ' +
                                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 == 'Bot':
        confirm_template = ConfirmTemplate(
            text='Photo of Miyuu or Osaka trip?',
            actions=[
                MessageAction(label='Miyuu !', text='Miyuu'),
                MessageAction(label='Osaka Trip !', text='Osaka'),
            ])
        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 == 'Osaka':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/osaka1024.jpg',
                title='Osaka1',
                text='Cooool',
                actions=[
                    PostbackAction(
                        label='Colorful town', text='Cooool', data='Cooool')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/osaka2-1024.jpg',
                title='Osaka2',
                text='Women power',
                actions=[
                    PostbackAction(
                        label='Castle', text='Women power', data='Women power')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/osaka3-1024.jpg',
                title='Osaka3',
                text='Where is this?',
                actions=[
                    PostbackAction(label='Some place !!',
                                   text='Where is this?',
                                   data='Where is this?')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/osaka4-1024.jpg',
                title='Osaka4',
                text='Nice Castle',
                actions=[
                    PostbackAction(label='Another GirlPow',
                                   text='Nice Castle',
                                   data='Nice Castle')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/osaka5-1024.jpg',
                title='Osaka5',
                text='Full face !!',
                actions=[
                    PostbackAction(label='Osaka member',
                                   text='Full face !!',
                                   data='Full face !!')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/osaka6-1024.jpg',
                title='Osaka6',
                text='Tired ??',
                actions=[
                    PostbackAction(
                        label='Mom Power!!', text='Tired ??', data='Tired ??')
                ])
        ])
        template_message = TemplateSendMessage(alt_text='Carousel alt text',
                                               template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'Miyuu':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/miyuu1024-1.jpg',
                text='Miyuu#1',
                actions=[
                    PostbackAction(
                        label='Best Friend', text='Elvis', data='Elvis')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/miyuu1024-2.jpg',
                text='Miyuu#2',
                actions=[
                    PostbackAction(label='GreatWolfLodge',
                                   text='Water park',
                                   data='Water park')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/miyuu1024-3.jpg',
                text='Miyuu#3',
                actions=[
                    PostbackAction(
                        label='Miyuu Cycle', text='Arcade', data='Arcade')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/miyuu1024-4.jpg',
                text='Miyuu#4',
                actions=[
                    PostbackAction(
                        label='Bath Time', text='Love It', data='Love It')
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://s3-us-west-2.amazonaws.com/awsrobomakerhelloworld-154344673743-bundlesbucket-1n2aine7xqbt8/image/miyuu1024-5.jpg',
                text='Miyuu#5',
                actions=[
                    PostbackAction(
                        label='The Gang', text='The Gang', data='The Gang')
                ])
        ])
        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 == 'Where is mom':
        location_message = LocationSendMessage(type='Where is Mom?',
                                               title='Mom home',
                                               address='Mom',
                                               latitude=13.799750,
                                               longitude=100.641546)
        line_bot_api.reply_message(event.reply_token, location_message)
    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:
        pass
Esempio n. 22
0
def handle_text_message(event):
    text = event.message.text
    profile = line_bot_api.get_profile(event.source.user_id)

    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(
                text='hoge1',
                image_url='https://via.placeholder.com/1024x1024',
                action=DatetimePickerAction(label='datetime',
                                            data='datetime_postback',
                                            mode='datetime')),
            ImageCarouselColumn(
                text='hoge1',
                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 == 'image':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(
                url='http://gosehat.heroku.com/static/image/logo_new.png',
                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='Tentang Aplikasi',
                                  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=
                        'GoSehat merupakan aplikasi konsultasi kesehatan yang dibangun oleh :'
                        '1. Arvianti Yulia Maulfa, 2. Entin Martiana Kusumaningtyas, 3. Fadilah Fahrul Hardiansyah '
                        ''
                        # BoxComponent(
                        #     layout='baseline',
                        #     spacing='sm',
                        #     contents=[
                        #         TextComponent(
                        #             text='GoSehat merupakan aplikasi konsultasi kesehatan yang dibangun oleh :'
                        #                  '1. Arvianti Yulia Maulfa, 2. Entin Martiana Kusumaningtyas, 3. Fadilah Fahrul Hardiansyah '
                        #                  '',
                        #             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.lower() == 'tentang aplikasi':
        url = request.url_root + '/static/image/tentang.png'
        app.logger.info("url=" + url)
        text = 'GoSehat merupakan aplikasi konsultasi kesehatan yang dibangun oleh:\n1. Arvianti Yulia Maulfa \n2. Entin ' \
               'Martiana Kusumaningtyas \n3. Fadilah Fahrul Hardiansyah\n'

        line_bot_api.reply_message(event.reply_token, [
            ImageSendMessage(url, url),
            TextSendMessage(text=text),
        ])
    elif text.lower() == 'informasi aplikasi':
        text = 'GoSehat adalah chatbot (aplikasi pintar) yang dapat digunakan untuk ' \
               'konsultasi kesehatan secara gratis! Anda dapat bertanya seputar kesehatan seperti pengobatan,' \
               'pencegahan, atau penyebab suatu penyakit. \n\nCukup kirim pesan apa yang ingin Anda tanyakan atau ' \
               'memilih menu yang tersedia ya.\ncontoh: "Saya sering mengalami pusing, mual, batuk. Saya ' \
               'sakit apa ?" atau menanyakan informasi seperti "Haloo, untuk obat maag apa ya?" \n\nTahapan pemakaian ' \
               'aplikasi GoSehat :\n1. Ketikkan pesan seperti pada contoh diatas atau pilih menu \n2. Anda bisa ' \
               'mengetikkan gejala untuk mendeteksi penyakit pada tubuh Anda\n3. Anda bisa mengetikkan nama penyakit ' \
               'untuk mengetahui jenis penyakit\n4. Tunggu hingga aplikasi memberikan Anda jawaban\n\nTetap jaga ' \
               'kesehatan ya!'

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=text),
        )
    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:
        conn = create_connection()
        cursor = conn.cursor()

        # set user_id dan profile (untuk nama)
        user_id = event.source.user_id
        name_user = line_bot_api.get_profile(event.source.user_id).display_name
        time = dt.datetime.now()

        if dt.datetime.now() < dt.datetime.now().replace(
                hour=12, minute=0,
                second=0) and dt.datetime.now() > dt.datetime.now().replace(
                    hour=0, minute=0, second=0):
            salam = "Selamat Pagi "
        elif dt.datetime.now() > dt.datetime.now().replace(
                hour=12, minute=0,
                second=0) and dt.datetime.now() < dt.datetime.now().replace(
                    hour=18, minute=0, second=0):
            salam = "Selamat Siang "
        elif dt.datetime.now() > dt.datetime.now().replace(
                hour=18, minute=0, second=0):
            salam = "Selamat Malam "
        else:
            salam = "Assalamualaikum "

        # MENU
        if text == '\informasi':
            messages = "Masukkan informasi yang ingin dicari.\nContoh : 'Apa penyakit maag ?'"
            save_menuinformasi(user_id, name_user, text, conn)
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=(messages)))

        elif text == '\konsultasi':
            save_menukonsultasi(user_id, name_user, text, conn)
            messages = "Masukkan keluhan Anda.\nContoh : 'Saya merasa demam, mual pusing muntih. Saya sakit apa ?'"
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=(messages)))
        else:
            cursor.execute("SELECT status FROM menu WHERE id_user = '******'")
            count_menu = cursor.fetchall()

        # print("DEBUG> count menu = ", count_menu)

        if len(count_menu) != 0:
            if count_menu[0][0] == '\informasi':
                disease_id = 0
                sinonim, penyakit, messages_info = get_info(text)
                if len(penyakit) == 0:
                    messages = check_greeting(sinonim)
                    save_history(user_id, name_user, text, messages, "",
                                 disease_id, time, conn)
                else:
                    messages = salam + name_user + "\n" + messages_info[0][0]
                    save_history(user_id, name_user, text, messages_info[0][0],
                                 "", disease_id, time, conn)
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text=(messages)))
                delete_menukonsultasi(user_id, conn)
            elif count_menu[0][0] == '\konsultasi':
                messages = message_bot(user_id, name_user, salam, text, time,
                                       conn)
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text=(messages)))
                delete_menukonsultasi(user_id, conn)
        else:
            decision = decide_process(text)
            print("DEBUG> pilihan = ", decision)
            if decision == "informasi":
                disease_id = 0
                sinonim, penyakit, messages_info = get_info(text)
                if len(penyakit) == 0 and len(sinonim) <= 2:
                    # gabung_sinonim = ' '.join(sinonim)
                    messages = check_greeting(sinonim)
                    save_history(user_id, name_user, text, messages, "",
                                 disease_id, time, conn)
                else:
                    messages = salam + name_user
                    for msg in messages_info:
                        messages = messages + "\n\n" + msg[0][0]
                    save_history(user_id, name_user, text, messages, "",
                                 disease_id, time, conn)
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text=(messages)))
            else:
                messages = message_bot(user_id, name_user, salam, text, time,
                                       conn)
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text=(messages)))
            delete_menukonsultasi(user_id, conn)
Esempio n. 23
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)),
                TextSendMessage(text='User_id: ' + event.source.user_id),
            ])
        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 == 'audio':
        line_bot_api.reply_message(
            event.reply_token,
            AudioSendMessage(
                original_content_url=
                'https://shareboxnow.com/wp-content/uploads/2020/02/test.m4a',
                duration=2000))
    elif text == 'video':
        line_bot_api.reply_message(
            event.reply_token,
            VideoSendMessage(
                original_content_url=
                'https://shareboxnow.com/wp-content/uploads/2020/02/IMG_0469.mp4',
                preview_image_url=
                'https://shareboxnow.com/wp-content/uploads/2020/02/th.jpeg'))
    elif text == 'location':
        line_bot_api.reply_message(
            event.reply_token,
            LocationSendMessage(title='我未來要爬的山!',
                                address='Himalayas',
                                latitude=28.598316,
                                longitude=83.931061))

    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',
            thumbnail_image_url=
            'https://logos-download.com/wp-content/uploads/2016/10/Python_logo_wordmark-700x203.png',
            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',
                thumbnail_image_url=
                'https://logos-download.com/wp-content/uploads/2016/10/Python_logo_wordmark-700x203.png',
                title='fuga1',
                actions=[
                    URIAction(label='Go to line.me', uri='https://line.me'),
                    PostbackAction(label='ping', data='ping')
                ]),
            CarouselColumn(
                text='hoge2',
                thumbnail_image_url=
                'https://logos-download.com/wp-content/uploads/2016/10/Python_logo_wordmark-700x203.png',
                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="ping")),
                    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))
Esempio n. 24
0
model = tf.keras.models.load_model('catus_04.h5')

# 載入 line secret key
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)