Beispiel #1
0
def detect_json_array_to_new_message_array(fn):    
    with open(fn, encoding='utf8') as f:
        jsonArray = json.load(f)
    
    returnArray = []
    for jsonObject in jsonArray:
        message_type = jsonObject.get('type')
        if message_type == 'text':
            returnArray.append(TextSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'imagemap':
            returnArray.append(ImagemapSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'template':
            returnArray.append(TemplateSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'image':
            returnArray.append(ImageSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'sticker':
            returnArray.append(StickerSendMessage.new_from_json_dict(jsonObject))  
        elif message_type == 'audio':
            returnArray.append(AudioSendMessage.new_from_json_dict(jsonObject))  
        elif message_type == 'location':
            returnArray.append(LocationSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'flex':
            returnArray.append(FlexSendMessage.new_from_json_dict(jsonObject))    

    return returnArray
Beispiel #2
0
def text_carousel_reply(event, text_message, item_list):
    if len(item_list) != 0:
        response = [{
            "type": "text",
            "text": text_message
        }, {
            "type": "template",
            "altText": "this is a carousel template",
            "template": {
                "type": "carousel",
                "actions": [],
                "columns": item_list
            }
        }]
    else:
        response = [{"type": "text", "text": text_message}]

    result_message_array = []

    for res in response:
        message_type = res.get('type')

        if message_type == 'text':
            result_message_array.append(
                TextSendMessage.new_from_json_dict(res))
        elif message_type == 'template':
            result_message_array.append(
                TemplateSendMessage.new_from_json_dict(res))

    line_bot_api.reply_message(event.reply_token, result_message_array)
Beispiel #3
0
def detect_json_array_to_new_message_array(fileName):
    ''' message_type 判斷器

        讀取指定的 json檔,解析成不同格式的 SendMessage
    '''
    with open(fileName, 'r', encoding='utf8') as f:
        jsonArray = json.load(f)
    
    newmessage_Array = []
    for jsonObject in jsonArray:
        message_type = jsonObject.get('type')
        
        if message_type == 'text':
            newmessage_Array.append(TextSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'sticker':
            newmessage_Array.append(StickerSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'image':
            newmessage_Array.append(ImageSendMessage.new_from_json_dict(jsonObject))  
        elif message_type == 'video':
            newmessage_Array.append(VideoSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'audio':
            newmessage_Array.append(AudioSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'location':
            newmessage_Array.append(LocationSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'imagemap':
            newmessage_Array.append(ImagemapSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'template':
            newmessage_Array.append(TemplateSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'flex':
            newmessage_Array.append(FlexSendMessage.new_from_json_dict(jsonObject))        

    return newmessage_Array
Beispiel #4
0
def detect_json_array_to_new_message_array(fileName):
    # 開啟檔案,轉成json
    with open(fileName, 'r', encoding="utf-8") as f:
        jsonArray = json.load(f)

    # 解析json
    returnArray = []
    for jsonObject in jsonArray:

        # 讀取其用來判斷的元件
        message_type = jsonObject.get('type')

        # 轉換
        if message_type == 'text':
            returnArray.append(TextSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'imagemap':
            returnArray.append(ImagemapSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'template':
            returnArray.append(TemplateSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'image':
            returnArray.append(ImageSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'sticker':
            returnArray.append(StickerSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'audio':
            returnArray.append(AudioSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'location':
            returnArray.append(LocationSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'flex':
            returnArray.append(FlexSendMessage.new_from_json_dict(jsonObject))
        elif message_type == 'video':
            returnArray.append(FlexSendMessage.new_from_json_dict(jsonObject))

            # 回傳
    return returnArray
Beispiel #5
0
def process_follow_event(event):
    # 綁定(圖文選單)
    linkRichMenuId = open(rich_menu_id_title, 'r').read()
    line_bot_api.link_rich_menu_to_user(event.source.user_id, linkRichMenuId)

    # 讀取並轉換
    jsonArray = json.load(open("data/message/001/reply.json",
                               encoding="utf-8"))
    text_message = TextSendMessage.new_from_json_dict(jsonArray)

    # 消息發送
    line_bot_api.reply_message(event.reply_token, [text_message])
Beispiel #6
0
def getQuestionnaireReply(reToken, fileName):
    # 開啟檔案,轉成json
    with open(fileName, "r", encoding="utf-8") as fi:
        #print(fi.read())
        #print(type(fi.read()))
        jsonStr = fi.read()
        jsonStr = jsonStr.replace("{url}", "{0}?linebottoken={1}".format(ques_url, reToken))
        ##jsonStr = fi.read().replace("{url}", "{0}?linebottoken={1}".format(ques_url, reToken))
        print("jsonStr:", jsonStr)
        jsonArray = json.loads(jsonStr)

    # 解析json
    returnArray = []
    for jsonObject in jsonArray:
        returnArray.append(TextSendMessage.new_from_json_dict(jsonObject))

    return returnArray
Beispiel #7
0
def process_follow_event(event):

    # 將菜單綁定在用戶身上
    linkRichMenuId = secretFileContentJson.get("rich_menu_id")
    line_bot_api.link_rich_menu_to_user(event.source.user_id, linkRichMenuId)

    # 轉換回覆消息
    response = [{
        "type":
        "text",
        "text":
        "Welcome to The Diamond Store! Please select your preferred service from the menu below."
    }]

    result_message_array = []
    result_message_array.append(TextSendMessage.new_from_json_dict(
        response[0]))

    # 消息發送
    line_bot_api.reply_message(event.reply_token, result_message_array)
Beispiel #8
0
def process_text_message(event):
    keywords = event.message.text

    query = {"query": {"match": {"product_info": {"query": keywords}}}}
    items = search(es, "products", query)

    item_list = []
    for item in items:
        item_list.append(item['_source']['info_for_line'])

    response = [{
        "type": "text",
        "text": "Here are the results for {}".format(keywords)
    }, {
        "type": "template",
        "altText": "this is a carousel template",
        "template": {
            "type": "carousel",
            "actions": [],
            "columns": item_list
        }
    }]

    result_message_array = []

    for res in response:

        message_type = res.get('type')

        if message_type == 'text':
            result_message_array.append(
                TextSendMessage.new_from_json_dict(res))

        elif message_type == 'template':
            result_message_array.append(
                TemplateSendMessage.new_from_json_dict(res))

    line_bot_api.reply_message(event.reply_token, result_message_array)
Beispiel #9
0
def process_follow_event(event):

    # 讀取並轉換
    result_message_array = []
    replyJsonPath = "素材/關注/reply.json"
    result_message_array = detect_json_array_to_new_message_array(
        replyJsonPath)

    # 呼叫個人用戶名,與用戶第一次接觸打招呼
    user_profile = line_bot_api.get_profile(event.source.user_id)
    hello = {
        "type": "text",
        "text": "您好!" + str(user_profile.display_name) + "\n歡迎您使用「RunningAI」"
    }
    result_message_array.insert(0, TextSendMessage.new_from_json_dict(hello))

    #綁定 rich_menu
    linkRichMenuId = open("素材/rich_menu_4/rich_menu_id", 'r').read()
    line_bot_api.link_rich_menu_to_user(event.source.user_id, linkRichMenuId)

    # 消息發送
    line_bot_api.reply_message(event.reply_token, result_message_array)

    # Redis端設定
    # 1.Redis防火牆關閉
    # 2.Redis Server啟動時後面帶上 --protected-mode no
    # src/redis-server  --protected-mode no

    # 串接Redis需安裝套件
    # !pip install redis
    import redis
    #r = redis.Redis(host='192.168.48.132', port=6379)
    r = redis.Redis(host='10.120.28.22', port=6379)
    myfile = json.dumps(vars(user_profile), sort_keys=True)
    print(myfile)
    print(type(myfile))
    r.set('messi', myfile)
Beispiel #10
0
def process_postback_event(event):
    model_dict = {'classify_14tree': '影像辨識:14種樹', 'classify_8leaf': '影像辨識:8種葉',
                  'objdetect_14tree': '物件偵測:14種樹', 'objdetect_8leaf': '物件偵測:8種葉',
                  'classify_bauya': '影像辨識:羊蹄甲3種葉'}
    
    db.increase(event.source.user_id, 'm')
    q = parse_qs(event.postback.data)
    if 'model' in q:
        m = q.get('model')[0]
        
        if m in model_dict:
            cameraQuickRB = QuickReplyButton(action=CameraAction(label="拍照"))
            cameraRollQRB = QuickReplyButton(action=CameraRollAction(label="讀檔"))
            quickReplyList = QuickReply(items = [cameraRollQRB, cameraQuickRB])
            fn = '<<fn_' + m + '>>'
            quickReplyTextSendMessage = get_textmessage_reply(cfg['reply_path'], fn, event.source.user_id, db)
            quickReplyTextSendMessage[0].quick_reply = quickReplyList
            line_bot_api.reply_message(event.reply_token, quickReplyTextSendMessage)
            db.markModel(event.source.user_id, m)
    
    elif 'page' in q:
        page = q.get('page')[0]
        msg, key = get_textmessage_reply(cfg['reply_path'], page, event.source.user_id, db, True)
        msg = msg[0] # get_textmessage_reply() returned list
        
        if 'category' in q:
            cat = q.get('category')[0]
            if cat == 'trees': # page=<<AS>>&category=trees
                items = [QuickReplyButton(action=PostbackAction(label='<<', data='page=<<trees>>'))]
                k = trees_dict[key]
                if k > 0:
                    p = f'page=<<{trees[k-1]}>>&category=trees'
                    items.append(QuickReplyButton(action=PostbackAction(label='<', data=p)))
                if k < len(trees)-1:
                    f = f'page=<<{trees[k+1]}>>&category=trees'
                    items.append(QuickReplyButton(action=PostbackAction(label='>', data=f)))
                msg.quickReply = QuickReply(items=items)
                
            elif cat == 'leaves':
                pass
        
        line_bot_api.reply_message(event.reply_token, msg)
        
    elif 'action' in q:
        a = q.get('action')[0]
        msg = None
        
        if a == 'whoami':
            t = q.get('target')[0] if 'target' in q else event.source.user_id
            u = db.getUser(t)
            msg = FlexSendMessage.new_from_json_dict(create_whoami(u))
            if 'callback' in q:
                cb = (q.get('callback')[0]).replace('^', '&')
                msg.quickReply = QuickReply(items=[QuickReplyButton(action=PostbackAction(label='<', data=cb))])
        elif a == 'show_email':
            msg = TextSendMessage.new_from_json_dict(
                {'type': 'text', 'text': 'Enos Chou, feel free to contact me\[email protected]'})
        elif a == 'count_usage':
            criterion = 1
            user_amt, user_today, usage_amt = db.countUsage(event.source.user_id, criterion=criterion)
            if user_amt is 0:
                msg = TextSendMessage.new_from_json_dict({"type": "text", "text": f'你還不是 {admin[criterion]}'})
            else:
                msg = TextSendMessage.new_from_json_dict(
                    {'type': 'text',
                     'text': f'用戶總數: {user_amt} 人\n今日新增: {user_today} 人\n今日使用: {usage_amt} 人'})
        elif a == 'list':
            AMOUNT = cfg['show_maxuser']
            alt = {'last':'註', 'visit':'訪', 'usage':'量'}
            criterion = 1
            mode = q.get('mode')[0]
            start = (int)(q.get('start')[0]) # must be cast to int, or it would be str
            users = db.getUsers(event.source.user_id, mode, start, AMOUNT, criterion)
            u_len = len(users)
            msg = FlexSendMessage.new_from_json_dict(create_list(users, alt[mode], start, u_len, event.postback.data))
            items = []
            if u_len > 0:
                if start > 0:
                    x = start - AMOUNT # cehck previus button
                    p = f'action=list&mode={mode}&start={x if x > 0 else 0}'
                    items.append(QuickReplyButton(action=PostbackAction(label='<', data=p)))
                    if x > 0: # check first page button
                        f = f'action=list&mode={mode}&start=0'
                        items.insert(0, QuickReplyButton(action=PostbackAction(label='<<', data=f)))
                if u_len == AMOUNT and (start+u_len < users[-1][-1]): # check next button
                    n = f'action=list&mode={mode}&start={start+u_len}'
                    items.append(QuickReplyButton(action=PostbackAction(label='>', data=n)))
                    nn = f'action=list&mode={mode}&start={AMOUNT*((users[-1][-1]-1)//AMOUNT)}'
                    items.append(QuickReplyButton(action=PostbackAction(label='>>', data=nn)))
                    
            for a in alt:
                if mode != a:
                    rb = QuickReplyButton(action=PostbackAction(label=alt[a], data=f'action=list&mode={a}&start=0'))
                    items.append(rb)
            msg.quickReply = QuickReply(items=items)
        elif a == 'reload':
            criterion = 2
            u = db.getUser(event.source.user_id) # user_id, display_name, picture_url, admin
            if u[3] >= criterion:
                if 'scope' in q:
                    s = q.get('scope')[0]
                    if s == 'db':
                        r = db.reload(event.source.user_id,
                                      cfg['mysql_ip'], cfg['mysql_db'], cfg['mysql_id'], cfg['mysql_pwd'], criterion)
                        desc = ['失敗!', '完成']
                        msg = TextSendMessage.new_from_json_dict({"type": "text", "text": f'DB重連{desc[r]}'})
                    elif s == 'profile':
                        pp = []
                        uids = db.getUids()
                        for uid in uids:
                            try:
                                p = line_bot_api.get_profile(uid) # sometimes failed due to UID not found by A
                                pp.append([p.display_name, p.picture_url, p.user_id])
                            except Exception as e1:
                                print(e1)
                                print(f'{uid} passed due to exception!')
                        db.updateUsers(pp)
                        msg = TextSendMessage.new_from_json_dict({"type": "text", "text": '更新用戶資料完畢'})
                    elif s == 'richmenu':
                        uids = db.getUids()
                        line_bot_api.link_rich_menu_to_users(uids, cfg['richmenu_id'])
                        msg = TextSendMessage.new_from_json_dict({"type": "text", "text": '重置圖文選單完畢'})
                else:
                    msg = get_textmessage_reply(cfg['reply_path'], '<<background>>', event.source.user_id, db)[0]
                    rb1 = QuickReplyButton(action=PostbackAction(label='重連DB', data='action=reload&scope=db'))
                    rb2 = QuickReplyButton(action=PostbackAction(label='更新用戶', data='action=reload&scope=profile'))
                    rb3 = QuickReplyButton(action=PostbackAction(label='重置選單', data='action=reload&scope=richmenu'))
                    msg.quickReply = QuickReply(items=[rb1, rb2, rb3])
            else:
                msg = TextSendMessage.new_from_json_dict({"type": "text", "text": f'你還不是 {admin[criterion]}'})
            
        line_bot_api.reply_message(event.reply_token, msg)
Beispiel #11
0
def process_postback_event(event):

    query_string_dict = parse_qs(event.postback.data)
    print(query_string_dict)

    # (1)商品關鍵字搜尋
    if ('button' in query_string_dict) and (query_string_dict.get('button')[0]
                                            == 'search'):
        response = [{
            "type":
            "text",
            "text":
            "Let’s find something for you! What’s on your list today?"
        }]

        result_message_array = [
            TextSendMessage.new_from_json_dict(response[0])
        ]
        line_bot_api.reply_message(event.reply_token, result_message_array)

    # (2)使用者專屬優惠
    elif ('button'
          in query_string_dict) and (query_string_dict.get('button')[0]
                                     == 'coupon'):

        #user_profile = line_bot_api.get_profile(event.source.user_id)
        #user_profile_dict = vars(user_profile)
        #user_id = user_profile_dict.get('user_id')

        query_id = model_ALS_rank[model_ALS_rank['user_id'] ==
                                  99522].loc[0:].iloc[0].to_list()
        text_message = "20% off items only for you! Use your ‘Diamond is the BEST -20’ coupon when checking out to get your discount 😚"

        item_list = general_carousel_query(es, query_id)
        text_carousel_reply(event, text_message, item_list)

    # (3)熱銷商品
    elif ('button'
          in query_string_dict) and (query_string_dict.get('button')[0]
                                     == 'hot'):

        #query = {"aggs": {"product": {"terms": { "field": "product_id" }}}}
        #result = es.search(index='orders', body=query)["aggregations"]['product']['buckets']
        #hot_query_id = [item.get('key') for item in result]

        query_id = hot_query_id
        text_message = "We’ve listed the most popular products for you, please take a look!"

        item_list = general_carousel_query(es, query_id)
        text_carousel_reply(event, text_message, item_list)

    # (4)Shopping List
    elif ('button'
          in query_string_dict) and (query_string_dict.get('button')[0]
                                     == 'list'):
        user_profile = line_bot_api.get_profile(event.source.user_id)
        user_profile_dict = vars(user_profile)

        user_id = user_profile_dict.get('user_id')

        query = {
            "size": 100,
            "query": {
                "match": {
                    "user_id": {
                        "query": user_id
                    }
                }
            }
        }
        items = search(es, 'shopping_list', query)
        item_list = [item['_source']['info_for_line'] for item in items]

        if len(item_list) != 0:
            text_message = "My Shopping List : "
        else:
            text_message = "Add Something to the Shopping List!"
        text_carousel_reply(event, text_message, item_list)

    # (5)相關商品推薦(You might also like)
    elif 'id' in query_string_dict:
        product_id = int(query_string_dict.get('id')[0])

        # item-based
        if (product_id in itembased_product_list) == True:
            query_id = model_itembased_rank[model_itembased_rank['product_id']
                                            == product_id].iloc[0,
                                                                1:].to_list()
            print(query_id)
            print("item-based")
            if 0 in query_id:
                query_id = [product for product in query_id if (product != 0)
                            ] + list(avg_rating)  # ALS preditons average
                print("item-based+ALS")

        # word2vec
        else:
            query_id = [
                int(product[0])
                for product in model.wv.most_similar(str(product_id))
            ]
            print('word2vec')

        text_message = "You may also like the products below! Check it out!"
        item_list = general_carousel_query(es, query_id)
        text_carousel_reply(event, text_message, item_list)

    # (6)Add to List
    elif 'add' in query_string_dict:

        user_profile = line_bot_api.get_profile(event.source.user_id)
        user_profile_dict = vars(user_profile)
        user_id = user_profile_dict.get('user_id')

        product_id = int(query_string_dict.get('add')[0])
        product_name = str(query_string_dict.get('name')[0])

        query = {
            "query": {
                "bool": {
                    "should": [{
                        "match": {
                            "product_id": {
                                "query": product_id
                            }
                        }
                    }]
                }
            }
        }

        result = search(es, 'products', query)[0]['_source']['info_for_line']

        info_for_line = {
            "thumbnailImageUrl":
            result['thumbnailImageUrl'],
            "title":
            product_name,
            "text":
            result['text'],
            "actions": [{
                "type": "uri",
                "label": "More Info",
                "uri": result['actions'][0]['uri']
            }, {
                "type": "postback",
                "label": "You May Also Like",
                "data": "id=" + str(product_id)
            }, {
                "type": "postback",
                "label": "Remove from List",
                "data": "remove=" + str(product_id)
            }]
        }

        add = {
            "user_id": user_id,
            "product_id": product_id,
            "product_name": product_name,
            "info_for_line": info_for_line
        }
        insert_doc(es, "shopping_list", add)

        response = [{
            "type": "text",
            "text": "'{}' added to your list ".format(product_name)
        }]

        result_message_array = [
            TextSendMessage.new_from_json_dict(response[0])
        ]
        line_bot_api.reply_message(event.reply_token, result_message_array)

    # (7) 移除收藏
    elif 'remove' in query_string_dict:
        user_profile = line_bot_api.get_profile(event.source.user_id)
        user_profile_dict = vars(user_profile)
        user_id = user_profile_dict.get('user_id')

        product_id = query_string_dict.get('remove')[0]

        # 刪除清單中該筆商品資料
        query = {
            "size": 1,
            "query": {
                "bool": {
                    "should": [{
                        "match": {
                            "product_id": {
                                "query": product_id
                            }
                        }
                    }, {
                        "match": {
                            "user_id": {
                                "query": user_id
                            }
                        }
                    }]
                }
            }
        }

        delete_id = search(es, 'shopping_list', query)[0]['_id']
        es.delete(index='shopping_list', id=delete_id)

        time.sleep(1)

        # 回覆使用者更新後的Shopping List
        query = {
            "size": 100,
            "query": {
                "match": {
                    "user_id": {
                        "query": user_id
                    }
                }
            }
        }
        items = search(es, 'shopping_list', query)
        item_list = [item['_source']['info_for_line'] for item in items]

        if len(item_list) != 0:
            text_message = "My New Shopping List : "
        else:
            text_message = "Add Something to the Shopping List!"
        text_carousel_reply(event, text_message, item_list)