示例#1
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))
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))
示例#3
0
def handle_text_message(event):
    text = event.message.text
    print_source(event)
    if 'aqi' == text.lower():
        line_bot_api.reply_message(
            event.reply_token,
            messages=TextSendMessage(
                text='Please share your location to get an accurate AQI krub',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(action=LocationAction(
                        label='Share Location'))
                ])))

    if 'มองบน' in text.lower():
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(
                image_url=
                'https://media.giphy.com/media/5Wi5ydRYRM28q9Gvyv/giphy.gif',
                action=MessageAction(label='มองบน', text='มองบน'))
        ])
        line_bot_api.reply_message(
            event.reply_token,
            TemplateSendMessage(alt_text='มองบนเรยจ้า',
                                template=image_carousel_template))

    if 'lineqa' in text.lower():
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(
                image_url=
                'https://media.giphy.com/media/4VUugEkI9a9DsKTmW1/giphy.gif',
                action=MessageAction(label='Daebak', text='대박!'))
        ])
        line_bot_api.reply_message(
            event.reply_token,
            TemplateSendMessage(alt_text='대박!',
                                template=image_carousel_template))

    if 'อากาศ' == text or 'weather' == text.lower():
        quick_reply = QuickReply(items=[
            QuickReplyButton(action=LocationAction(label='Send Location')),
            QuickReplyButton(
                action=PostbackAction(label='Tokyo Weather',
                                      data='weather=tokyo',
                                      display_text='Tokyo Weather')),
            QuickReplyButton(
                action=PostbackAction(label='Seoul Weather',
                                      data='weather=seoul',
                                      display_text='Seoul Weather')),
            QuickReplyButton(
                action=PostbackAction(label='London Weather',
                                      data='weather=london',
                                      display_text='London Weather'))
        ])
        reply_message = TextSendMessage(
            text="Let me know your location or place", quick_reply=quick_reply)
        line_bot_api.reply_message(event.reply_token, messages=reply_message)

    m = re.match('weather in (.*)', text.lower())

    if m is not None:
        place_name = m.group(1)
        weather_data = weather.get_weather_data(place_name)
        latlng_data, address = weather.get_latlng_from_place_name(place_name)
        # weather_aqi_data = weather.get_weather_aqi_by_place_name(place_name)
        weather_aqi_station_id = weather_aqi.get_nearest_station(
            latlng_data['lat'], latlng_data['lng'])
        weather_aqi_data = weather_aqi.get_aqi_data(weather_aqi_station_id)
        if isinstance(weather_data, str):
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=weather_data))
        else:
            messages = []
            weather_msg = weather.get_weather_message(weather_data)
            messages.append(
                FlexSendMessage(alt_text="Weather Forecast",
                                contents=weather_msg))
            if weather_aqi_data is not None:
                weather_aqi_msg = weather_aqi.get_aqi_message(weather_aqi_data)
                messages.append(
                    FlexSendMessage(alt_text="Air Quality Index",
                                    contents=weather_aqi_msg))
            # weather_aqi_msg = weather.get_weather_aqi_message(weather_aqi_data)
            # messages.append(weather_aqi_msg)
            # weather.get_weather_aqi_message_v2(weather_aqi_data)
            # weather_aqi_msg_v2 = weather.get_weather_aqi_message_v2(weather_aqi_data)
            # messages.append(weather_aqi_msg_v2)
            line_bot_api.reply_message(event.reply_token, messages=messages)

    n = re.match('flight (.*)', text.lower())
    if n is not None:
        latest_flight = flight_api.get_latest_flight(n.group(1).upper())
        if latest_flight is not None:
            flight_metadata = flight_api.get_flight_metadata(
                latest_flight['flight_number'], latest_flight['adshex'])
            if flight_metadata['success'] is True:
                flight_bubble = flight_api.create_flight_message(
                    latest_flight['flight_number'], latest_flight['adshex'],
                    flight_metadata['payload'])
                messages = []
                messages.append(
                    FlexSendMessage(alt_text="Flight Information",
                                    contents=flight_bubble))
                line_bot_api.reply_message(event.reply_token, messages)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text=
                'Sorry, I can\'t find your flight: {}. Please try another flight number'
                .format(n.group(1).upper())))

    p = re.match('(^[A-Z]{3}-[A-Z]{3}$)', text.upper())
    if p is not None:
        text = p.group(1).upper()
        origin = text.split('-')[0]
        destination = text.split('-')[1]
        flight_route_data = flight_api.get_flight_by_route(origin, destination)
        if flight_route_data is not None:
            carouesel_container = flight_api.create_flight_route_message(
                flight_route_data)
            line_bot_api.reply_message(
                event.reply_token,
                FlexSendMessage(alt_text="Flight {0} Route Info".format(text),
                                contents=carouesel_container))
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Sorry, There is no flight for "{}" route.'.format(text)))

    q = re.match('airport (.*)', text.lower())
    if q is not None:
        text = q.group(1).lower()
        airports = flight_api.get_airport_code(text)
        if airports is not None:
            quick_reply_items = []
            for airport in airports:
                airport_name = (
                    airport['title'][:14] +
                    ' ({0})'.format(airport['url'].split('/')[-1])) if len(
                        airport['title']
                    ) > 14 else airport['title'] + ' ({0})'.format(
                        airport['url'].split('/')[-1])
                quick_reply_items.append({
                    "type": "action",
                    "action": {
                        "type": "postback",
                        "label": airport_name,
                        "data":
                        "airport={0}".format(airport['url'].split('/')[-1])
                    }
                })
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text='Here are possible airports',
                    quick_reply=QuickReply(items=quick_reply_items)))
示例#4
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)
示例#5
0
def handle_message(event):
    input_msg = event.message.text
    # ランダム : ランダムに1店舗紹介する。
    # テキストで返して、その後に2通目のメッセージで詳細を見ますか?でyesならリッチメッセージを送る仕掛け欲しい。postbackactionじゃな。
    # if input_msg in ["ランダム", "random"]:
    #     output_msg = random.choice(restaurant_names)
    #     line_bot_api.reply_message(
    #         event.reply_token,
    #         TextSendMessage(text=output_msg))
    # ちかく:近くのおすすめ店舗を紹介する。
    if input_msg in ["近くのお店", "ちかく", "近く", "near"]:
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='位置情報から近くの店を検索する',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(action=LocationAction(label="位置情報の画面へ")),
                ])))
    elif input_msg in ["お気に入りからランダム", "ランダム"]:
        conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format(
            user, password, host, port_db, database))
        cur = conn.cursor()
        df = pd.read_sql(
            "SELECT favorite_restaurant_name FROM favorite_restaurants WHERE user_id = '{}'"
            .format(event.source.user_id),
            con=conn)
        favorite_restaurant_names = list(df.favorite_restaurant_name.values)
        conn.commit()
        cur.close()
        conn.close()
        num_lists = range(len(favorite_restaurant_names))
        if len(num_lists) > 10:
            favorite_restaurant_nums = random.sample(num_lists,
                                                     k=6)  #仕様上10個まで。
        else:
            favorite_restaurant_nums = random.sample(num_lists,
                                                     k=len(num_lists))

        favorite_restaurants = []
        for favorite_restaurant_num in favorite_restaurant_nums:
            for restaurant in restaurants:
                if favorite_restaurant_names[
                        favorite_restaurant_num] == restaurant.name:
                    favorite_restaurants.append(restaurant)

        favorite_carousel_columns = []
        for favorite_restaurant in favorite_restaurants:
            if json.loads(favorite_restaurant.image_url.replace(
                    '\'', '"'))["shop_image1"] != "":
                image_url = json.loads(
                    favorite_restaurant.image_url.replace('\'',
                                                          '"'))["shop_image1"]
            else:
                image_url = img_restaurant_default
            try:
                if json.loads(favorite_restaurant.pr.replace(
                        '\'', '"'))["pr_short"] != "":
                    pr = json.loads(favorite_restaurant.pr.replace(
                        '\'', '"'))["pr_short"][:60]
                else:
                    pr = "おすすめのお店です"
            except JSONDecodeError:
                pr = "おすすめのお店です"

            favorite_carousel_column = CarouselColumn(
                thumbnail_image_url=image_url,
                title=favorite_restaurant.name,
                text=pr,
                actions=[
                    URIAction(label='ぐるなびへ',
                              uri=favorite_restaurant.url_mobile),
                    MessageAction(label='位置情報をみる',
                                  text='位置情報 ' + favorite_restaurant.name),
                    MessageAction(
                        label="お気に入りから削除する",
                        text="お気に入り削除" + ' ' +
                        favorite_restaurant.name)  # event.source.user_id
                ])
            favorite_carousel_columns.append(favorite_carousel_column)
        if len(favorite_carousel_columns) > 0:
            line_bot_api.reply_message(
                event.reply_token,
                TemplateSendMessage(alt_text='Carousel template',
                                    template=CarouselTemplate(
                                        columns=favorite_carousel_columns)))
        else:
            output_msg = "まだお気に入りがありません。"
            line_bot_api.reply_message(event.reply_token,
                                       TextSendMessage(text=output_msg))

    elif input_msg in ["お気に入り一覧", "一覧"]:
        conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format(
            user, password, host, port_db, database))
        cur = conn.cursor()
        df = pd.read_sql(
            "SELECT favorite_restaurant_name FROM favorite_restaurants WHERE user_id = '{}'"
            .format(event.source.user_id),
            con=conn)
        print(df)
        favorite_restaurant_names = list(df.favorite_restaurant_name.values)
        conn.commit()
        cur.close()
        conn.close()
        if len(favorite_restaurant_names) > 0:
            output_msg = ""
            for favorite_restaurant_name in favorite_restaurant_names:
                output_msg += "•" + favorite_restaurant_name + "\n"
            output_msg = output_msg[:-1]
        else:
            output_msg = "まだお気に入りがありません。"
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=output_msg))

    elif input_msg in ["ランキング"]:
        conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format(
            user, password, host, port_db, database))
        cur = conn.cursor()
        df = pd.read_sql(
            "SELECT count(*) as favorites, favorite_restaurant_name FROM favorite_restaurants GROUP BY favorite_restaurant_name",
            con=conn)
        df = df.sort_values('favorites', ascending=False)
        restaurant_names = df["favorite_restaurant_name"].values.tolist()
        conn.commit()
        cur.close()
        conn.close()

        if len(restaurant_names) > 10:
            restaurant_names = restaurant_names[:10]

        ranking_restaurants = []
        for restaurant_name in restaurant_names:
            for restaurant in restaurants:
                if restaurant.name == restaurant_name:
                    ranking_restaurants.append(restaurant)

        ranking_carousel_columns = []
        for i in range(len(ranking_restaurants)):
            # for ranking_restaurant in ranking_restaurants:
            if json.loads(ranking_restaurants[i].image_url.replace(
                    '\'', '"'))["shop_image1"] != "":
                image_url = json.loads(
                    ranking_restaurants[i].image_url.replace(
                        '\'', '"'))["shop_image1"]
            else:
                image_url = img_restaurant_default
            try:
                if json.loads(ranking_restaurants[i].pr.replace(
                        '\'', '"'))["pr_short"] != "":
                    pr = str(i + 1) + "位: " + json.loads(
                        ranking_restaurants[i].pr.replace(
                            '\'', '"'))["pr_short"][:50]
                else:
                    pr = str(i + 1) + "位: " + "おすすめのお店です"
            except JSONDecodeError:
                pr = str(i + 1) + "位: " + "おすすめのお店です"

            conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format(
                user, password, host, port_db, database))
            cur = conn.cursor()
            cur.execute(
                "SELECT FROM favorite_restaurants WHERE user_id = '{}' and favorite_restaurant_name = '{}';"
                .format(event.source.user_id, ranking_restaurants[i].name))
            if cur.fetchone() is None:
                label_favorite = "お気に入りに追加する"
                text_favorite = "お気に入り追加"
            else:  # もうお気に入りされている。
                label_favorite = "お気に入りから削除する"
                text_favorite = "お気に入り削除"
            conn.commit()
            cur.close()
            conn.close()

            ranking_carousel_column = CarouselColumn(
                thumbnail_image_url=image_url,
                title=ranking_restaurants[i].name,
                text=pr,
                actions=[
                    URIAction(label='ぐるなびへ',
                              uri=ranking_restaurants[i].url_mobile),
                    MessageAction(label='位置情報をみる',
                                  text='位置情報 ' + ranking_restaurants[i].name),
                    MessageAction(
                        label=label_favorite,
                        text=text_favorite + ' ' +
                        ranking_restaurants[i].name)  # event.source.user_id
                ])
            ranking_carousel_columns.append(ranking_carousel_column)
        if len(ranking_carousel_columns) > 0:
            line_bot_api.reply_message(
                event.reply_token,
                TemplateSendMessage(alt_text='Carousel template',
                                    template=CarouselTemplate(
                                        columns=ranking_carousel_columns)))

    elif input_msg in ["ジャンル別"]:
        quickreply_items = []
        for category in restaurant_categories:
            item = QuickReplyButton(
                action=MessageAction(label=category, text=category + "のランキング"))
            quickreply_items.append(item)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='ジャンルを選んで下さい。',
                            quick_reply=QuickReply(items=quickreply_items)))
    elif "ランキング" in input_msg:  # ジャンル別ランキング
        for category in restaurant_categories:
            if category in input_msg:
                # DBからそのジャンルのfavoritesランキングを抽出する。
                conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format(
                    user, password, host, port_db, database))
                cur = conn.cursor()
                df_favorites = pd.read_sql(
                    "SELECT count(*) as favorites, favorite_restaurant_name FROM favorite_restaurants GROUP BY favorite_restaurant_name",
                    con=conn)
                df_favorites = df_favorites.rename(
                    columns={'favorite_restaurant_name': 'name'})
                df_restaurant2 = df_restaurant.copy(deep=False)
                df_favorites_ranking = pd.merge(df_restaurant2,
                                                df_favorites,
                                                on='name',
                                                how='outer')
                df_favorites_ranking = df_favorites_ranking[[
                    "name", "favorites", "category2", "image_url", "url",
                    "url_mobile", "pr"
                ]]
                dict_category = {
                    "和食": "Japanese",
                    "韓国料理": "Korean",
                    "中華": "Chinese",
                    "イタリアン": "Italian",
                    "カフェ": "Cafe",
                    "居酒屋": "Izakaya",
                    "ほか": "others"
                }
                df_favorites_ranking = df_favorites_ranking[
                    df_favorites_ranking["category2"] ==
                    dict_category[category]]
                df_favorites_ranking = df_favorites_ranking.sort_values(
                    "favorites", ascending=False)
                if len(df_favorites_ranking) > 10:
                    df_favorites_ranking = df_favorites_ranking[:9]
                recommend_carousel_columns = []
                for index, row in df_favorites_ranking.reset_index().iterrows(
                ):
                    print(index, row["name"], row.favorites)
                    if json.loads(row.image_url.replace(
                            '\'', '"'))["shop_image1"] != "":
                        image_url = json.loads(row.image_url.replace(
                            '\'', '"'))["shop_image1"]
                    else:
                        # image_url = "https://i.picsum.photos/id/10/200/300.jpg"
                        image_url = img_restaurant_default
                    try:
                        if json.loads(row.pr.replace('\'',
                                                     '"'))["pr_short"] != "":
                            pr = str(index + 1) + "位: " + json.loads(
                                row.pr.replace('\'', '"')
                            )["pr_short"][:
                                          40]  # 60文字までという制限がある。オーバーの時は"..."を表示する。
                        else:
                            pr = str(
                                index +
                                1) + "位: " + "おすすめのお店です"  # もう少し、良いメッセージにする。
                    except JSONDecodeError:
                        pr = str(index + 1) + "位: " + "おすすめのお店です"

                    cur.execute(
                        "SELECT FROM favorite_restaurants WHERE user_id = '{}' and favorite_restaurant_name = '{}';"
                        .format(event.source.user_id, row["name"]))
                    if cur.fetchone() is None:
                        label_favorite = "お気に入りに追加する"
                        text_favorite = "お気に入り追加"
                    else:  # もうお気に入りされている。 # is not None
                        label_favorite = "お気に入りから削除する"
                        text_favorite = "お気に入り削除"
                    recommend_carousel_column = CarouselColumn(
                        thumbnail_image_url=image_url,
                        title=row["name"],
                        text=pr,
                        actions=[
                            URIAction(label='ぐるなびへ', uri=row.url_mobile),
                            MessageAction(label='位置情報をみる',
                                          text='位置情報 ' + row["name"]),
                            MessageAction(label=label_favorite,
                                          text=text_favorite + ' ' +
                                          row["name"])  # event.source.user_id
                        ])
                    recommend_carousel_columns.append(
                        recommend_carousel_column)
                conn.commit()
                cur.close()
                conn.close()
                line_bot_api.reply_message(
                    event.reply_token,
                    TemplateSendMessage(
                        alt_text='Carousel template',
                        template=CarouselTemplate(
                            columns=recommend_carousel_columns)))

    # おすすめ : カルーセルで数店舗紹介する。仕様上10店舗まで。
    elif input_msg in [
            "あなたへのおすすめ", "おすすめのお店", "おすすめ", "オススメ", "recommendation", "r", "re"
    ]:  #一旦動く。

        # recommend logic(ランダム)
        recommend_carousel_columns = []
        # recommend_restaurant_nums = [10,0,11,12]
        recommend_restaurant_nums = [14, 15, 16, 17, 18, 19]

        # num_lists = range(0, len(restaurant_names))
        # recommend_restaurant_nums = random.choices(num_lists, k=6) #仕様上10個まで。それ以上は、moreにすると良さそう。
        conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format(
            user, password, host, port_db, database))
        # conn = sqlite3.connect('restaurants.db')
        cur = conn.cursor()
        for i in recommend_restaurant_nums:
            if json.loads(restaurants[i].image_url.replace(
                    '\'', '"'))["shop_image1"] != "":
                image_url = json.loads(restaurants[i].image_url.replace(
                    '\'', '"'))["shop_image1"]
            else:
                # image_url = "https://i.picsum.photos/id/10/200/300.jpg"
                image_url = img_restaurant_default
            try:
                if json.loads(restaurants[i].pr.replace(
                        '\'', '"'))["pr_short"] != "":
                    pr = json.loads(
                        restaurants[i].pr.replace('\'', '"')
                    )["pr_short"][:60]  # 60文字までという制限がある。オーバーの時は"..."を表示する。
                else:
                    pr = "おすすめのお店です"  # もう少し、良いメッセージにする。
            except JSONDecodeError:
                pr = "おすすめのお店です"

            cur.execute(
                "SELECT FROM favorite_restaurants WHERE user_id = '{}' and favorite_restaurant_name = '{}';"
                .format(event.source.user_id, restaurants[i].name))
            if cur.fetchone() is None:
                label_favorite = "お気に入りに追加する"
                text_favorite = "お気に入り追加"
            else:  # もうお気に入りされている。 # is not None
                label_favorite = "お気に入りから削除する"
                text_favorite = "お気に入り削除"

            recommend_carousel_column = CarouselColumn(
                thumbnail_image_url=image_url,
                title=restaurants[i].name,
                text=pr,
                actions=[
                    URIAction(label='ぐるなびへ', uri=restaurants[i].url_mobile),
                    MessageAction(label='位置情報をみる',
                                  text='位置情報 ' + restaurants[i].name),
                    MessageAction(label=label_favorite,
                                  text=text_favorite + ' ' +
                                  restaurants[i].name)  # event.source.user_id
                ])
            recommend_carousel_columns.append(recommend_carousel_column)
        conn.commit()
        cur.close()
        conn.close()
        line_bot_api.reply_message(
            event.reply_token,
            TemplateSendMessage(
                alt_text='Carousel template',
                template=CarouselTemplate(columns=recommend_carousel_columns)))
    # 位置情報へを押された場合、"位置情報 (レストラン名)"とメッセージをトーク画面に返して、同時にそれをinputとして読み取って位置情報を返す。
    elif "位置情報" in input_msg:
        for restaurant in restaurants:
            if restaurant.name in input_msg:
                line_bot_api.reply_message(
                    event.reply_token,
                    LocationSendMessage(title=restaurant.name,
                                        address=restaurant.address,
                                        latitude=restaurant.latitude,
                                        longitude=restaurant.longitude))
    # お気に入りに追加するを押された場合、"お気に入り追加 (レストラン名)"とメッセージをトーク画面に返して、同時にそれをinputとして読み取って位置情報を返す。
    elif "お気に入り追加" in input_msg:
        for restaurant in restaurants:  # splitして、[command, name]もあり。
            if restaurant.name in input_msg:
                conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format(
                    user, password, host, port_db, database))
                cur = conn.cursor()
                cur.execute(
                    "INSERT INTO favorite_restaurants(user_id,favorite_restaurant_name) \
                SELECT '{}', '{}' \
                WHERE NOT EXISTS(SELECT 1 FROM favorite_restaurants WHERE user_id = '{}' AND favorite_restaurant_name = '{}')"
                    .format(event.source.user_id, restaurant.name,
                            event.source.user_id, restaurant.name))
                conn.commit()
                cur.close()
                conn.close()
    elif "お気に入り削除" in input_msg:
        for restaurant in restaurants:
            if restaurant.name in input_msg:
                conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format(
                    user, password, host, port_db, database))
                cur = conn.cursor()
                cur.execute("DELETE FROM favorite_restaurants \
                WHERE user_id = '{}' AND favorite_restaurant_name = '{}'" \
                .format(event.source.user_id, restaurant.name))
                conn.commit()
                cur.close()
                conn.close()
    else:
        output_msg = "知ってる言葉は\nちかく、ランダム、一覧、ランキング、ジャンル別、おすすめ。"
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=output_msg))
示例#6
0
def handle_text_message(event):
    text = event.message.text

    if text == 'profile':
        if isinstance(event.source, SourceUser):
            profile = line_bot_api.get_profile(event.source.user_id)
            line_bot_api.reply_message(
                event.reply_token, [
                    TextSendMessage(text='Display name: ' + profile.display_name),
                    TextSendMessage(text='Status message: ' + str(profile.status_message))
                ]
            )
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't use profile API without user ID"))
    elif text == 'quota':
        quota = line_bot_api.get_message_quota()
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text='type: ' + quota.type),
                TextSendMessage(text='value: ' + str(quota.value))
            ]
        )
    elif text == 'quota_consumption':
        quota_consumption = line_bot_api.get_message_quota_consumption()
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text='total usage: ' + str(quota_consumption.total_usage)),
            ]
        )
    elif text == 'push':
        line_bot_api.push_message(
            event.source.user_id, [
                TextSendMessage(text='PUSH!'),
            ]
        )
    elif text == 'multicast':
        line_bot_api.multicast(
            [event.source.user_id], [
                TextSendMessage(text='THIS IS A MULTICAST MESSAGE'),
            ]
        )
    elif text == 'broadcast':
        line_bot_api.broadcast(
            [
                TextSendMessage(text='THIS IS A BROADCAST MESSAGE'),
            ]
        )
    elif text.startswith('broadcast '):  # broadcast 20190505
        date = text.split(' ')[1]
        print("Getting broadcast result: " + date)
        result = line_bot_api.get_message_delivery_broadcast(date)
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text='Number of sent broadcast messages: ' + date),
                TextSendMessage(text='status: ' + str(result.status)),
                TextSendMessage(text='success: ' + str(result.success)),
            ]
        )
    elif text == 'bye':
        if isinstance(event.source, SourceGroup):
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text='Leaving group'))
            line_bot_api.leave_group(event.source.group_id)
        elif isinstance(event.source, SourceRoom):
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text='Leaving group'))
            line_bot_api.leave_room(event.source.room_id)
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="Bot can't leave from 1:1 chat"))
    elif text == 'image':
        url = request.url_root + '/static/logo.png'
        app.logger.info("url=" + url)
        line_bot_api.reply_message(
            event.reply_token,
            ImageSendMessage(url, url)
        )
    elif text == 'confirm':
        confirm_template = ConfirmTemplate(text='Do it?', actions=[
            MessageAction(label='Yes', text='Yes!'),
            MessageAction(label='No', text='No!'),
        ])
        template_message = TemplateSendMessage(
            alt_text='Confirm alt text', template=confirm_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'buttons':
        buttons_template = ButtonsTemplate(
            title='My buttons sample', text='Hello, my buttons', actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping'),
                PostbackAction(label='ping with text', data='ping', text='ping'),
                MessageAction(label='Translate Rice', text='米')
            ])
        template_message = TemplateSendMessage(
            alt_text='Buttons alt text', template=buttons_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'carousel':
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(text='hoge1', title='fuga1', actions=[
                URIAction(label='Go to line.me', uri='https://line.me'),
                PostbackAction(label='ping', data='ping')
            ]),
            CarouselColumn(text='hoge2', title='fuga2', actions=[
                PostbackAction(label='ping with text', data='ping', text='ping'),
                MessageAction(label='Translate Rice', text='米')
            ]),
        ])
        template_message = TemplateSendMessage(
            alt_text='Carousel alt text', template=carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'image_carousel':
        image_carousel_template = ImageCarouselTemplate(columns=[
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerAction(label='datetime',
                                                            data='datetime_postback',
                                                            mode='datetime')),
            ImageCarouselColumn(image_url='https://via.placeholder.com/1024x1024',
                                action=DatetimePickerAction(label='date',
                                                            data='date_postback',
                                                            mode='date'))
        ])
        template_message = TemplateSendMessage(
            alt_text='ImageCarousel alt text', template=image_carousel_template)
        line_bot_api.reply_message(event.reply_token, template_message)
    elif text == 'imagemap':
        pass
    elif text == 'flex':
        bubble = BubbleContainer(
            direction='ltr',
            hero=ImageComponent(
                url='https://example.com/cafe.jpg',
                size='full',
                aspect_ratio='20:13',
                aspect_mode='cover',
                action=URIAction(uri='http://example.com', label='label')
            ),
            body=BoxComponent(
                layout='vertical',
                contents=[
                    # title
                    TextComponent(text='Brown Cafe', weight='bold', size='xl'),
                    # review
                    BoxComponent(
                        layout='baseline',
                        margin='md',
                        contents=[
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/grey_star.png'),
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/gold_star.png'),
                            IconComponent(size='sm', url='https://example.com/grey_star.png'),
                            TextComponent(text='4.0', size='sm', color='#999999', margin='md',
                                          flex=0)
                        ]
                    ),
                    # info
                    BoxComponent(
                        layout='vertical',
                        margin='lg',
                        spacing='sm',
                        contents=[
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(
                                        text='Place',
                                        color='#aaaaaa',
                                        size='sm',
                                        flex=1
                                    ),
                                    TextComponent(
                                        text='Shinjuku, Tokyo',
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5
                                    )
                                ],
                            ),
                            BoxComponent(
                                layout='baseline',
                                spacing='sm',
                                contents=[
                                    TextComponent(
                                        text='Time',
                                        color='#aaaaaa',
                                        size='sm',
                                        flex=1
                                    ),
                                    TextComponent(
                                        text="10:00 - 23:00",
                                        wrap=True,
                                        color='#666666',
                                        size='sm',
                                        flex=5,
                                    ),
                                ],
                            ),
                        ],
                    )
                ],
            ),
            footer=BoxComponent(
                layout='vertical',
                spacing='sm',
                contents=[
                    # callAction, separator, websiteAction
                    SpacerComponent(size='sm'),
                    # callAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='CALL', uri='tel:000000'),
                    ),
                    # separator
                    SeparatorComponent(),
                    # websiteAction
                    ButtonComponent(
                        style='link',
                        height='sm',
                        action=URIAction(label='WEBSITE', uri="https://example.com")
                    )
                ]
            ),
        )
        message = FlexSendMessage(alt_text="hello", contents=bubble)
        line_bot_api.reply_message(
            event.reply_token,
            message
        )
    elif text == 'quick_reply':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='Quick reply',
                quick_reply=QuickReply(
                    items=[
                        QuickReplyButton(
                            action=PostbackAction(label="label1", data="data1")
                        ),
                        QuickReplyButton(
                            action=MessageAction(label="label2", text="text2")
                        ),
                        QuickReplyButton(
                            action=DatetimePickerAction(label="label3",
                                                        data="data3",
                                                        mode="date")
                        ),
                        QuickReplyButton(
                            action=CameraAction(label="label4")
                        ),
                        QuickReplyButton(
                            action=CameraRollAction(label="label5")
                        ),
                        QuickReplyButton(
                            action=LocationAction(label="label6")
                        ),
                    ])))
    elif text == 'link_token' and isinstance(event.source, SourceUser):
        link_token_response = line_bot_api.issue_link_token(event.source.user_id)
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text='link_token: ' + link_token_response.link_token)
            ]
        )
    else:
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text=event.message.text))
示例#7
0
文件: app.py 项目: jo-h28/UPI-Bot
def handle_text_message(event):
    if (event.message.text.lower() == "nilai"):
        # jika tombol nilai ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Nilai dari mata kuliah apa yang ingin ditampilkan?'))
        menuNilai = CarouselTemplate(columns=[
            CarouselColumn(
                title='AI',
                text='Inteligensi Buatan',
                defaultAction=MessageAction(label='Lihat Nilai', text='AI'),
                actions=[MessageAction(label='Lihat Nilai', text='AI')]),
            CarouselColumn(
                title='Jarkom',
                text='Jaringan Komputer',
                defaultAction=MessageAction(label='Lihat Nilai',
                                            text='Jarkom'),
                actions=[MessageAction(label='Lihat Nilai', text='Jarkom')]),
            CarouselColumn(
                title='IMK',
                text='Interaksi Manusia Komputer',
                defaultAction=MessageAction(label='Lihat Nilai', text='IMK'),
                actions=[MessageAction(label='Lihat Nilai', text='IMK')]),
            CarouselColumn(
                title='MPPL',
                text='Manajemen Proyek Perangkat Lunak',
                defaultAction=MessageAction(label='Lihat Nilai', text='MPPL'),
                actions=[MessageAction(label='Lihat Nilai', text='MPPL')]),
            CarouselColumn(
                title='WBD',
                text='Web-Based Development',
                defaultAction=MessageAction(label='Lihat Nilai', text='WBD'),
                actions=[MessageAction(label='Lihat Nilai', text='WBD')]),
            CarouselColumn(
                title='MBD',
                text='Manajemen Basis Data',
                defaultAction=MessageAction(label='Lihat Nilai', text='MBD'),
                actions=[MessageAction(label='Lihat Nilai', text='MBD')])
        ])
        messageNilai = TemplateSendMessage(alt_text='Tampilkan Nilai',
                                           template=menuNilai)
        line_bot_api.reply_message(event.reply_token, messageNilai)
    elif (event.message.text.lower() == "ai"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Inteligensi Buatan\n' \
        '== KUIS == \n' \
        'Kuis 1 : 75 \n' \
        'Kuis 2 : 88 \n' \
        '== TUGAS == \n' \
        'Tucil 1 : 100 \n' \
        'Tubes 1 : 100 \n' \
        '== UJIAN == \n' \
        'UTS : 99'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Selamat! Kamu benar-benar bersinar dalam mata kuliah ini!'
            ))
    elif (event.message.text.lower() == "jarkom"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Jaringan Komputer\n' \
        '== KUIS == \n' \
        'Kuis 1 : 90 \n' \
        'Kuis 2 : 101 \n' \
        'Kuis 3 : 85 \n' \
        'Kuis 4 : 95 \n' \
        'Kuis 5 : 90'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Kuis dadakan bukan menjadi penghalang untuk kamu terus berkembang!'
            ))
    elif (event.message.text.lower() == "imk"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Interaksi Manusia Komputer\n' \
        '== KUIS == \n' \
        'Kuis 1 : 45 \n' \
        'Kuis 2 : 60 \n' \
        'Kuis 3 : 75 \n' \
        'Kuis 4 : 70 \n' \
        'Kuis 5 : 90 \n' \
        '== TUGAS == \n' \
        'Tugas 1 : 95 \n' \
        'Tugas 2 : 85 \n' \
        'Tugas 3 : 80 \n' \
        'Tugas 4 : 90 \n' \
        'Tugas 5 : 95'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Nilai kuismu kian hari kian membaik! Pertahankanlah!'))
    elif (event.message.text.lower() == "mppl"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Manajemen Proyek Perangkat Lunak\n' \
        '== TUGAS == \n' \
        'Tugas 1 : 88 \n' \
        'Tugas 2 : 88 \n' \
        'Tugas 3 : 88 \n' \
        'Tugas 4 : 87 \n' \
        'Tugas 5 : 88 \n' \
        '== UJIAN == \n' \
        'UTS : 54'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Masih ada kesempatan untuk meraih nilai yang lebih tinggi di UAS nanti. Semangat!'
            ))
    elif (event.message.text.lower() == "wbd"):
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                'Nilai tidak ditemukan untuk mata kuliah Web-based Development.'
            ))
    elif (event.message.text.lower() == "mbd"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Manajemen Basis Data\n' \
        '== KUIS == \n' \
        'Kuis 1 : 45 \n' \
        'Kuis 2 : 60 \n' \
        '== TUGAS == \n' \
        'Tugas 1 : 95 \n' \
        '== UJIAN == \n' \
        'UTS : 67'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Jangan biarkan soal beranak itu melunturkan semangatmu! Kamu masih memiliki kesempatan untuk memperbaiki nilaimu. Berjuanglah!'
            ))
    elif (event.message.text.lower() == "to-do list"):
        # jika tombol to-do list ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        toDoListMenu = ButtonsTemplate(
            title='To-do List Menu',
            text='Pilih salah satu',
            thumbnail_image_url=
            'https://raw.githubusercontent.com/alvinlimassa/upi-bot/todolist/Image/todolist.png?token=AZu-_q7EbEcr2o4ChRGwXOrzCXqetxNcks5b7p25wA%3D%3D',
            actions=[
                MessageAction(label='Tampilkan Semua',
                              text='Tampilkan Semua To-do List'),
                DatetimePickerTemplateAction(label='Pilih tanggal',
                                             data='datetime_postback',
                                             mode='date'),
                MessageAction(label='Tambah To-do List',
                              text='Tambah To-do List')
            ])
        toDoListMessage = TemplateSendMessage(alt_text='To do List Menu',
                                              template=toDoListMenu)
        line_bot_api.reply_message(event.reply_token, toDoListMessage)
    elif (event.message.text.lower() == "tampilkan semua to-do list"):
        # jika user meminta menampilkan semua to-do list
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Berikut ini adalah To-Do List anda : \n' \
        'Senin, 12 November 2018 : \n' \
        '- 07.00 - 09.00 = AI \n' \
        '- 09.00 - 11.00 = IMK \n' \
        '- PR IMK (Deadline 10.00)\n' \
        'Selasa, 13 November 2018 : \n' \
        '- 07.00 - 09.00 = WBD\n' \
        '- 09.00 - 11.00 = JARKOM'))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Tekan/ ketik Selanjutnya untuk menampilkan to-do list berikutnya',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(action=MessageAction(
                        label='Selanjutnya', text='to-do list lanjut')),
                ])))
    elif (event.message.text.lower() == "to-do list lanjut"):
        # jika user meminta menampilkan Lanjutan To-do list
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Berikut ini adalah To-Do List anda : \n' \
        'Rabu, 14 November 2018 : \n' \
        '- 07.00 - 08.00 = IMK \n' \
        '- 08.00 - 10.00 = AI \n' \
        'Kamis, 15 November 2018 : \n' \
        '- 07.00 - 09.00 = WBD\n' \
        '- 09.00 - 11.00 = JARKOM'))
    elif (event.message.text.lower() == "tambah to-do list"):
        # jika user ingin menambahkan jadwal
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                'Untuk menambahkan To-do List gunakan perintah = add: <judul to-do list>'
            ))
    elif (event.message.text.lower() == "referensi"):
        # jika tombol referensi ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        temp = [
            MessageAction(label=x.split(" ")[1],
                          text=x.split(" ")[0] + " " +
                          " ".join(x.split(" ")[2:])) for x in matkul_list
        ]
        matkulMenu = CarouselTemplate(columns=[
            CarouselColumn(
                title=x.label, text=x.text, defaultAction=x, actions=[x])
            for x in temp
        ])
        matkulMessage = TemplateSendMessage(alt_text='Daftar mata kuliah',
                                            template=matkulMenu)
        line_bot_api.reply_message(event.reply_token, matkulMessage)
    elif (event.message.text.lower() ==
          "if3110 pengembangan aplikasi berbasis web"):
        # referensi wbd
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3110 Pengembangan Aplikasi Berbasis Web\n\n' \
        '1. Web Technologies: A Computer Science Perspec4ve, Jeffrey C. Jackson, Pren4ce Hall, 2007\n\n' \
        '2. Developing Large Web Applica4ons: Producing Code That Can Grow and Thrive, Kyle Loudon, O\'Reilly Media, Inc., 2010\n\n' \
        '3. HTML5: Up and Running, Mark Pilgrim, O\'Reilly Media, Inc., 2010\n\n' \
        '4. The Java EE 6 Tutorial: Basic Concepts, Eric Jendrock & Ian Evans & Devika Gollapudi & Kim Haase & Chinmayee Srivathsa, Pren4ce Hall, 2010\n\n' \
        '5. JavaScript: The Defini4ve Guide, David Flanagan, O\'Reilly Media, 2011'))
    elif (event.message.text.lower() == "if3130 jaringan komputer"):
        # referensi jarkom
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3130 Jaringan Komputer\n\n' \
        '1. Computer Networks: A Systems Approach (4th Edition) by Larry Peterson and Bruce Davie. Morgan Kaufmann, 2007.\n\n' \
        '2. Lin, Y.-D. Computer Networks: An Open Source Approach McGraw Hills, 2011\n\n' \
        '3. Tanenbaum, Andrew, “Computer Networks”, 4th Ed. Prentice Hall, 2003\n\n' \
        '4. Stallings, William, “Data & Computer Communications”, Prentice Hall, 2002'))
    elif (event.message.text.lower() == "if3140 manajemen basis data"):
        # referensi mbd
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3140 Manajemen Basis Data\n\n' \
        '1. Silberschatz, H.F. Korth, S. Sudarshan, ‘Database System Concepts’, McGraw-Hill (Pustaka Utama)\n\n' \
        '2. J.A. Hoffer, M.B. Prescott, F.R. McFadden, ‘Modern Database Management’, Pearson Prentice Hall (Pendukung)\n\n' \
        '3. C.J. Date, ‘An Introduction to Database System’, Addison Wesley (Pendukung)'))
    elif (event.message.text.lower() ==
          "if3150 manajemen proyek perangkat lunak"):
        # referensi mppl
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3150 Manajemen Proyek Perangkat Lunak\n\n' \
        '1. Information Technology Project Management 8th Edition, Kathy Schwalbe, Thomson Course Technology, 2015\n\n' \
        '2. A Guide to the Project Management Body of Knowledge, ANSI-PMI, 2008\n\n' \
        '3. Software Project, Steve McConnel, Microsoft Press, 1998\n\n' \
        '4. Project Management Professional Study Guide, Kim Heldman, Sybex, 2004\n\n' \
        '5. Wysocki, Robert K. Effective project management: traditional, agile, extreme. John Wiley & Sons, 2011'))
    elif (event.message.text.lower() == "if3151 interaksi manusia dan komputer"
          ):
        # referensi wbd
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3151 Interaksi Manusia dan Komputer\n\n' \
        '1. Interaction Design - Beyond Human-Computer Interaction, Jenny Preece et al., John Wiley & Sons'))
    elif (event.message.text.lower() == "if3170 intelegensi buatan"):
        # referensi wbd
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Referensi IF3110 Pengembangan Aplikasi Berbasis Web\n\n' \
        '1. Stuart J Russell & Peter Norvig, Artificial Intelligence: A Modern Approach, 3rd Edition, Prentice-Hall International, Inc, 2010\n\n' \
        '2. Tom Mitchell, Machine Learning, 1999\n\n' \
        '3. MIT OpenCourseWare Website: http://ocw.mit.edu/courses/electrical-engineering-and-computer-science/'))
    elif (event.message.text.lower() == "presensi"):
        # jika tombol presensi ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        presensiMenu = ButtonsTemplate(
            title='Pilih Jenis Presensi',
            text='Pilih salah satu',
            actions=[
                MessageAction(label='Semua Mata Kuliah',
                              text='presensi-semua'),
                MessageAction(label='Spesific Mata Kuliah',
                              text='presensi-spesific'),
            ])
        presensiMessage = TemplateSendMessage(alt_text='Presensi Menu',
                                              template=presensiMenu)
        line_bot_api.reply_message(event.reply_token, presensiMessage)

    elif (event.message.text.lower() == "presensi-semua"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Jaringan Komputer : 20%\n'\
        'Manajemen Basis Data : 100%\n'\
        'Manajemen Proyek Perangkat Lunak : 80%\n'\
        'Interaksi Manusia Komputer : 100%\n'\
        'Web-Based Development : 80%\n'\
        'Intelegensi Buatan : 100%\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Semangat untuk jaringan komputernya, jangan menghilang seperti ninja :)'
            ))
    elif (event.message.text.lower() == "presensi-spesific"):
        # jika tombol presensi ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        menuSpesific = CarouselTemplate(columns=[
            CarouselColumn(title='IF3170',
                           text='Inteligensi Buatan',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3170'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3170')
                           ]),
            CarouselColumn(title='IF3130',
                           text='Jaringan Komputer',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3130'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3130')
                           ]),
            CarouselColumn(title='IF3151',
                           text='Interaksi Manusia Komputer',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3151'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3151')
                           ]),
            CarouselColumn(title='IF3150',
                           text='Manajemen Proyek Perangkat Lunak',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3150'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3150')
                           ]),
            CarouselColumn(title='IF3110',
                           text='Web-Based Development',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3110'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3110')
                           ]),
            CarouselColumn(title='IF3140',
                           text='Manajemen Basis Data',
                           defaultAction=MessageAction(label='Lihat presensi',
                                                       text='presensi-IF3140'),
                           actions=[
                               MessageAction(label='Lihat presensi',
                                             text='presensi-IF3140')
                           ])
        ])
        messageSpesific = TemplateSendMessage(alt_text='Tampilkan Nilai',
                                              template=menuSpesific)
        line_bot_api.reply_message(event.reply_token, messageSpesific)

    elif (event.message.text.lower() == "presensi-if3130"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Jaringan Komputer : 20%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : 3-18\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(text='Semangat untuk kelas jarkomnya !!! '))

    elif (event.message.text.lower() == "presensi-if3140"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Manajemen Basis Data : 100%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : -\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(text='Mantap sudah bagus !!!, Pertahankan !!!'))
    elif (event.message.text.lower() == "presensi-if3170"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Intelegensi Buatan : 100%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : -\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(text='Mantap sudah bagus !!!, Pertahankan !!!'))
    elif (event.message.text.lower() == "presensi-if3150"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Manajemen Proyek Perangkat Lunak : 80%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : 19,20\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Absen masih aman, namun jatahmu sudah habis :( . Jangan bolos lagi !!!'
            ))
    elif (event.message.text.lower() == "presensi-if3151"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Interaksi Manusia Komputer : 100%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : -\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(text='Mantap sudah bagus !!!, Pertahankan !!!'))
    elif (event.message.text.lower() == "presensi-if3110"):
        line_bot_api.reply_message(event.reply_token, TextSendMessage('PRESENSI \n' \
        '============================\n' \
        'Web-Based Development : 80%\n'\
        'Jumlah Pertemuan : 20\n'\
        'Pertemuan tidak masuk : 19,20\n'\
        ))
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text=
                'Absen masih aman, namun jatahmu sudah habis :( . Jangan bolos lagi !!!'
            ))
    elif (event.message.text.lower() == "aturan"):
        # jika tombol aturan ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        aturanMenu = ButtonsTemplate(
            title='Prosedur dan Regulasi ITB',
            text='Pilih salah satu',
            actions=[
                MessageAction(label='Jadwal TU', text='Jadwal TU Kantor'),
                MessageAction(label='Pinjam Labtek V', text='Pinjam Labtek V'),
                MessageAction(label='KTM Hilang', text='KTM Hilang'),
                MessageAction(label='Transkrip', text='Permintaan Transkrip')
            ])
        aturanMessage = TemplateSendMessage(alt_text='Menu aturan',
                                            template=aturanMenu)
        line_bot_api.reply_message(event.reply_token, aturanMessage)
    elif (event.message.text.lower() == "jadwal tu kantor"):
        # jadwal buka TU dan kantor
        line_bot_api.reply_message(event.reply_token, TextSendMessage('JADWAL BUKA TU DAN KANTOR \n' \
        '============================\n' \
        '\n' \
        'TU STEI \n' \
        '07.00 - 12.00  13.00 - 15.00 \n' \
        'LK ITB \n' \
        '07.00 - 12.00  13.00 - 16.30 \n' \
        'SP ITB\n' \
        '08.00 - 12.00  13.00 - 16.30'))
    elif (event.message.text.lower() == "pinjam labtek v"):
        # prosedur peminjaman ruangan labtek V
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Prosedur Peminjaman Ruangan Labtek V \n' \
        '================================ \n' \
        '\n' \
        'Prasyarat: \n' \
        '1. Biaya fotokopi Rp500,00 \n' \
        '\n' \
        'Prosedur: \n' \
        '1. Datang ke TU Lab Labtek V lantai 4 pada jam kerja\n' \
        '2. Isi surat peminjaman ruangan\n' \
        '3. Bawa surat peminjaman ke SP STEI Labtek VIII lantai 2 pada jam kerja\n'
        '4. Datang kembali ke SP STEI setelah 1 hari\n'
        '5. Ambil surat dan fotokopi 3 lembar\n'
        '6. Beri surat ke TU Lab dan dapur Labtek V lantai 4'))
    elif (event.message.text.lower() == "permintaan transkrip"):
        # prosedur permintaan transkrip
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Prosedur Permintaan Transkrip \n' \
        '========================= \n' \
        '\n' \
        'Prasyarat: \n' \
        '1. Biaya fotokopi Rp1.000,00 \n' \
        '2. Bolpoin\n' \
        '\n' \
        'Prosedur: \n' \
        '1. Datang ke TU STEI Labtek V lantai 2 pada jam kerja\n' \
        '2. Isi lembar permintaan surat\n' \
        '3. Kembalikan lembar ke TU\n' \
        '4. Datang kembali ke TU STEI setelah 3 hari\n' \
        '5. Ambil transkrip asli dan fotokopi 5 lembar\n' \
        '6. Bawa hasil fotokopi ke TU untuk dilegalisasi'))
    elif (event.message.text.lower() == "ktm hilang"):
        # prosedur permintaan KTM baru
        line_bot_api.reply_message(event.reply_token, TextSendMessage('Prosedur Penggantian KTM Hilang \n' \
        '============================ \n' \
        '\n' \
        'Prasyarat: \n' \
        '1. Surat keterangan hilang dari TU \n' \
        '2. Foto untuk KTM baru (digital)\n' \
        '3. Biaya penggantian Rp30.000,00\n' \
        '\n' \
        'Prosedur: \n' \
        '1. Datang ke Annex ITB dengan membawa prasyarat\n' \
        '2. Upload foto dan isi data di web sesuai dengan pemberitahuan\n' \
        '3. Ambil KTM baru di gedung CRCS pada waktu yang telah diberitahukan'))
    elif (event.message.text.lower() == "soal"):
        # jika tombol soal ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        line_bot_api.push_message(event.source.user_id,
                                  TextSendMessage(text='Pilih Mata Kuliah'))
        menuQuiz = CarouselTemplate(columns=[
            CarouselColumn(
                title='AI',
                text='Inteligensi Buatan',
                defaultAction=MessageAction(label='Latihan', text='quiz-AI'),
                actions=[MessageAction(label='Latihan', text='quiz-AI')]),
            CarouselColumn(
                title='Jarkom',
                text='Jaringan Komputer',
                defaultAction=MessageAction(label='Latihan',
                                            text='quiz-Jarkom'),
                actions=[MessageAction(label='Latihan', text='quiz-Jarkom')])
        ])
        messageQuiz = TemplateSendMessage(alt_text='Tampilkan Nilai',
                                          template=menuQuiz)
        line_bot_api.reply_message(event.reply_token, messageQuiz)
    elif (event.message.text.lower() == "quiz-ai"):
        menuQuiz = CarouselTemplate(columns=[
            CarouselColumn(title='Bab 1',
                           text='Pengenalan AI',
                           defaultAction=MessageAction(label='Mulai Quiz',
                                                       text='quiz-pengenalan'),
                           actions=[
                               MessageAction(label='Mulai Quiz',
                                             text='quiz-pengenalan')
                           ]),
            CarouselColumn(title='Bab 2',
                           text='Learning',
                           defaultAction=MessageAction(label='Mulai Quiz',
                                                       text='quiz-learning'),
                           actions=[
                               MessageAction(label='Mulai Quiz',
                                             text='quiz-learning')
                           ])
        ])
        messageQuiz = TemplateSendMessage(alt_text='Tampilkan Nilai',
                                          template=menuQuiz)
        line_bot_api.reply_message(event.reply_token, messageQuiz)

    elif (event.message.text.lower() == "quiz-pengenalan"):
        # jika tombol aturan ditekan
        # fungsi yang akan dilakukan ditulis dibawah ini
        aturanMenu = ButtonsTemplate(
            title='Pengenalan',
            text='Mana yang bukan pendekatan AI?',
            actions=[
                MessageAction(label='Thinking Humanlly', text='TH'),
                MessageAction(label='Thinking Animally ', text='TA'),
                MessageAction(label='Acting Humanlly', text='AH'),
                MessageAction(label='Acting Rationally', text='AR')
            ])
        aturanMessage = TemplateSendMessage(alt_text='To do List Menu',
                                            template=aturanMenu)
        line_bot_api.reply_message(event.reply_token, aturanMessage)
    elif (event.message.text.lower() == "th"
          or event.message.text.lower() == "ah"
          or event.message.text.lower() == "ar"):
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Persentase Kebenaran: 0%\n Ayo semangat ngerjainnya!'))
    elif (event.message.text.lower() == "ta"):
        line_bot_api.push_message(
            event.source.user_id,
            TextSendMessage(
                text='Persentase Kebenaran: 100%\n Alhamdulillah bener semua'))
    else:
        inputTextA = event.message.text.lower().split(": ")
        inputTextB = event.message.text.lower().split(" :")
        inputTextC = event.message.text.lower().split(":")
        inputTextD = event.message.text.lower().split(" ")
        if (inputTextA[0] == "add" or inputTextA[0] == "referensi"):
            inputText = inputTextA
        elif (inputTextB[0] == "add" or inputTextB[0] == "referensi"):
            inputText = inputTextB
        elif (inputTextC[0] == "add" or inputTextC[0] == "referensi"):
            inputText = inputTextC
        elif (inputTextD[0] == "add" or inputTextD[0] == "referensi"):
            inputText = inputTextD
        else:
            inputText = []
        if (inputText[0] == "add"):
            # fungsi untuk menambahkan to-do list
            global toDoListString
            toDoListString = 'Judul To-do List : ' + inputText[1]
            addToDoListMenu = ButtonsTemplate(
                title='Add To Do List',
                text=toDoListString,
                actions=[
                    DatetimePickerTemplateAction(
                        label='Pilih tanggal',
                        data='todolist_datetime_postback',
                        mode='datetime')
                ])
            addToDoListMessage = TemplateSendMessage(
                alt_text='To do List Menu', template=addToDoListMenu)
            line_bot_api.reply_message(event.reply_token, addToDoListMessage)
        elif (inputText[0] == "referensi"):
            # fungsi untuk mencari referensi dengan keyword mata kuliah
            temp = [
                MessageAction(label=x.split(" ")[1],
                              text=x.split(" ")[0] + " " +
                              " ".join(x.split(" ")[2:])) for x in matkul_list
                if inputText[1].lower() in x.lower()
            ]
            if (temp):
                matkulMenu = CarouselTemplate(columns=[
                    CarouselColumn(title=x.label,
                                   text=x.text,
                                   defaultAction=x,
                                   actions=[x]) for x in temp
                ])
                matkulMessage = TemplateSendMessage(
                    alt_text='Daftar mata kuliah', template=matkulMenu)
                line_bot_api.reply_message(event.reply_token, matkulMessage)
            else:
                line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage('Tidak ditemukan mata kuliah terkait ' +
                                    '\'' + inputText[1] + '\''))
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    "Maaf, kami tidak mengerti permintaan anda harap cek kembali input anda"
                ))
示例#8
0
def handle_message(event):
    if event.message.text == '暗殺教室':
        img_send_message = ImageSendMessage(
            original_content_url=
            'https://www.animen.com.tw/FilesUpload/CK-Images/150925_71_2.jpg',
            preview_image_url=
            'https://upload.wikimedia.org/wikipedia/zh/3/3c/Assassination_Classroom_Volume_1.jpg'
        )
        line_bot_api.reply_message(event.reply_token, img_send_message)
    elif event.message.text == '帥哥':
        img_list = [[
            'https://i0.wp.com/www.littleoslo.com/lyc/home/wp-content/uploads/2016/04/%E9%9F%8B%E7%A6%AE%E5%AE%89.png?fit=1024%2C1024',
            'https://img.mymusic.net.tw/mms/singer/732/18732s.jpg'
        ]]
        index = random.randint(0, len(img_list))
        img_send_message = ImageSendMessage(
            original_content_url=img_list[index][0],
            preview_image_url=img_list[index][1])
        line_bot_api.reply_message(event.reply_token, img_send_message)

    elif event.message.text == '隱藏功能':
        # 創造一個QuickReplyButton
        text_quickreply = QuickReplyButton(
            action=MessageAction(label='我是標籤', text='我幫你打字'))
        #
        location_quickreply = QuickReplyButton(action=LocationAction(
            label='助教在哪裡'))

        # 創造一個QuickReply,並把剛剛創建的button放進去
        quick_reply_array = QuickReply(
            items=[text_quickreply, location_quickreply])
        # 生成一個文字消息
        reply_text_message = TextSendMessage(event.message.text,
                                             quick_reply=quick_reply_array)

        line_bot_api.reply_message(event.reply_token, reply_text_message)

    elif event.message.text == '我要點餐':
        # 創造一個QuickReplyButton
        text_quickreply0 = QuickReplyButton(
            action=MessageAction(label='1. 大麥克', text='配餐選擇'))
        text_quickreply1 = QuickReplyButton(
            action=MessageAction(label='2. 雙層牛肉吉士堡', text='配餐選擇'))
        # 創造一個QuickReply,並把剛剛創建的button放進去
        quick_reply_array = QuickReply(
            items=[text_quickreply0, text_quickreply1])
        # 生成一個文字消息
        reply_text_message = TextSendMessage('請選擇主餐',
                                             quick_reply=quick_reply_array)

        line_bot_api.reply_message(event.reply_token, reply_text_message)

    elif event.message.text == '配餐選擇':
        # 創造一個QuickReplyButton
        text_quickreply0 = QuickReplyButton(
            action=MessageAction(label='A 經典配餐', text='A'))
        text_quickreply1 = QuickReplyButton(
            action=MessageAction(label='B 清爽配餐', text='B'))
        # 創造一個QuickReply,並把剛剛創建的button放進去
        quick_reply_array = QuickReply(
            items=[text_quickreply0, text_quickreply1])
        # 生成一個文字消息
        reply_text_message = TextSendMessage('請選擇配餐',
                                             quick_reply=quick_reply_array)

        line_bot_api.reply_message(event.reply_token, reply_text_message)

    else:
        # 把用戶的化轉成文字發送消息
        reply_text_message = TextSendMessage(event.message.text)

        # line_bot_api 傳送回去
        line_bot_api.reply_message(event.reply_token, reply_text_message)
示例#9
0
def handle_postback(event):
    nata_id = event.source.user_id
    profile = line_bot_api.get_profile(nata_id)
    if event.postback.data == 'event':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='silahkan pilih kategori perlengkapan event'),
            event_map
        ])

    elif event.postback.data == 'keranjang':
        tmp_user = user_generator(nata_id, profile.display_name)
        if len(tmp_user.user_events) > 0:
            line_bot_api.reply_message(event.reply_token, [
                TextSendMessage(text='keranjang kamu'),
                FlexSendMessage(alt_text="keranjang",
                                contents=nata_receipt(tmp_user))
            ])
        else:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='kamu belum pesan apapun'))

    elif 'pesan' in event.postback.data:
        tmp_parse = event.postback.data.split("%")
        tmp_id = tmp_parse[1]

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text='untuk berapa lama?',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=PostbackAction(label='1 hari',
                                              data='tambah%' + tmp_id + '%' +
                                              '1',
                                              text='untuk 1 hari')),
                    QuickReplyButton(
                        action=PostbackAction(label='2 hari',
                                              data='tambah%' + tmp_id + '%' +
                                              '2',
                                              text='untuk 2 hari')),
                    QuickReplyButton(
                        action=PostbackAction(label='3 hari',
                                              data='tambah%' + tmp_id + '%' +
                                              '3',
                                              text='untuk 3 hari')),
                    QuickReplyButton(
                        action=PostbackAction(label='4 hari',
                                              data='tambah%' + tmp_id + '%' +
                                              '4',
                                              text='untuk 4 hari')),
                    QuickReplyButton(
                        action=PostbackAction(label='5 hari',
                                              data='tambah%' + tmp_id + '%' +
                                              '5',
                                              text='untuk 5 hari')),
                    QuickReplyButton(
                        action=PostbackAction(label='6 hari',
                                              data='tambah%' + tmp_id + '%' +
                                              '6',
                                              text='untuk 6 hari')),
                    QuickReplyButton(
                        action=PostbackAction(label='1 minggu',
                                              data='tambah%' + tmp_id + '%' +
                                              '7',
                                              text='untuk 1 minggu'))
                ])))

    elif 'tambah' in event.postback.data:
        tmp_user = user_generator(nata_id, profile.display_name)
        tmp_parse = event.postback.data.split("%")
        tmp_id = tmp_parse[1]
        tmp_qnt = tmp_parse[2]

        tmp_arr = []
        for i in tmp_user.user_events:
            tmp_arr.append(i)
        tmp_arr.append([tmp_id, tmp_qnt])
        tmp_user.user_events = tmp_arr
        db.session.commit()

        tmp_event = Event.query.filter_by(id=tmp_id).first()

        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text=(tmp_event.event_name).lower() +
                            ' masuk dalam keranjang'))

    elif 'batalkan' == event.postback.data:
        cancel_msg = TemplateSendMessage(alt_text='cancel pesanan',
                                         template=ConfirmTemplate(
                                             text='Batalkan pesanan?',
                                             actions=[
                                                 PostbackAction(label='Ya',
                                                                data='flush'),
                                                 PostbackAction(
                                                     label='Tidak',
                                                     data='not_canceled',
                                                 )
                                             ]))
        line_bot_api.reply_message(event.reply_token, cancel_msg)

    elif 'flush' == event.postback.data:
        tmp_user = user_generator(nata_id, profile.display_name)
        tmp_user.user_events = []
        db.session.commit()
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text='pesanan dibatalkan'))

    elif 'not_canceled' == event.postback.data:
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='tidak jadi nata batalkan'))

    elif 'bayar' == event.postback.data:
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='pesanan Nata konfirmasi, silahkan masukan nama'),
            TextSendMessage(text='contoh : \\nama Azhar Difa')
        ])

    elif event.postback.data == 'date_postback':
        tmp_user = user_generator(nata_id, profile.display_name)
        customer_date = event.postback.params['date']
        tmp_user.user_date = customer_date
        db.session.commit()
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text=
                'sipp, satu langkah terakhir nih untuk konfirmasi pesanan kamu'
            ),
            transfer_msg()
        ])

    elif event.postback.data == 'transfer_bca':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='kirim bukti transfer ke-nomor rekening dibawah ini'),
            atm_map('BCA')
        ])
    elif event.postback.data == 'transfer_bni':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='kirim bukti transfer ke-nomor rekening dibawah ini'),
            atm_map('BNI')
        ])
    elif event.postback.data == 'transfer_mandiri':
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='kirim bukti transfer ke-nomor rekening dibawah ini'),
            atm_map('Mandiri')
        ])


# batas 2.0

    elif 'clear_cart_danus' in event.postback.data:
        cart_tmp = Cart.query.filter_by(id=str(nata_id)).first()
        for order in cart_tmp.orders:
            if order.danus_flag:
                db.session.delete(order)
        db.session.commit()
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text='pesanan Nata batalkan'))

    elif 'clear_cart_event' in event.postback.data:
        cart_tmp = Cart.query.filter_by(id=str(nata_id)).first()
        for order in cart_tmp.orders:
            if order.event_flag:
                db.session.delete(order)
        db.session.commit()
        line_bot_api.reply_message(
            event.reply_token, TextSendMessage(text='pesanan Nata batalkan'))

    elif 'confirm_cart' in event.postback.data:
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(
                text='pesanan Nata konfirmasi, silahkan masukan nama'),
            TextSendMessage(text='contoh : \\nama Nata purnomo')
        ])

    elif 'confirm_cancel_danus' in event.postback.data:
        line_bot_api.reply_message(event.reply_token, confirm_cancel('danus'))

    elif 'confirm_cancel_event' in event.postback.data:
        line_bot_api.reply_message(event.reply_token, confirm_cancel('event'))
示例#10
0
def handle_message(event):
    global stage
    global li
    reply = event.message.text
    if reply == "書きたくない":
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                    text="分かりました!\nまた書きたくなったら話かけてくださいね〜😁"))
        
    elif stage == "accepter":
        stage = "sender"
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                    text="ありがとうございます!\n素敵な手紙を書いてくださいね😊\n\n誰に手紙を書きますか?"))
    elif stage == "sender":
        stage = "reason" 
        li.append(reply)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                    text=li[0]+"さんですね!\nきっと喜びますね!\nあなたの名前は何ですか?"))
    elif stage == "reason":
        stage = "detail"
        li.append(reply)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                text=li[1]+"さんですね!\nありがとうございます!\n今回"+li[0]+"さんに手紙を書こうと思った理由は何ですか?\n\n例)大切な気持ちを伝えたい",
                quick_reply=QuickReply(
                    items=[
                        QuickReplyButton(
                            action=MessageAction(label="感謝を伝えたい", text="感謝を伝えたい")
                         ),
                         QuickReplyButton(
                            action=MessageAction(label="謝りたい", text="謝りたい")
                          ),
                         QuickReplyButton(
                            action=MessageAction(label="自分の気持ちを伝えたい", text="自分の気持ちを伝えたい")
                         ),
                 ])))
    elif stage == "detail":
        stage = "addition"
        if reply == "感謝を伝えたい":
            li.append("今日は" + li[0] + "さんにお礼を言いたくてこの手紙を書くことにしました。")
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="ステキですね✨\n" + li[0] + "さんへの感謝の気持ちを伝えたいか教えてください!\n\n例)落ち込んでいるときにそっと声を掛けてくれてありがとう"))
        elif reply == "謝りたい":
            li.append("今日は謝りたくてこの手紙を書くことにしました。")
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="なかなか言えない気持ちを伝えるのはすごい勇気が入りますよね...でもきっと気持ちは伝わりますよ!\n" + li[0] +
                                "さんに伝えたいその気持ちを教えてください!\n\n例)この間は太郎くんの気持ちを考えないであんなこと言ってごめんね"))
        elif reply == "自分の気持ちを伝えたい":
            li.append("今日は伝えたいことがあって、この手紙を書くことにしました。") 
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text="あなたの気持ちは必ず伝わりますよ!\n" + li[0] + "さんに伝えたいその気持ちを教えてください!\n\n例"+
                                " )実はあのときテニス部に入る気はなかったんです"))
    elif stage == "addition":
        stage = "complete"
        li.append(reply)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text="最後に何か一言どうぞ!\n\n例)これからもよろしくね!"))
    elif stage == "complete":
        sentences=""
        li.append(reply)
        for i,j in enumerate(li):
            if i == 0:
                sentences += j + "さんへ" + "\n\n"
            elif i == 1:
                continue
            elif i == len(li) - 1:
                sentences += j + "\n\n" + li[1] + "より"
            else:
                for ix, va in enumerate(range(0, len(j), 14)):
                    sentences += j[va:va+14] + "\n"
        print("wow",sentences)
                
        stage = "accepter"
        li = []
        src_image_path = Path(SRC_IMAGE_PATH).absolute()
        main_image_path = MAIN_IMAGE_PATH
        preview_image_path = PREVIEW_IMAGE_PATH

        date_the_image(src=src_image_path, desc=Path(main_image_path).absolute(), sentences=sentences)
        date_the_image(src=src_image_path, desc=Path(preview_image_path).absolute(), sentences=sentences)

        # 画像の送信
        image_message = ImageSendMessage(
            original_content_url=f"https://line-bot-letter.herokuapp.com/{main_image_path}",
            preview_image_url=f"https://line-bot-letter.herokuapp.com/{preview_image_path}"
         )
        #ログの取得
        app.logger.info(f"https://line-bot-letter.herokuapp.com/{main_image_path}")

        confirm_template = ConfirmTemplate(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, [
                TextSendMessage(text="お疲れ様でした!こちらが手紙の文章です!"),
                image_message,
                template_message
            ]
        )
示例#11
0
def handle_message(event):
    mtext = event.message.text
    if mtext == 'Hi':
        try:
            message = TextSendMessage(text="Hi, I am Mask-App.")
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='Please try again,thx.'))

    elif mtext == '來看精選口罩!':
        uri = 'https://7ab75a946a8a.ngrok.io/image?path='
        message = [
            #ImageSendMessage(
            #class
            #original_content_url ='https://i.imgur.com/CSQJsZP.jpg',
            #preview_image_url = 'https://i.imgur.com/CSQJsZP.jpg'),
            ImageSendMessage(
                #original
                original_content_url=uri + '12601132093474.jpg_converted.jpg',
                preview_image_url=uri + '12601132093474.jpg_converted.jpg'),
            ImageSendMessage(
                #original
                original_content_url=uri + '12601136402499.jpg_converted.jpg',
                preview_image_url=uri + '12601136402499.jpg_converted.jpg'),
            ImageSendMessage(
                #original
                original_content_url=uri + '12601138680722.jpg_converted.jpg',
                preview_image_url=uri + '12601138680722.jpg_converted.jpg'),
            ImageSendMessage(
                #original
                original_content_url=uri + '12601141694399.jpg_converted.jpg',
                preview_image_url=uri + '12601141694399.jpg_converted.jpg')
        ]
        line_bot_api.reply_message(event.reply_token, message)

    elif mtext == '貼圖':
        try:
            message = StickerSendMessage(package_id='1', sticker_id='410')
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='Please try again,thx.'))

    elif mtext == '多項傳送':
        try:
            message = [
                StickerSendMessage(package_id='1', sticker_id='410'),
                TextSendMessage(text="Hi, I am Mask-App."),
                ImageSendMessage(
                    original_content_url='https://i.imgur.com/CSQJsZP.jpg',
                    preview_image_url='https://i.imgur.com/CSQJsZP.jpg')
            ]

            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='Please try again,thx.'))

    elif mtext == '位置':
        try:
            message = LocationSendMessage(title='交通大學 台南分校',
                                          address='台南市歸仁區高發三路301號',
                                          latitude=22.924879,
                                          longitude=120.294950)
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='Please try again,thx.'))

    elif mtext == '快速選單':
        try:
            message = TextSendMessage(
                text='please select',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=MessageAction(label="文字", text="文字")),
                    QuickReplyButton(
                        action=MessageAction(label="圖片", text="圖片")),
                    QuickReplyButton(
                        action=MessageAction(label="貼圖", text="貼圖")),
                    QuickReplyButton(
                        action=MessageAction(label="多項傳送", text="多項傳送")),
                    QuickReplyButton(
                        action=MessageAction(label="位置", text="位置")),
                ]))
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(text='Please try again,thx.'))
示例#12
0
    def think_reply_message(self, received_message, option=None):
        if 'ボタンテンプレート' in received_message:
            sending_message = TemplateSendMessage(
                alt_text='Buttons template',
                template=ButtonsTemplate(
                    thumbnail_image_url=
                    'https://placehold.jp/565656/151x100.png',
                    title='Menu',
                    text='Please select',
                    actions=[
                        PostbackAction(label='postback',
                                       text='postback text',
                                       data='action=buy&itemid=1'),
                        MessageAction(label='message', text='message text'),
                        URIAction(label='uri', uri='http://example.com/')
                    ]))

        elif '確認テンプレート' in received_message:
            sending_message = TemplateSendMessage(
                alt_text='Confirm template',
                template=ConfirmTemplate(text='Are you sure?',
                                         actions=[
                                             PostbackAction(
                                                 label='postback',
                                                 text='postback text',
                                                 data='action=buy&itemid=1'),
                                             MessageAction(label='message',
                                                           text='message text')
                                         ]))

        elif '画像カルーセルテンプレート' in received_message:
            sending_message = TemplateSendMessage(
                alt_text='ImageCarousel template',
                template=ImageCarouselTemplate(columns=[
                    ImageCarouselColumn(
                        image_url='https://placehold.jp/ababab/150x150.png',
                        action=PostbackAction(label='postback1',
                                              text='postback text1',
                                              data='action=buy&itemid=1')),
                    ImageCarouselColumn(
                        image_url='https://placehold.jp/565656/150x150.png',
                        action=PostbackAction(label='postback2',
                                              text='postback text2',
                                              data='action=buy&itemid=2'))
                ]))

        elif 'カルーセルテンプレート' in received_message:
            sending_message = TemplateSendMessage(
                alt_text='Carousel template',
                template=CarouselTemplate(columns=[
                    CarouselColumn(
                        thumbnail_image_url=
                        'https://placehold.jp/ababab/100x151.png',
                        title='this is menu1',
                        text='description1',
                        actions=[
                            PostbackAction(label='postback1',
                                           text='postback text1',
                                           data='action=buy&itemid=1'),
                            MessageAction(label='message1',
                                          text='message text1'),
                            URIAction(label='uri1', uri='http://example.com/1')
                        ]),
                    CarouselColumn(thumbnail_image_url=
                                   'https://placehold.jp/565656/100x151.png',
                                   title='this is menu2',
                                   text='description2',
                                   actions=[
                                       PostbackAction(
                                           label='postback2',
                                           text='postback text2',
                                           data='action=buy&itemid=2'),
                                       MessageAction(label='message2',
                                                     text='message text2'),
                                       URIAction(label='uri2',
                                                 uri='http://example.com/2')
                                   ])
                ]))

        elif 'フレックス' in received_message:
            sending_message = FlexSendMessage(
                alt_text='ImageCarousel template',
                contents=BubbleContainer(
                    header=BoxComponent(
                        layout='vertical',
                        contents=[TextComponent(text='header')]),
                    hero=ImageComponent(
                        url='https://placehold.jp/ababab/1024x1024.png',
                        size='full'),
                    body=BoxComponent(layout='vertical',
                                      contents=[TextComponent(text='body')]),
                    footer=BoxComponent(
                        layout='vertical',
                        contents=[TextComponent(text='footer')]),
                    styles=BubbleStyle(header=BlockStyle(),
                                       hero=BlockStyle(),
                                       body=BlockStyle(),
                                       footer=BlockStyle())))

        elif 'ログイン' in received_message:
            url = "{provider_url}/link_account?linkToken={link_token}".format(
                provider_url=PROVIDER_URL, link_token=option)
            sending_message = TemplateSendMessage(
                alt_text='Account Link',
                template=ButtonsTemplate(
                    thumbnail_image_url=
                    'https://placehold.jp/565656/100x151.png',
                    title='Menu',
                    text='Link your account',
                    actions=[URIAction(label='Account Link', uri=url)]))

        elif 'ログアウト' in received_message:
            pass

        elif 'クイックリプライ' in received_message:
            sending_message = TextSendMessage(
                text='Hello, world',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=MessageAction(label="label01", text="text01"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=01"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label02", text="text02"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=02"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label03", text="text03"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=03"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label04", text="text04"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=04"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label05", text="text05"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=05"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label06", text="text06"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=06"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label07", text="text07"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=07"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label08", text="text08"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=08"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label09", text="text09"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=09"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label10", text="text10"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=10"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label11", text="text11"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=11"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label12", text="text12"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=12"
                    ),
                    QuickReplyButton(
                        action=MessageAction(label="label13", text="text13"),
                        image_url=
                        "https://placehold.jp/24/ffffff/000000/50x50.png?text=13"
                    )
                ]))
        else:
            sending_message = TextSendMessage(received_message)

        return sending_message
示例#13
0
    def test_push_text_message_with_quick_reply(self):
        responses.add(responses.POST,
                      LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push',
                      json={},
                      status=200)

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

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


# ========================================

QuickReply_text_message_help = TextSendMessage(
    text=HELP_MESSAGE,
    quick_reply=QuickReply(
        items=[
            QuickReplyButton(
                action=MessageAction(label="#邦食堂", text="#邦食堂"),
            ),
            QuickReplyButton(
                action=MessageAction(label="#微笑廚房", text="#微笑廚房"),
            ),
            QuickReplyButton(
                action=MessageAction(label="#五九麵館", text="#五九麵館"),
            ),
            QuickReplyButton(
                action=MessageAction(label="#大李水餃", text="#大李水餃"),
            ),
            QuickReplyButton(
                action=MessageAction(label="#合益佳雞肉飯", text="#合益佳雞肉飯"),
            )
        ]))

QuickReply_text_message_nostore = TextSendMessage(
    text="抱歉,查無此店",
    quick_reply=QuickReply(
        items=[
            QuickReplyButton(
                action=MessageAction(label="#邦食堂", text="#邦食堂"),
def handle_postback_event(event):

    reply_text_messge = TextSendMessage(event.message.text)
    if reply_text_messge.text == "前往客廳":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-aa539642a4e870c6bcfaff4eab1d78b7"
        )

    elif reply_text_messge.text == "前往大廳":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-ddeca7d9b46777ff8afe73b5875a38c0"
        )

    elif reply_text_messge.text == "前往廚房":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-7e1cbf2b1f5653d672e06c7fed11ea72"
        )
    elif reply_text_messge.text == "前往玄關":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-5ce99f617283f7be62f5613a1b03781e"
        )

    elif reply_text_messge.text == "前往書房":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-be72968b52bad1ea3297223564b96dd8"
        )

    elif reply_text_messge.text == "前往廁所":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-a483bc2452bbe7691de931760645af47"
        )

    elif reply_text_messge.text == "前往臥室":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-3d72221c0ce598cc6f9ec723c08b10d3"
        )

    elif reply_text_messge.text == "前往陽台":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-e5be13aea8b048f1e43dbf9c0513f9a5"
        )

    # 開始的互動
    elif reply_text_messge.text == "點選圖片前往指定地點":
        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-5ce99f617283f7be62f5613a1b03781e"
        )

    # 玄關的互動訊息
    elif reply_text_messge.text == "是 Lucky!":
        image_message = ImageSendMessage(
            original_content_url='https://i2.kknews.cc/SIG=qggjlr/ctp-vzntr/94792o175ro14951n6o0032ps905864n.jpg ',
            preview_image_url='https://images2.gamme.com.tw/news2/2017/52/41/qZqZo6SVk6ecq6Q.jpg'
        )
        line_bot_api.reply_message(event.reply_token, image_message)

    elif reply_text_messge.text == "隔離中,請勿出門!!!!!!!!!":
        image_message = ImageSendMessage(
            original_content_url='https://www.health.taichung.gov.tw/media/541906/%E5%B1%85%E5%AE%B6%E6%AA%A2%E7%96%AB-%E9%9A%94%E9%9B%A2%E8%80%85%E7%A6%81%E6%AD%A2%E8%B6%B4%E8%B6%B4%E8%B5%B0.jpg',
            preview_image_url='https://www.health.taichung.gov.tw/media/541906/%E5%B1%85%E5%AE%B6%E6%AA%A2%E7%96%AB-%E9%9A%94%E9%9B%A2%E8%80%85%E7%A6%81%E6%AD%A2%E8%B6%B4%E8%B6%B4%E8%B5%B0.jpg'
        )
        line_bot_api.reply_message(event.reply_token, image_message)

    # 客廳的互動訊息
    elif reply_text_messge.text == "來看電視吧":
        # 創造QuickReplyButton
        text_quireply_first = QuickReplyButton(action=MessageAction(label="Netflix", text="最近冰與火之歌好像完結了"))
        text_quireply_second = QuickReplyButton(action=MessageAction(label="新聞", text="台灣新聞真的莫名其妙= ="))
        text_quireply_third = QuickReplyButton(action=MessageAction(label="電影", text="看點經典的吧"))

        # 創造一個QuickReply,並把剛剛創建的button放進去
        quick_reply_array = QuickReply(items=[text_quireply_first, text_quireply_second, text_quireply_third])

        # line_bot_api 傳送回去
        line_bot_api.reply_message(event.reply_token,TextSendMessage(text='請選擇你要的節目',quick_reply=quick_reply_array))

    elif reply_text_messge.text == "最近冰與火之歌好像完結了":
        buttons_template_message = TemplateSendMessage(
            alt_text='Buttons template',
            template=ButtonsTemplate(
                thumbnail_image_url='https://www.dramaqueen.com.tw/upload/images/mgot_s8_character_art_dany.jpg',
                title='冰與火之歌',
                text='《權力遊戲》是一部中世紀奇幻題材的電視連續劇。改編自喬治·R·R·馬丁的奇幻小說系列《冰與火之歌》的《權力遊戲》',
                actions=[
                    # 如何解析多欄位的 data
                    # python querystring parser
                    MessageAction(
                        label="開始觀看",
                        text="結局也太...")
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token, buttons_template_message)

    elif reply_text_messge.text == "台灣新聞真的莫名其妙= =":
        buttons_template_message = TemplateSendMessage(
            alt_text='Buttons template',
            template=ButtonsTemplate(
                thumbnail_image_url='https://im.marieclaire.com.tw/m800c533h100b0/assets/mc/202006/5ED69328505111591120680.jpeg',
                title='振興三倍券',
                text='振興三倍券6大QA!超商預購、郵局購買、信用卡綁定優惠...懶人包幫你整理好了',
                actions=[
                    # 如何解析多欄位的 data
                    # python querystring parser
                    MessageAction(
                        label="開始觀看",
                        text="關在裡面領不到...")
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token, buttons_template_message)

    elif reply_text_messge.text == "看點經典的吧":
        buttons_template_message = TemplateSendMessage(
            alt_text='Buttons template',
            template=ButtonsTemplate(
                thumbnail_image_url='https://img.myvideo.net.tw/images/WAR020/0000/0033/201309181832000352_420x600.jpg',
                title='全面啟動 INCEPTION',
                text='偷技高超的神偷唐姆柯比,目標是趁對象進入深沉的睡眠、心智遂呈現最脆弱狀態時,入侵其潛意識...',
                actions=[
                    # 如何解析多欄位的 data
                    # python querystring parser
                    MessageAction(
                        label="開始觀看",
                        text="太厲害啦!!!")
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token, buttons_template_message)
        
    # 書房互動
    elif reply_text_messge.text == "來玩些遊戲吧":
        # 創造QuickReplyButton
        text_quireply_first = QuickReplyButton(action=MessageAction(label="switch", text="現在的 Switch好貴喔"))
        text_quireply_second = QuickReplyButton(action=MessageAction(label="ps4", text="PS5年底就要出了ㄟ,要買嗎?"))

        # 創造一個QuickReply,並把剛剛創建的button放進去
        quick_reply_array = QuickReply(items=[text_quireply_first, text_quireply_second])

        # line_bot_api 傳送回去
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='請選擇你想玩的遊戲', quick_reply=quick_reply_array))

    elif reply_text_messge.text == "現在的 Switch好貴喔":
        buttons_template_message = TemplateSendMessage(
            alt_text='Buttons template',
            template=ButtonsTemplate(
                thumbnail_image_url='https://ct.yimg.com/xd/api/res/1.2/3l5IRqFyeKqfj_m8SxVQkA--/YXBwaWQ9eXR3YXVjdGlvbnNlcnZpY2U7aD03MDA7cT04NTtyb3RhdGU9YXV0bzt3PTQxNw--/https://s.yimg.com/ob/image/4d965226-b7bd-411b-8470-68d6d992cf71.jpg',
                title='薩爾達傳說 曠野之息',
                text='薩爾達傳說是任天堂自1986年起推出的動作冒險遊戲系列,創始人為宮本茂。遊戲以奇幻世界為背景,描述著林克的冒險經歷...',
                actions=[
                    # 如何解析多欄位的 data
                    # python querystring parser
                    MessageAction(
                        label="開始遊戲",
                        text="真好玩")
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token, buttons_template_message)

    elif reply_text_messge.text == "PS5年底就要出了ㄟ,要買嗎?":
        buttons_template_message = TemplateSendMessage(
            alt_text='Buttons template',
            template=ButtonsTemplate(
                thumbnail_image_url='https://upload.wikimedia.org/wikipedia/zh/f/f2/The_last_of_us_part_2_cover.jpg',
                title='最後生還者 第II章',
                text='《最後生還者 第II章》是一款由頑皮狗開發的生存恐怖動作遊戲。本作是2013年遊戲《最後生還者》的續作...',
                actions=[
                    # 如何解析多欄位的 data
                    # python querystring parser
                    MessageAction(
                        label="開始遊戲",
                        text="玩得好累阿")
                ]
            )
        )
        line_bot_api.reply_message(event.reply_token, buttons_template_message)

    elif reply_text_messge.text == "看些書好了":
        # 創造QuickReplyButton
        text_quireply_first = QuickReplyButton(action=MessageAction(label="富爸爸,窮爸爸", text="看完了我也能發財嗎?"))
        text_quireply_second = QuickReplyButton(action=MessageAction(label="哆啦A夢 第0集", text="這也算書吧?"))
        text_quireply_third = QuickReplyButton(action=MessageAction(label="野貓軍團 咖哩飯", text="看完都餓了..."))

        # 創造一個QuickReply,並把剛剛創建的button放進去
        quick_reply_array = QuickReply(items=[text_quireply_first, text_quireply_second, text_quireply_third])

        # line_bot_api 傳送回去
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='請選擇你要的節目', quick_reply=quick_reply_array))

    # 廁所
    # elif reply_text_messge.text == "我真帥":
    #     image_message = ImageSendMessage(
    #         original_content_url='https://s.newtalk.tw/album/news/207/5c64e354b5868.jpg',
    #         preview_image_url='https://github.com/hsiaopray/student_project/blob/master/handsome.png?raw=true'
    #     )
    #     line_bot_api.reply_message(event.reply_token, image_message)

    elif reply_text_messge.text == "我真帥":
        with open("./mirror.json", "r", encoding="utf-8") as mirror:
            json_object = json.load(mirror)

        template_message_from_json = TemplateSendMessage.new_from_json_dict(json_object)

        line_bot_api.reply_message(event.reply_token, template_message_from_json)

    elif reply_text_messge.text == "嘩啦啦嘩啦啦嘩啦啦......":
        # 創造一個圖片訊息
        image_message = ImageSendMessage(
            original_content_url='https://pic.17qq.com/uploads/ckcnmpgcpv.jpeg',
            preview_image_url='https://img.itw01.com/images/2018/03/16/23/2535_l5FZM5_V24RNEC.jpg!r800x0.jpg'
        )
        # line_bot_api 傳送過去
        line_bot_api.reply_message(event.reply_token, image_message)

    # 廚房互動
    elif reply_text_messge.text == "來喝點東西吧":
        # 創造QuickReplyButton
        text_quireply_first = QuickReplyButton(action=MessageAction(label="喝酒", text="好暈喔 @@"))
        text_quireply_second = QuickReplyButton(action=MessageAction(label="可口可樂", text="快樂肥宅水,讚啦!"))
        text_quireply_third = QuickReplyButton(action=MessageAction(label="果汁", text="好甜喔!是濃縮的吧!"))

        # 創造一個QuickReply,並把剛剛創建的button放進去
        quick_reply_array = QuickReply(items=[text_quireply_first, text_quireply_second, text_quireply_third])

        # line_bot_api 傳過回去
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='請選擇你要的飲品', quick_reply=quick_reply_array))

    elif reply_text_messge.text == "肚子有點餓了":
        # 創造QuickReplyButton
        text_quireply_first = QuickReplyButton(action=MessageAction(label="咖哩", text="自己煮的果然不能吃 = ="))
        text_quireply_second = QuickReplyButton(action=MessageAction(label="泡麵", text="最簡單的,最好吃!"))
        text_quireply_third = QuickReplyButton(action=MessageAction(label="牛排", text="啊!回來的太急,沒有買"))

        # 創造一個QuickReply,並把剛剛創建的button放進去
        quick_reply_array = QuickReply(items=[text_quireply_first, text_quireply_second, text_quireply_third])

        # line_bot_api 傳過回去
        line_bot_api.reply_message(event.reply_token, TextSendMessage(text='請選擇你要的飲品', quick_reply=quick_reply_array))

    elif reply_text_messge.text == "現在都封城,外面都沒人了":
        # 創造一個圖片訊息
        image_message = ImageSendMessage(
            original_content_url='https://s.rfi.fr/media/display/0a0719cc-4073-11ea-af6d-005056a98db9/w:1280/p:16x9/2020-01-26t065742z_155462673_rc2ine9bvjjo_rtrmadp_3_china-health.jpg',
            preview_image_url='https://s.rfi.fr/media/display/0a0719cc-4073-11ea-af6d-005056a98db9/w:1280/p:16x9/2020-01-26t065742z_155462673_rc2ine9bvjjo_rtrmadp_3_china-health.jpg'
        )
        # line_bot_api 傳送過去
        line_bot_api.reply_message(event.reply_token, image_message)

    elif reply_text_messge.text == "來洗衣服好了":
        with open("./wash_clothes.json", "r", encoding="utf-8") as wash_clothes:
            json_object = json.load(wash_clothes)

        template_message_from_json = TemplateSendMessage.new_from_json_dict(json_object)

        line_bot_api.reply_message(event.reply_token, template_message_from_json)

    elif reply_text_messge.text == "來做個乾淨的孩子吧":
        with open("./clothes_item.json", "r", encoding="utf-8") as clothes_item:
            json_object = json.load(clothes_item)

        template_message_from_json = TemplateSendMessage.new_from_json_dict(json_object)

        line_bot_api.reply_message(event.reply_token, template_message_from_json)

    elif reply_text_messge.text == "看看是什麼":
        item_first = "是張便利商店的發票阿,都變得破破爛爛的了"
        item_second = "撿到一百塊,超爽der"
        item_third = "是臥室房間的鑰匙"

        item_message = random.choice([item_first, item_second, item_third])

        line_bot_api.reply_message(event.reply_token, TextSendMessage(item_message))

        if item_message == "是臥室房間的鑰匙":
            # with open("./bedroom_key.json", "r", encoding="utf-8") as key:
            #     json_object = json.load(key)
            #
            # template_message_from_json = TemplateSendMessage.new_from_json_dict(json_object)
            #
            # line_bot_api.reply_message(event.reply_token, template_message_from_json)
            # if reply_text_messge.text == "是":
                line_bot_api.link_rich_menu_to_user(
                    user_id=line_bot_api.get_profile(event.source.user_id).user_id,
                    rich_menu_id="richmenu-3d72221c0ce598cc6f9ec723c08b10d3"
                )
    elif reply_text_messge.text == "看些床邊故事吧":
        with open("./bed_read.json", "r", encoding="utf-8") as bed_read:
            json_object = json.load(bed_read)

        template_message_from_json =  FlexSendMessage.new_from_json_dict(json_object)

        line_bot_api.reply_message(event.reply_token, template_message_from_json)

    elif reply_text_messge.text == "原來都是夢阿":

        dream_send_message = TextSendMessage(text="還好你在台灣,所以沒有這麼嚴重的疫情,不過還是要記得做好防疫工作喔!")
        dream_send_image = ImageSendMessage(
            original_content_url='https://github.com/hsiaopray/student_project/blob/master/dream_wash_hands.jpg?raw=true',
            preview_image_url='https://github.com/hsiaopray/student_project/blob/master/dream_wash_hands.jpg?raw=true')
        dream_send_vidoe_message = TextSendMessage(text="防疫新生活" + "https://www.youtube.com/watch?v=uiYtECIpbqQ")

        line_bot_api.reply_message(event.reply_token, [dream_send_message, dream_send_image, dream_send_vidoe_message])

        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-470c864eafa5de695a37b9388eb53ece"
        )

    elif reply_text_messge.text == "重新開始":
        # 建立文字消息
        follow_text_send_messange = TextSendMessage("境外移入記得隔離14天喔!")

        # 建立範本消息
        buttons_template_message = TemplateSendMessage(
            alt_text='Buttons template',
            template=ButtonsTemplate(
                thumbnail_image_url='https://github.com/hsiaopray/student_project/blob/master/start.jpg?raw=true',
                title='COVIN-19 (武漢肺炎)',
                text='政府公告: 旅遊疫情建議「第一級」及「第二級」國家入境旅客,入境後須自主健康管理14天',
                actions=[
                    # 如何解析多欄位的 data
                    # python querystring parser
                    MessageAction(
                        label="開始你的隔離生活",
                        text="點選圖片前往指定地點"
                    )
                ]
            )
        )

        # 麻煩line_bot_api 把文字消息、圖片消息、範本消息、json生成的模本消息交給line
        line_bot_api.reply_message(event.reply_token, [follow_text_send_messange, buttons_template_message])

        line_bot_api.link_rich_menu_to_user(
            user_id=line_bot_api.get_profile(event.source.user_id).user_id,
            rich_menu_id="richmenu-5ce99f617283f7be62f5613a1b03781e"
        )
示例#16
0
def handle_text_message(event):
    if not is_member(event):
        line_message_reply(event, [
            {
                'type': 'text',
                'text': '{0} is not member.'.format(get_profile(event))
            }
        ])

    text = event.message.text
    if text == 'test':
        line_bot_api.reply_message(
            event.reply_token, [
                TextSendMessage(text=event.message.text),
                TextSendMessage(text="line_id=" + event.source.user_id),
                TextSendMessage(text=get_profile(event)),
                StickerSendMessage(package_id=1, sticker_id=110),
                LocationSendMessage(address='ที่ไหนซักแห่ง', latitude='16.737367', longitude='100.273091',
                                    title='ส่งพิกัดให้นะ'),

            ]
        )

    if text == 'q':
        quick_reply = QuickReply(items=[
            QuickReplyButton(action=PostbackAction(label="กคลิกันดูสิ", data='ping')),
            QuickReplyButton(action=DatetimePickerAction(label='วันที่', mode='date', data='date1')),
        ])
        line_bot_api.reply_message(event.reply_token, [
            TextSendMessage(text='ได้เลย', quick_reply=quick_reply)
        ])

    if text == 'p':
        line_message_reply(event, [
            {
                "type": "text",
                "text": "Wow Wow"
            },
            {
                "type": "template",
                "altText": "this is a carousel template",
                "template": {
                    "type": "carousel",
                    "actions": [],
                    "columns": [
                        {
                            "text": "Text",
                            "actions": [
                                {
                                    "type": "uri",
                                    "label": "URL",
                                    "uri": "http://google.com?q=" + event.source.user_id
                                },
                                {
                                    "type": "message",
                                    "label": "Action 2",
                                    "text": "Action 2"
                                }
                            ]
                        },
                        {
                            "text": "Text",
                            "actions": [
                                {
                                    "type": "message",
                                    "label": "Action 1",
                                    "text": "Action 1"
                                },
                                {
                                    "type": "message",
                                    "label": "Action 2",
                                    "text": "Action 2"
                                }
                            ]
                        }
                    ]
                }
            },
            {
                "type": "template",
                "altText": "this is a buttons template",
                "template": {
                    "type": "buttons",
                    "actions": [
                        {
                            "type": "message",
                            "label": "Action 1",
                            "text": "Action 1"
                        },
                        {
                            "type": "message",
                            "label": "Action 2",
                            "text": "Action 2"
                        }
                    ],
                    "title": "Title",
                    "text": "Text"
                }
            },
            {
                "type": "template",
                "altText": "this is a confirm template",
                "template": {
                    "type": "confirm",
                    "actions": [
                        {
                            "type": "message",
                            "label": "Yes",
                            "text": "Yes"
                        },
                        {
                            "type": "message",
                            "label": "No",
                            "text": "No"
                        }
                    ],
                    "text": "Continue?"
                }
            },
            {
                "type": "sticker",
                "packageId": "1",
                "stickerId": "100"
            }
        ])

    if text == 'คิว':
        line_message_reply(event, [
            {
                "type": "flex",
                "altText": "this is a flex message",
                "contents": {
                    "type": "bubble",
                    "styles": {
                        "header": {
                            "backgroundColor": "#ffaaaa"
                        },
                        "body": {
                            "backgroundColor": "#aaffaa"
                        },
                        "footer": {
                            "backgroundColor": "#aaaaff"
                        }
                    },
                    "header": {
                        "type": "box",
                        "layout": "vertical",
                        "contents": [
                            {
                                "type": "text",
                                "text": "หมายเลข A0021",
                                "weight": "bold",
                                "size": "lg",
                                "align": "center",

                            }
                        ]
                    },
                    "hero": {
                        "type": "image",
                        "url": "https://barcode.tec-it.com/barcode.ashx?data=A0021&code=MobileQRCode&multiplebarcodes=false&translate-esc=false&unit=Fit&dpi=96&imagetype=Gif&rotation=0&color=%23000000&bgcolor=%23ffffff&qunit=Mm&quiet=0&eclevel=L",
                        "size": "full",
                        "aspectRatio": "2:1"
                    },
                    "body": {
                        "type": "box",
                        "layout": "vertical",
                        "contents": [
                            {
                                "type": "text",
                                "text": "เหลืออีก 10 คิวจะถึงคิวของท่าน เวลาโดยประมาณ 50 นาที",
                                "wrap": True
                            }
                        ]
                    },
                    "footer": {
                        "type": "box",
                        "layout": "vertical",
                        "contents": [
                            {
                                "type": "text",
                                "text": "Smart Queue Solution",
                                "align": "center",
                                "size": "sm"
                            }
                        ]
                    }
                }
            }
        ])
示例#17
0
def execute_command(event, text_string):

    # separate command string and other parameters or unnecessary inputs
    split_text = text_string.split()

    # get the first word (the command) while
    # lowering the characters and removing the '?' prefix
    command_string = split_text[0].lower()[1:]

    # get other words other than the command itself
    if len(split_text) > 1:
        other_string = split_text[1:]
    else:  # temporary fix
        other_string = []

    # get the command from database
    command_tuple = get_command(command_string)
    # if the command exists in the database, it should be truthy
    if command_tuple:
        # unpack the tuple
        c_type, c_content, c_clearance = get_command(command_string)

        # check if the user has clearance for the command
        if authenticate(event.source, c_clearance):

            # collect data
            track_api_calls(command_string, event.source.user_id)

            # for simple text-based replies
            if c_type == 'text':
                line_bot_api.reply_message(
                    event.reply_token, TextSendMessage(text=c_content))

            # for simple image-based replies
            elif c_type == 'image':
                # unpack the content first into ratio and image url
                ratio, image_url, alt_text = json.loads(c_content).values()
                # then create the content bubble using ratio and image url
                content = create_image_bubble(ratio, image_url)
                line_bot_api.reply_message(event.reply_token, FlexSendMessage(
                    alt_text=alt_text, contents=content))

            # for code text-based replies
            elif c_type == 'code':
                line_bot_api.reply_message(
                    event.reply_token, TextSendMessage(text=get_code(c_content)))

            # for updating code commands
            elif c_type == 'update_code':
                if other_string:
                    if command_string in ('gantikoderulat', 'gantikodelokerdoksos', 'gantikodelemarioren'):
                        update_code(c_content, other_string[0])
                    else:
                        update_code(c_content, ' '.join(other_string))

                    line_bot_api.reply_message(event.reply_token, TextSendMessage(
                        text=("Kode sudah diganti menjadi " + get_code(c_content))))
                else:
                    line_bot_api.reply_message(event.reply_token, TextSendMessage(
                        text=('Mau diganti sama apa kodenya?')))

            elif c_type == 'image carousel':
                # unpack the content first into ratio and image url
                ratio, image_urls, alt_text = json.loads(c_content).values()
                
                # count how many images are in the command
                images_count = len(image_urls)

                image_urls_sects = []
                if images_count < 51:
                    for i in range(5):
                        image_urls_sect = image_urls[i*10:(i+1)*10]
                        if image_urls_sect:
                            image_urls_sects.append(image_urls_sect)

                replies = [FlexSendMessage(contents=create_image_carousel(ratio, urls_sect), alt_text=alt_text) for urls_sect in image_urls_sects]
                line_bot_api.reply_message(event.reply_token, replies)

            # for complex replies [to do list], not yet added to database
            elif c_type == 'others':
                if command_string == 'agenda':
                    duration = translate_words_to_date(' '.join(other_string))
                    alt_text = "Agenda " + \
                        translate_date_to_words(int(duration)) + " Kedepan"
                    if authenticate(event.source, 2):
                        line_bot_api.reply_message(event.reply_token, FlexSendMessage(
                            alt_text=alt_text, contents=create_fungs_agenda(duration)))
                    else:
                        line_bot_api.reply_message(event.reply_token, FlexSendMessage(
                            alt_text=alt_text, contents=create_lfm_agenda(duration)))
                
                elif command_string == 'upcomingmovies':
                    start_date, end_date, region = parse_upcoming_movies_params(
                        other_string)
                    line_bot_api.reply_message(event.reply_token, FlexSendMessage(alt_text="Upcoming Movies", contents=create_upcoming_movies_carousel(
                        discover_movies(start_date=start_date, end_date=end_date, region=region))))
                
                elif command_string == 'nowshowing':
                    line_bot_api.reply_message(event.reply_token, FlexSendMessage(
                        alt_text="Now Showing", contents=create_now_showing_carousel(get_now_showing())))

            elif c_type == 'help':

                # if user asks for detailed help of a command
                if other_string:
                    reply = get_command_description(other_string[0])
                # general help
                else:
                    # commands available for kru
                    commands = '\n  • ?Agenda \n  • ?NowShowing \n  • ?UpcomingMovies \n  • ?Database \n  • ?FiLEFEM \n  • ?FTP \n  • ?FAQSurat \n  • ?TrackRecord \n  • ?WhatSOPKru \n  • ?KitMakingMovies \n  • ?Alkhazini \n  • ?PinjamDisney+ \n  • ?PinjamNetflix \n  • ?YukSukacita'
                    # commands available only for fungs
                    if authenticate(event.source, 2):
                        commands += '\n\n  • ?KodeRulat \n  • ?GantiKodeRulat \n  • ?KodeLokerDoksos \n  • ?GantiKodeLokerDoksos \n  • ?PasswordEneng \n  • ?GantiPasswordEneng \n  • ?PasswordCici \n  • ?GantiPasswordCici'

                    reply = "Halo! \nAku bisa bantu kru sekalian dengan beberapa perintah, diantaranya: " + commands + \
                        "\n\nKalau masih bingung perintahnya untuk apa, coba ketik ?Help dan nama perintahnya, \nmisal: ?Help Agenda "

                # create quick reply buttons
                quick_reply_buttons = QuickReply(items=[
                    QuickReplyButton(action=MessageAction(
                        label="Agenda 📅", text="?Agenda")),
                    QuickReplyButton(action=MessageAction(
                        label="Now Showing 🍿", text="?NowShowing")),
                    QuickReplyButton(action=MessageAction(
                        label="Upcoming Movies 🎬", text="?UpcomingMovies")),
                    QuickReplyButton(action=MessageAction(
                        label="FiLEFEM 📑", text="?FiLEFEM"))
                ])

                # send the message
                line_bot_api.reply_message(
                    event.reply_token, TextSendMessage(
                        text=reply, quick_reply=quick_reply_buttons))
示例#18
0
def handle_message(event):
    """
    這裡很眼熟吧?就發送一個訊息
    quick_reply 底下的動作,就是幫你建立自動回覆的按鈕
    每一個 QuickReplyButton 都代表一個按鈕
    label 就是顯示的文字,text就是當你點下去,他會回復你的訊息
    最後一樣 push_message
    """
    # user_id = event.source.user_id
    text = event.message.text
    
    #line_bot_api.reply_message(event.reply_token, carousel_template_message)
    
    districts = ['嘉義縣','新北市','嘉義市','新竹縣', '新竹市', '臺北市', '臺南市', '宜蘭縣', '苗栗縣', '雲林縣', '花蓮縣', 
    '臺中市', '臺東縣', '桃園市', '南投縣', '高雄市', '金門縣', '屏東縣', '基隆市', '澎湖縣', '彰化縣', '連江縣']

    for a,b,c,d,e in fish_price:
        if event.message.text == a:
            text = f'{a}的價格: $ {b}\n出沒地點:{c}\n月份:{d}\n時間:{e}'
            line_bot_api.reply_message(event.reply_token,TextSendMessage(text))
            return 0

    for a,b in bugs_price:
        if event.message.text == a:
            text = f'{a}的價格: $ {b}'
            line_bot_api.reply_message(event.reply_token,TextSendMessage(text))
            return 0

    for a,b in shell_price:
        if event.message.text == a:
            text = f'{a}的價格: $ {b}'
            line_bot_api.reply_message(event.reply_token,TextSendMessage(text))
            return 0

    for a,b in other_price:
        if event.message.text == a:
            text = f'{a}的價格: $ {b}'
            line_bot_api.reply_message(event.reply_token,TextSendMessage(text))
            return 0
        
    
    fishlist=[]
    bugslist=[]
    shelllist=[]
    otherlist=[]

    #價格排序降序並把文字結果放在陣列
    def fish_text(fish_price):
        fish=[random.choice(fish_price) for i in range(6)]
        #fish = sorted(fish_price,key=lambda x:eval(x[1]),reverse=True)[:5]
        for a,b,c,d,e in fish:
            fishlist.append(f'{a}: $ {b}')

        return "\n".join(fishlist)

    def bugs_text(bugs_price):
        bugs=[random.choice(bugs_price) for i in range(6)]
        #bugs = sorted(bugs_price,key=lambda x:eval(x[1]),reverse=True)[:-10]
        for a,b in bugs:
            bugslist.append(f'{a}: $ {b}')

        return "\n".join(bugslist)

    def shell_text(shell_price):
    #shell=[random.choice(shell_price) for i in range(5)]
        shell = sorted(shell_price,key=lambda x:eval(x[1]),reverse=True)[:]
        for a,b in shell:
            shelllist.append(f'{a}: $ {b}')

        return "\n".join(shelllist)

    def other_text(other_price):
        other = sorted(other_price,key=lambda x:eval(x[1]),reverse=True)[:]
        for a,b in other:
            otherlist.append(f'{a}: $ {b}')

        return "\n".join(otherlist)
        
    if event.message.text =='Hi' or event.message.text =='嗨':
        line_bot_api.reply_message(
                event.reply_token,
                TextSendMessage(
                    text='請輸入:示範',
                    quick_reply=QuickReply(
                        items=[
                            QuickReplyButton(
                                action=MessageAction(label="魚價格", 
                                text=fish_text(fish_price))
                            ),
                            QuickReplyButton(
                                action=MessageAction(label="蟲價格", 
                                text=bugs_text(bugs_price))
                            ),
                            QuickReplyButton(
                                action=MessageAction(label="貝殼價格", 
                                text=shell_text(shell_price))
                            ),
                            QuickReplyButton(
                                action=MessageAction(label="其他價格", 
                                text=other_text(other_price))
                            ),
                            QuickReplyButton(
                                action=MessageAction(label="天氣", 
                                text='臺北市')
                            )
                        ]
                    )
                )
        )
        return 0

    ## 天氣
    if '台' in text:
        text=text.replace('台','臺')
        if text in districts:
            line_bot_api.reply_message(event.reply_token,TextSendMessage(weather(text)))
            return 0
    elif text in districts:
        line_bot_api.reply_message(event.reply_token,TextSendMessage(weather(text)))
        return 0
    elif text == '示範':
        currency = get_currencyjson()
        currency_USDTWD = '更新時間: '+currency['USDTWD']['UTC']+'\n國際匯率: '+ format(currency['USDTWD']['Exrate'],'.4f')
        currency_USDJPY = '更新時間: '+currency['USDJPY']['UTC']+'\n國際匯率: '+ format(currency['USDJPY']['Exrate'],'.4f')
        currency_TWDJPY = '更新時間: '+currency['USDJPY']['UTC']+'\n國際匯率: '+ format(currency['USDTWD']['Exrate']/currency['USDJPY']['Exrate'],'.4f')
        wtcg=weather('臺中市')
        wtpe=weather('臺北市')

        line_bot_api.reply_message(event.reply_token, TemplateSendMessage(
            alt_text='魚類名單',
            template=CarouselTemplate(
                columns=[
                    CarouselColumn(
                        thumbnail_image_url='https://www.tech-girlz.com/wp-content/uploads/2020/04/%E5%8B%95%E6%A3%AE4%E6%9C%88%E9%AD%9A%E9%A1%9E-1024x680.png',
                        title='動物森友會查詢工具',
                        text='請依以下查詢教學操作',
                        actions=[
                            PostbackAction(
                                label='魚的價格',
                                data='fish'
                            ),
                            PostbackAction(
                                label='昆蟲價格',
                                data='bug'
                            ),PostbackAction(
                                label='其他價格',
                                data='other'
                            ),
                        ]
                    ),
                    CarouselColumn(
                        thumbnail_image_url='https://www.tech-girlz.com/wp-content/uploads/2020/04/%E5%8B%95%E6%A3%AE4%E6%9C%88%E9%AD%9A%E9%A1%9E-1024x680.png',
                        title='匯率查詢工具',
                        text='請依以下查詢教學操作',
                        actions=[
                            MessageAction(
                                label='美金台幣',
                                text=currency_USDTWD
                            ),
                            MessageAction(
                                label='美金日幣',
                                text=currency_USDJPY
                            ),
                            MessageAction(
                                label='台幣日幣',
                                text=currency_TWDJPY
                            ),
                        ]
                    ),
                    CarouselColumn(
                        thumbnail_image_url='https://www.tech-girlz.com/wp-content/uploads/2020/04/%E5%8B%95%E6%A3%AE4%E6%9C%88%E9%AD%9A%E9%A1%9E-1024x680.png',
                        title='氣象查詢工具',
                        text='請依以下查詢教學操作',
                        actions=[
                            MessageAction(
                                label='台北市',
                                text=wtpe
                            ),
                            MessageAction(
                                label='台中市',
                                text=wtcg
                            ),
                            PostbackAction(
                                label='氣溫',
                                data='temperature'
                            )
                        ]
                    ),
                   
                ]
            )
        ))
        return 0
        
    elif text.isalnum():
        line_bot_api.reply_message(event.reply_token,TextSendMessage('請輸入:示範 獲得說明'))
        return 0
示例#19
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)
示例#20
0
from linebot.models import (TextSendMessage, QuickReplyButton, MessageAction,
                            QuickReply)

text_message = TextSendMessage(
    text='Hello, world',
    quick_reply=QuickReply(items=[
        QuickReplyButton(action=MessageAction(label="label", text="text"))
    ]))
示例#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)
            ])
        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))
示例#22
0
def handle_TextMessage(event):
    print(event.message.text)
    #### Get If in Search Mode ####
    currentStatus = r.get(event.source.user_id + "search")
    #### IN Search Mode ####
    if currentStatus == b'1':
        if event.message.text.casefold() == "exit".casefold(
        ):  #### exit search mode
            r.set(event.source.user_id + "search", 0)
            msg = 'Successfully exit Search Mode. You could send "help" to learn how to use in the normal mode.'
            line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))
            return
        ######Wikipedia#####
        searchResult = searchWiki(event.message.text)
        introText = ("From Wikipedia: \n" + searchResult[0])
        print(introText)
        line_bot_api.reply_message(
            event.reply_token,
            [TextSendMessage(introText),
             TextSendMessage(searchResult[1])])
        ######Wikipedia#####
    #### IN Search Mode ####
    #### Enter Search Mode ####
    if event.message.text.casefold() == "search mode".casefold():
        r.set(event.source.user_id + "search", 1)
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(
                'You are in Search Mode now. You could send any keywords to search. To exit Search Mode, please send "exit".'
            ))
    #### Enter Search Mode ####
    #### Exit Search Mode ####
    if event.message.text.casefold() == "exit".casefold():
        if currentStatus == b'1':
            r.set(event.source.user_id + "search", 0)
            msg = 'Successfully exit Search Mode. You could send "help" to learn how to use in the normal mode.'
        else:
            msg = 'You have already exited the Search Mode. You are in normal mode now. You could send "help" to learn how to use in the normal mode.'
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))
    #### Exit Search Mode ####
    #### Help ####
    if event.message.text.casefold() == "help".casefold():
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(  # quick reply for help
                text=
                'You could send "coronavirus tips" to get some tips.\n\nYou could send some city names (e.g. HongKong, Beijing, Shanghai) to get the corresponding comfirmed coronavirus cases. You could also send "total" to get the total case number.\n\nYou could send "Find Mask" to find some face masks. You could also send "config" to choose find the nearest or the cheapest face mask.\n\n You could send "search mode" to get in Wikipedia Search Mode',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(action=MessageAction(
                        label="Coronavirus Tips", text="coronavirus tips")),
                    QuickReplyButton(action=MessageAction(
                        label="Hong Kong cases", text="HongKong")),
                    QuickReplyButton(action=MessageAction(label="Total cases",
                                                          text="total")),
                    QuickReplyButton(action=MessageAction(label="Find Mask",
                                                          text="Find Mask")),
                    QuickReplyButton(action=MessageAction(
                        label="Mask Preference", text="config")),
                    QuickReplyButton(action=MessageAction(
                        label="Enter Search Mode", text="Search Mode"))
                ])))
    #### Help ####
    #### Stateful ####
    if event.message.text.casefold() == "config/findMask/cheapest".casefold():
        r.set(event.source.user_id,
              "cheap")  # rememeber every user's preference
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(  # quick reply for config
                text='OK, We will find the cheapest mask store for you',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(action=MessageAction(
                        label="Find Mask NOW!", text="Find Mask"))
                ])))
    elif event.message.text.casefold() == "config/findMask/nearest".casefold():
        r.set(event.source.user_id,
              "nearby")  # rememeber every user's preference
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(  # quick reply for config
                text='OK, We will find the nearest mask store for you',
                quick_reply=QuickReply(items=[
                    QuickReplyButton(action=MessageAction(
                        label="Find Mask NOW!", text="Find Mask"))
                ])))
    #### Stateful ####
    QuickReply_text_message_config = TextSendMessage(  # quick reply for config
        text='Here are the available configurations for finding masks',
        quick_reply=QuickReply(items=[
            QuickReplyButton(
                action=MessageAction(label="Cheap Mask First",
                                     text="config/findMask/cheapest"),
                image_url=
                "https://cdn1.iconfinder.com/data/icons/ios-11-glyphs/30/money_bag-512.png"
            ),
            QuickReplyButton(
                action=MessageAction(label="Nearby Mask First",
                                     text="config/findMask/nearest"),
                image_url=
                "https://lh3.googleusercontent.com/proxy/1a9k68551lJJFBDpXMENUSDxJC33VlTmir0Bj2LrZJ5QLOoHD6V8G-k3wpAfjdqN7oizSWerzL1nWwWbHKaYz3FCkOe5GpaV1OhRVJQQLrKHINKqMA"
            )
        ]))

    if event.message.text.casefold() == "config".casefold(
    ):  # quick reply for config
        line_bot_api.reply_message(event.reply_token,
                                   QuickReply_text_message_config)
    ####ZHU Feng for quick reply location
    QuickReply_text_message = TextSendMessage(
        text=
        'Please send your location so that we could help you find a neaby face mask store',
        quick_reply=QuickReply(items=[
            QuickReplyButton(action=LocationAction(label="Send Location"), )
        ]))
    if event.message.text.casefold() == "Find Mask".casefold():
        line_bot_api.reply_message(event.reply_token, QuickReply_text_message)
    ####ZHU Feng for quick reply location
    ## Sample Code of getting string from Redis
    if event.message.text.casefold() == "sample".casefold():
        msg = r.get("sample").decode("utf-8")
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))
    ## WANG Yuhao ##

    print(event.message.text)
    if event.message.text == "coronavirus tips":
        message = TemplateSendMessage(
            alt_text='Carousel template',
            template=CarouselTemplate(columns=[
                CarouselColumn(
                    thumbnail_image_url=
                    'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcR5mlTGpxz5Ogie5g93siEvUcTy5dMxnOAJeiUwrTFSJtOEIi8u&usqp=CAU',
                    title='Measure 1',
                    text='Wear mask when go outside.',
                    actions=[
                        PostbackTemplateAction(label='Some tips',
                                               text='tip 1',
                                               data='action=buy&itemid=1'),
                        #                             MessageTemplateAction(
                        #                                 label='message1',
                        #                                 text='message text1'
                        #                             ),
                        URITemplateAction(
                            label='More details',
                            uri=
                            'https://jingyan.baidu.com/article/f54ae2fc46c8061e93b84950.html'
                        )
                    ]),
                CarouselColumn(
                    thumbnail_image_url=
                    'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTruPXKu--ondWTUstQVMeqAc__4WMTB97rI6lSS-0gK2c7QPmE&usqp=CAU',
                    title='Measure 2',
                    text='Wash hands frequently.',
                    actions=[
                        PostbackTemplateAction(label='Some tips',
                                               text='tip 2',
                                               data='action=buy&itemid=1'),
                        #                             MessageTemplateAction(
                        #                                 label='message1',
                        #                                 text='message text1'
                        #                             ),
                        URITemplateAction(
                            label='More details',
                            uri=
                            'https://jingyan.baidu.com/article/ff4116257cae5753e48237de.html'
                        )
                    ]),
                CarouselColumn(
                    thumbnail_image_url=
                    'https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTIZzVtv-nGuPw-FebkzaIGI28s9PdBG3gTWtdDH5iHcK0mvvr5&usqp=CAU',
                    title='Measure 3',
                    text='Do not go to the crowed places.',
                    actions=[
                        PostbackTemplateAction(label='Some tips',
                                               text='tip 3',
                                               data='action=buy&itemid=2'),
                        #                             MessageTemplateAction(
                        #                                 label='message2',
                        #                                 text='message text2'
                        #                             ),
                        URITemplateAction(
                            label='More details',
                            uri=
                            'https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_3'
                        )
                    ])
            ]))
        line_bot_api.reply_message(event.reply_token, message)
#more buttons and images instead of only words,looks better

#         msg = """You ought to remember the following tips.
#         1.Wearing mask when go outside.
#         2.Washing hands frequently.
#         3.Do not go to the crowed places.
#         If you want to know more details,just type in the serial number."""
#         line_bot_api.reply_message(
#             event.reply_token,
#             TextSendMessage(msg)
#         )
    elif event.message.text == "tip 1":
        msg = r.get('tip1').decode("utf-8")
        ###############using redis##################
        #         msg = """How to wear mask correctly.
        #         ·The coloured side of the mask faces outwards, with the metallic strip uppermost.
        #         ·The strings or elastic bands are positioned properly to keep the mask firmly in place.
        #         ·The mask covers the nose, mouth and chin.
        #         ·The metallic strip moulds to the bridge of the nose."""
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))
    elif event.message.text == "tip 2":
        msg = r.get('tip2').decode("utf-8")
        ###############using redis##################
        #         msg = """How to wash hands correctly.
        #         ·Wet your hands with clean, running water (warm or cold), turn off the tap, and apply soap....
        #         ·Lather your hands by rubbing them together with the soap.
        #         ·Lather the backs of your hands, between your fingers, and under your nails.
        #         ·Scrub your hands for at least 20 seconds. Need a timer? Hum the “Happy Birthday” song from beginning to end twice.
        #         ·Rinse your hands well under clean, running water.Dry your hands using a clean towel or air dry them."""
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))
    elif event.message.text == "tip 3":
        msg = r.get('tip3').decode("utf-8")
        #############using redis##################
        #         msg = "May be staying at home is the best choice,although the situation in China is getting better and better.If you'd like to travel abroad(like US,France,etc),that's not a good idea."
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))
#     else:
#         msg = "Sorry,I can't catch your point.You can type in 'measures to prevent new coronavirus' for some information about new coronavirus."
#         line_bot_api.reply_message(
#             event.reply_token,
#             TextSendMessage(msg)
#         )
## WANG Yuhao##

## ZHI Yiyao ##

    elif event.message.text.casefold() == "shanghai".casefold():
        msg = "current number: " + r.hget("infection",
                                          "shanghai").decode("utf-8")
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))

    elif event.message.text.casefold() == "hubei".casefold():
        msg = "current number: " + r.hget("infection", "hubei").decode("utf-8")
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))

    elif event.message.text.casefold() == "hongkong".casefold():
        msg = "current number: " + r.hget("infection",
                                          "hongkong").decode("utf-8")
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))

    elif event.message.text.casefold() == "guangdong".casefold():
        msg = "current number: " + r.hget("infection",
                                          "guangdong").decode("utf-8")
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))

    elif event.message.text.casefold() == "taiwan".casefold():
        msg = "current number: " + r.hget("infection",
                                          "taiwan").decode("utf-8")
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))

    elif event.message.text.casefold() == "beijing".casefold():
        msg = "current number: " + r.hget("infection",
                                          "beijing").decode("utf-8")
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))

    elif event.message.text.casefold() == "total".casefold():
        msg = "To view real-time situation please visit  " + "https://voice.baidu.com/act/newpneumonia/newpneumonia/?from=osari_pc_3"
        line_bot_api.reply_message(event.reply_token, TextSendMessage(msg))
    ## ZHI Yiyao ##

    else:
        QuickReply_text_message_help = TextSendMessage(  # quick reply for help
            text=
            'Sorry, I cannot understand you. Send "help" to learn how to use this bot',
            quick_reply=QuickReply(items=[
                QuickReplyButton(action=MessageAction(label="I need help NOW!",
                                                      text="help"))
            ]))
        line_bot_api.reply_message(event.reply_token,
                                   QuickReply_text_message_help)
示例#23
0
from linebot.models import (
        QuickReply, QuickReplyButton, LocationAction
)

quick_reply = QuickReply(
        items = [
            QuickReplyButton(
                action = LocationAction(label = "Location")
                )
            ]
        )
示例#24
0
def handle_message(event):
    #總通道
    deviceID = '17750119494'
    apiURL = 'http://iot.cht.com.tw/iot/v1/device/' + deviceID + '/rawdata'
    headers = {
        "CK": "PK0B9PPBEHGEA4ASC7",
        "Content-Type": "application/json",
    }

    print(event)
    text = event.message.text
    if (text == "hi"):
        today = str(datetime.date.today())
        UTC = str(datetime.datetime.utcnow())[11:23]
        reply_text = "Hello " + today
        print(text)
        #Your user ID

    elif (text == "團隊資訊"):
        reply_text = "http://192.168.43.51/index1.php"

    elif (text == "@本期中獎號碼"):
        reply_text = monoNim(0)

    elif (text == "@前期中獎號碼"):
        try:
            message = [
                TextSendMessage(text=monoNim(1)),
                TextSendMessage(text=monoNim(2))
            ]
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(event.reply_token, message,
                                       TextSendMessage(reply_text="發生錯誤"))
    elif (text == "@輸入發票最後三碼"):
        reply_text = "請輸入發票末三碼"

    elif ("圖片" in text):
        try:
            message = ImageSendMessage(
                original_content_url="https://i.imgur.com/LNwfaQL.jpg",
                preview_image_url="https://i.imgur.com/LNwfaQL.jpg")
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(event.reply_token, message,
                                       TextSendMessage(reply_text="發生錯誤"))
    elif ("瀚元" in text):
        try:
            message = [
                TextSendMessage(text="瀚元牛逼~~"),
                StickerSendMessage(package_id="1", sticker_id="14")
            ]
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(event.reply_token, message,
                                       TextSendMessage(reply_text="發生錯誤"))

    elif ("介紹" in text):
        try:
            message = [
                TextSendMessage(text="我害羞~~"),
                ImageSendMessage(
                    original_content_url="https://i.imgur.com/LNwfaQL.jpg",
                    preview_image_url="https://i.imgur.com/LNwfaQL.jpg"),
                StickerSendMessage(package_id="2", sticker_id="522")
            ]
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(event.reply_token, message,
                                       TextSendMessage(reply_text="發生錯誤"))

    elif ("醫院" in text):
        try:
            message = [
                TextSendMessage(
                    text="臺大醫院網址:\nhttps://www.ntuh.gov.tw/ntuh/Index.action"),
                LocationSendMessage(
                    title='臺大醫院',
                    address=
                    "No. 7, Zhongshan South Road, Zhongzheng District, Taipei City, 100",
                    latitude=25.0407,
                    longitude=121.5190)
            ]
            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(event.reply_token, message,
                                       TextSendMessage(reply_text="發生錯誤"))

    elif ("快速選單" in text):
        try:
            message = TextSendMessage(
                text="請選擇最喜歡的程式語言",
                quick_reply=QuickReply(items=[
                    QuickReplyButton(
                        action=MessageAction(label="python", text="python")),
                    QuickReplyButton(
                        action=MessageAction(label="java", text="java")),
                    QuickReplyButton(
                        action=MessageAction(label="C#", text="c#")),
                    QuickReplyButton(
                        action=MessageAction(label="c++", text="c++"))
                ]))

            line_bot_api.reply_message(event.reply_token, message)
        except:
            line_bot_api.reply_message(event.reply_token, message,
                                       TextSendMessage(reply_text="發生錯誤"))

    elif (text == "可查詢" or text == "功能" or text == "?"):
        reply_text = "本產品[肺-REAL-GOOD]官方網址如下:\nhttp://192.168.43.51/index1.php\n功能列表:\n***最新10筆資料***\n1.顯示病患檢測時間\n2.顯示病患ID及預測得病率\n3.可上傳影像立即辨識\n聯絡電話:02-2234-2258\nEmail:[email protected]"
    elif ("肺癌" in text):
        apiURL = 'https://iot.cht.com.tw/iot/v1/device/23632626264/sensor/data2/rawdata?start=2020-08-19T23:59:59.000Z&end=2020-12-31T23:59:59.000Z&utcOffset=8'  #大平台通道ID  &utcOffset=8
        headers = {
            "CK": "PK4ACRESYYKAKUUTPE",
            "Content-Type": "application/json",
        }
        payload = [{"id": "data2"}]
        response1 = requests.get(apiURL,
                                 headers=headers,
                                 data=json.dumps(payload))
        hjson = json.loads(response1.text)
        #reply_text = "預約掛號網址:http://localhost/index1.php"
        try:
            get_date1 = (hjson[-1]['time'], hjson[-1]['value'])
            get_date2 = (hjson[-2]['time'], hjson[-2]['value'])
            get_date3 = (hjson[-3]['time'], hjson[-3]['value'])
            get_date4 = (hjson[-4]['time'], hjson[-4]['value'])
            get_date5 = (hjson[-5]['time'], hjson[-5]['value'])
            get_date6 = (hjson[-6]['time'], hjson[-6]['value'])
            get_date7 = (hjson[-7]['time'], hjson[-7]['value'])
            get_date8 = (hjson[-8]['time'], hjson[-8]['value'])
            get_date9 = (hjson[-9]['time'], hjson[-9]['value'])
            get_date10 = (hjson[-10]['time'], hjson[-10]['value'])
            reply_text = str(get_date1) + "\n" + str(get_date2) + "\n" + str(
                get_date3) + "\n" + str(get_date4) + "\n" + str(
                    get_date5) + "\n" + str(get_date6) + "\n" + str(
                        get_date7) + "\n" + str(get_date8) + "\n" + str(
                            get_date9) + "\n" + str(get_date10)
        except:
            try:
                reply_text = str(get_date1) + "\n" + str(
                    get_date2) + "\n" + str(get_date3) + "\n" + str(
                        get_date4) + "\n" + str(get_date5) + "\n" + str(
                            get_date6) + "\n" + str(get_date7) + "\n" + str(
                                get_date8) + "\n" + str(get_date9)
            except:
                try:
                    reply_text = str(get_date1) + "\n" + str(
                        get_date2) + "\n" + str(get_date3) + "\n" + str(
                            get_date4) + "\n" + str(get_date5) + "\n" + str(
                                get_date6) + "\n" + str(
                                    get_date7) + "\n" + str(get_date8)
                except:
                    try:
                        reply_text = str(get_date1) + "\n" + str(
                            get_date2) + "\n" + str(get_date3) + "\n" + str(
                                get_date4) + "\n" + str(
                                    get_date5) + "\n" + str(
                                        get_date6) + "\n" + str(get_date7)
                    except:
                        try:
                            reply_text = str(get_date1) + "\n" + str(
                                get_date2) + "\n" + str(
                                    get_date3) + "\n" + str(
                                        get_date4) + "\n" + str(
                                            get_date5) + "\n" + str(get_date6)
                        except:
                            try:
                                reply_text = str(get_date1) + "\n" + str(
                                    get_date2) + "\n" + str(
                                        get_date3) + "\n" + str(
                                            get_date4) + "\n" + str(get_date5)
                            except:
                                try:
                                    reply_text = str(get_date1) + "\n" + str(
                                        get_date2) + "\n" + str(
                                            get_date3) + "\n" + str(get_date4)
                                except:
                                    try:
                                        reply_text = str(
                                            get_date1) + "\n" + str(
                                                get_date2) + "\n" + str(
                                                    get_date3)
                                    except:
                                        try:
                                            reply_text = str(
                                                get_date1) + "\n" + str(
                                                    get_date2)
                                        except:
                                            reply_text = str(get_date1)
    else:
        pass

    message = TextSendMessage(reply_text)
    line_bot_api.reply_message(event.reply_token, message)
示例#25
0
def handle_text_message(event):
    text = event.message.text

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

Quickreply_Friend = TextSendMessage(
    text='如果你喜歡本服務,歡迎分享',
    quick_reply=QuickReply(items=[
        QuickReplyButton(
            action=PostbackAction(label="分享Line好友資料", data="ShareProfile")),
        QuickReplyButton(
            action=PostbackAction(label="分享Line ID", data="ShareID")),
        QuickReplyButton(
            action=PostbackAction(label="分享Line QR code", data="ShareQR")),
    ]))
# In[ ]:


# 告知handler,如果收到FollowEvent,則做下面的方法處理
# handler如果收到關注事件時,執行下面的方法
@handler.add(FollowEvent)
def reply_text_and_get_user_profile(event):
    # 取出消息內User的資料
    user_profile = line_bot_api.get_profile(event.source.user_id)

    # 將用戶資訊存在檔案內
    my_database.csv_record_user_info(
示例#28
0
def handle_stage(event):

    req_json = dict()
    profile = line_bot_api.get_profile(event.source.user_id)
    req_json['message'] = event.message.text
    req_json['user_id'] = event.source.user_id
    req_json['username'] = profile.display_name
    EC2_URL = "http://13.209.239.166/"

    response = requests.post(url=EC2_URL, json=req_json)

    status = response.status_code
    if status // 100 == 2:
        res_json = response.json()
        print("res_json: ", res_json)
        if 'stage' in res_json:
            stage = res_json['stage']

            if stage == 0:
                buttons_template = ButtonsTemplate(
                    title='궁금한 것을 알려주세요!',
                    text='띵톡이가 할 수 있는 일들이에요.',
                    actions=[
                        MessageAction(label='경로 내의 화장실 정보', text='경로 내'),
                        MessageAction(label='특정 역의 화장실 정보', text='특정역'),
                        MessageAction(label='최단 시간 경로 보기', text='최단 경로'),
                        MessageAction(label='최소 환승 경로 보기', text='최소 환승')
                    ])
                line_bot_api.reply_message(
                    event.reply_token,
                    TemplateSendMessage(alt_text='기능 선택하기',
                                        template=buttons_template))

            elif stage == 4:
                last_stage = res_json['last_stage']
                if last_stage == 1:
                    reply_msg = "{start}~{end}의 경로를 찾습니다. 어떤 경로로 검색할까요?".format(
                        start=res_json['start'], end=res_json['end'])
                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(
                            text=reply_msg,
                            quick_reply=QuickReply(items=[
                                QuickReplyButton(action=MessageAction(
                                    label="최단 시간", text="최단 시간 방법")),
                                QuickReplyButton(action=MessageAction(
                                    label="최소 환승", text="최소 환승 방법")),
                                QuickReplyButton(action=MessageAction(
                                    label="출발역이 틀렸어!", text="출발역 틀림")),
                                QuickReplyButton(action=MessageAction(
                                    label="도착역이 틀렸어!", text="도착역 틀림")),
                                QuickReplyButton(action=MessageAction(
                                    label="역이 전부 틀렸어 T.T", text="역이 전부 틀림"))
                            ])))

                elif last_stage in [21, 22]:
                    reply_msg = "{start}~{end}의 경로를 찾습니다. 경로가 맞나요?".format(
                        start=res_json['start'], end=res_json['end'])
                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(
                            text=reply_msg,
                            quick_reply=QuickReply(items=[
                                QuickReplyButton(action=MessageAction(
                                    label="응!! 똑똑한걸~?", text="다 맞음")),
                                QuickReplyButton(action=MessageAction(
                                    label="출발역이 틀렸어!", text="출발역 틀림")),
                                QuickReplyButton(action=MessageAction(
                                    label="도착역이 틀렸어!", text="도착역 틀림")),
                                QuickReplyButton(action=MessageAction(
                                    label="역이 전부 틀렸어 T.T", text="역이 전부 틀림"))
                            ])))

            # 경로 내(stage=1) 시나리오 종료 단계
            elif stage == 5:
                toilet_list = res_json['toilet_here']

                items_list = [
                    CarouselColumn(
                        thumbnail_image_url=IMAGE_URL.format(toilet_name),
                        title=toilet_name,
                        text=detailed,
                        actions=[
                            URIAction(label="자세히 보기",
                                      uri=DETAILED_NAVER_MAP_URL.format(code))
                        ]) for toilet_name, code, detailed in toilet_list
                ]

                carousel_template = CarouselTemplate(
                    columns=items_list,
                    # image_aspect_ratio="rectangle",
                    image_size="cover"  # another options: "contain"
                )
                line_bot_api.reply_message(
                    event.reply_token,
                    TemplateSendMessage(alt_text='화장실이 있는 역 리스트',
                                        template=carousel_template))
                fin_text_msg = """여기까지가 띵톡이 찾은 개찰구 내 화장실이에요!\n계속 해당 기능을 이용하시려면 'A역에서 B역으로 가는 길이야' 라고 다시 입력해 주시거나 이용을 원치 않으시면 종료'라고 입력해 주세요!"""
                line_bot_api.push_message(event.source.user_id,
                                          [TextSendMessage(text=fin_text_msg)])

            # 경로 찾기 final output
            elif stage == 23:

                json_form = setting_json_form(res_json)
                message = FlexSendMessage(alt_text="경로 출력", contents=json_form)
                line_bot_api.reply_message(event.reply_token, message)
            elif stage in [11, 33, 34]:
                reply_msg = res_json['message']
                candidate_words = res_json['candidate_words']
                len_candidate = len(candidate_words)

                if len_candidate > 1:
                    len_candidate = len(candidate_words)

                    items_list = list()
                    for i in range(len_candidate):
                        word = candidate_words[i]
                        items_list.append(
                            QuickReplyButton(
                                action=MessageAction(label=word, text=word)))

                    items_list.append(
                        QuickReplyButton(action=MessageAction(
                            label="찾는 역이름이 없어", text="없음")))

                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(
                            text=reply_msg,
                            quick_reply=QuickReply(items=items_list)))

                else:
                    line_bot_api.reply_message(event.reply_token,
                                               TextSendMessage(text=reply_msg))

            elif stage == 3:
                reply_msg = res_json['message']
                candidate_words = res_json['candidate_words']
                len_candidate = len(candidate_words)

                if len_candidate > 1:

                    items_list = []
                    for i in range(len_candidate):
                        word = candidate_words[i]
                        items_list.append(
                            QuickReplyButton(
                                action=MessageAction(label=word, text=word)))

                    items_list.append(
                        QuickReplyButton(action=MessageAction(
                            label="찾는 역이름이 없어", text="없음")))

                    line_bot_api.reply_message(
                        event.reply_token,
                        TextSendMessage(
                            text=reply_msg,
                            quick_reply=QuickReply(items=items_list)))

                else:
                    line_bot_api.reply_message(event.reply_token,
                                               TextSendMessage(text=reply_msg))

            # 특정역(stage=10) 시나리오 종료 단계
            elif stage in [19]:
                reply_msg = res_json['message']

                reply_msg += "\n계속 다른 역을 찾고 싶으시면 'A'역과 같이 입력해 주시거나 이용을 종료하고 싶으시면 '종료'라고 적어주세요!"
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text=reply_msg))

            else:  # case: stage == 11, ...
                reply_msg = res_json["message"]
                line_bot_api.reply_message(event.reply_token,
                                           TextSendMessage(text=reply_msg))
    else:
        reply_msg = "예기치 않은 오류가 발생했습니다 : \n 띵톡을 다시 불러 실행해 주시거나 관리자에게 문의해 주세요ㅠㅠ"
        line_bot_api.reply_message(event.reply_token,
                                   TextSendMessage(text=reply_msg))
示例#29
0
from linebot.models import (MessageEvent, TextMessage, TextSendMessage,
                            QuickReply, QuickReplyButton, MessageAction)
from calculate import calculate
from calculate_history import calculate_history
import re
from models import AccountMovement
from server import db

ASK_FOR_FUNCTION = "รับ หรือ จ่าย"
ASK_FOR_NUMBER = "จำนวนเงิน"
ASK_FOR_RESPONSE = "ต้องการลบข้อมูลเก่าทิ้งหรือไม่ ปัจจุบันคุณมีเงิน "

FIRST_PROMPT = TextSendMessage(
    text="ok",
    quick_reply=QuickReply(items=[
        QuickReplyButton(action=MessageAction(label="ใช่", text="ใช่")),
        QuickReplyButton(action=MessageAction(label="ไม่", text="ไม่")),
    ]))


def isdigit(text):
    return re.match("^\d+(\.\d+)?$", text) is not None


class User:
    def __init__(self, user_id):
        self.user_id = user_id
        self.reset()

    def reset(self):
        self.first = None
        self.ask = None
示例#30
0
#textQuickReplyButton_dem = QuickReplyButton(
#    action=URIAction(
#        label="好,我要離開",
#        uri="https://www.thenewslens.com/article/127718"
#    )
#)

# In[44]:
'''

以QuickReply封裝該些QuickReply Button

'''
## 設計QuickReplyButton的List
#上個廁所
quickReplyList_toilet = QuickReply(
    items=[textQuickReplyButton_toilet, textQuickReplyButton_NO])
#坐上椅子
quickReplyList_chair = QuickReply(
    items=[textQuickReplyButton_chair, textQuickReplyButton_NO])
#打開洗衣機
quickReplyList_wash_1 = QuickReply(
    items=[textQuickReplyButton_wash_1, textQuickReplyButton_NO])
quickReplyList_wash_2 = QuickReply(
    items=[textQuickReplyButton_wash_2, textQuickReplyButton_NO])

#洗手台上有面鏡子
quickReplyList_mirror = QuickReply(
    items=[textQuickReplyButton_mirror, textQuickReplyButton_NO])

#發現一顆大冰塊
quickReplyList_ice = QuickReply(