Exemple #1
0
def handler_postback(event):
    # 把postback裡面的資料轉成字典
    data = dict(parse_qsl(event.postback.data))
    # 再取出action裡面的值
    action = data.get('action')
    # 從event裡面取得用戶id
    user_id = event.source.user_id
    # 從event裡面取得reply_token
    reply_token = event.reply_token
    # 建立一個購物車物件
    cart = Cart(user_id=user_id)
    # 從資料庫取得送出postback的用戶資料
    query = User.query.filter_by(id=user_id).first()
    print(event.postback.data)
    # 點擊加入會員
    if event.postback.data in ['join_us', '加入會員']:
        # 資料庫該使用者狀態改為註冊中
        # Updata data
        print('註冊中')
        query.is_signup = True
        db_session.commit()
        line_bot_api.link_rich_menu_to_user(user_id, richmenu_list.RichMenu_ID.richmenu_02)
        line_bot_api.push_message(user_id, AllMessage.sign_cellphone())
    # 點擊取消輸入之類的
    elif event.postback.data in ['exit']:
        query.is_signup = False
        query.edit_user_name = False
        query.edit_home_address = False
        query.edit_company_address = False
        db_session.commit()
        if not query.is_member:
            line_bot_api.link_rich_menu_to_user(user_id, richmenu_list.RichMenu_ID.richmenu_01)
        line_bot_api.push_message(user_id, TextSendMessage(text='好的,歡迎您再來找我聊聊天喔!'))
    # 點擊會員中心
    elif event.postback.data in ['會員中心']:
        line_bot_api.reply_message(reply_token, TextSendMessage(text='這是專屬於你的會員中心', sender=Sender(
            name='會員中心管理員結衣',
            icon_url='https://i.imgur.com/S7SHmup.png'
        )))
        line_bot_api.push_message(user_id, AllMessage.member_center(query))
    # 觸發點餐相關事件
    elif event.postback.data in ['當日外帶', 'add', '點餐']:
        # 先跳出選擇內用外帶
        line_bot_api.reply_message(reply_token, TemplateSendMessage(alt_text="請問您要內用還是外帶呢?",
                                                                    sender=Sender(
                                                                        name='服務員結衣',
                                                                        icon_url='https://i.imgur.com/S7SHmup.png'
                                                                    ),
                                                                    template=ConfirmTemplate(
                                                                        text="請問您要內用還是外帶呢?",
                                                                        actions=[
                                                                            PostbackAction(
                                                                                label="內用",
                                                                                text="內用",
                                                                                data="here"
                                                                            ),
                                                                            PostbackAction(
                                                                                label="外帶",
                                                                                text="外帶",
                                                                                data="out"
                                                                            )
                                                                        ]
                                                                    )))
    # 外帶事件
    elif event.postback.data in ['out']:
        line_bot_api.reply_message(reply_token, Products.list_all())
    # 內用事件
    elif event.postback.data in ['here']:
        line_bot_api.reply_message(reply_token, TemplateSendMessage(alt_text="請掃描桌上的QRCODE",
                                                                    sender=Sender(
                                                                        name='服務員結衣',
                                                                        icon_url='https://i.imgur.com/S7SHmup.png'
                                                                    ),
                                                                    template=ButtonsTemplate(
                                                                        text='請掃描桌上的QRCode點餐',
                                                                        actions=[
                                                                            URIAction(
                                                                                type='uri',
                                                                                label='點我掃描',
                                                                                uri="https://liff.line.me/1654280234-Wabazm3B"
                                                                            )
                                                                        ]
                                                                    )))
    # 觸發確認訂單事件
    elif event.postback.data in ['待補', '確認訂單']:
        if cart.bucket():
            line_bot_api.reply_message(reply_token, cart.display())
        else:
            line_bot_api.reply_message(reply_token, TextSendMessage(text='你的購物車目前沒東西喔'))
    # 觸發清空購物車事件
    elif event.postback.data in ['Empty Cart']:
        cart.reset()
        line_bot_api.reply_message(reply_token, TextSendMessage(text="你的購物車已經被清空了"))
    # 如果action為check則執行結帳動作
    elif action == 'checkout':
        if not cart.bucket():
            line_bot_api.reply_message(reply_token,
                                       TextSendMessage(text='你的購物車是空的'))
            return 'OK'

        # 透過uuid來建立訂單id,它可以幫我們建立一個獨一無二的值
        order_id = uuid.uuid4().hex
        # 訂單總金額
        total = 0
        # 訂單內容物的陣列
        items = []

        for product_name, num in cart.bucket().items():
            product = db_session.query(Products).filter(Products.name.ilike(product_name)).first()

            print(product.id)
            item = Items(product_id=product.id,
                         product_name=product.name,
                         product_price=product.price,
                         order_id=order_id,
                         quantity=num)

            items.append(item)

            total += product.price * int(num)

        cart.reset()

        line_pay = LinePay()
        # 傳送這些資訊過去他會回我們一個json
        # 自己試試看把info印出來或是用postman看看裡面的結構
        info = line_pay.pay(product_name='OrderBot 點吧',
                            amount=total,
                            order_id=order_id,
                            product_image_url=Config.STORE_IMAGE_URL)

        # 從info裡面擷取付款連結跟transactionid
        pay_web_url = info['paymentUrl']['web']
        transaction_id = info['transactionId']

        # 產生訂單
        order = Orders(id=order_id,
                       transaction_id=transaction_id,
                       is_pay=False,
                       amount=total,
                       user_id=user_id)

        db_session.add(order)

        for item in items:
            db_session.add(item)

        db_session.commit()

        message = TemplateSendMessage(
            alt_text='差一點點就完成訂購囉~',
            template=ButtonsTemplate(
                text='差一點點就完成訂購囉~',
                actions=[
                    URIAction(label='Pay NT${}'.format(order.amount),
                              uri='{liff_url}?redirect_url={url}'.format(
                                  liff_url=Config.LIFF_URL,
                                  url=pay_web_url))
                ]))
        line_bot_api.reply_message(reply_token, message)

    # 訂單管理
    elif event.postback.data in ['訂單管理']:
        line_bot_api.reply_message(reply_token, Booking.list_all_user(user_id))

    # 取消訂單
    elif '取消訂位' in event.postback.data:
        line_bot_api.reply_message(reply_token, TextSendMessage(text="您的訂單已取消",
                                                                sender=Sender(
                                                                    name='會員中心管理員結衣',
                                                                    icon_url='https://i.imgur.com/S7SHmup.png'
                                                                )))
        book_id = str(event.postback.data)[4:]
        db_session.query(Booking).filter_by(id=book_id).first().is_confirm = -2
        db_session.commit()

    return 'OK'
Exemple #2
0
def handle_message(event):

    get_or_create_user(event.source.user_id)

    message_text = str(event.message.text).lower()

    cart = Cart(user_id=event.source.user_id)

    message = None

    if message_text in ["what is your story?", "story"]:
        message = [
            ImageSendMessage(
                original_content_url='https://i.imgur.com/DKzbk3l.jpg',
                preview_image_url='https://i.imgur.com/DKzbk3l.jpg'),
            StickerSendMessage(package_id='11537', sticker_id='52002734')
        ]

    elif message_text in ['i am ready to order.', 'add']:
        message = Products.list_all()

    elif "i'd like to have" in message_text:

        product_name = message_text.split(',')[0]
        num_item = message_text.rsplit(':')[1]

        product = db_session.query(Products).filter(
            Products.name.ilike(product_name)).first()

        if product:

            cart.add(product=product_name, num=num_item)

            confirm_template = ConfirmTemplate(
                text='Sure, {} {}, anything else?'.format(
                    num_item, product_name),
                actions=[
                    MessageAction(label='Add', text='add'),
                    MessageAction(label="That's it", text="That's it")
                ])

            message = TemplateSendMessage(alt_text='anything else?',
                                          template=confirm_template)

        else:
            message = TextSendMessage(
                text="Sorry, We don't have {}.".format(product_name))

        print(cart.bucket())

    elif message_text in ['my cart', 'cart', "that's it"]:

        if cart.bucket():
            message = cart.display()
        else:
            message = TextSendMessage(text='Your cart is empty now.')

    elif message_text == 'empty cart':

        cart.reset()

        message = TextSendMessage(text='Your cart is empty now.')

    if message:
        line_bot_api.reply_message(event.reply_token, message)