Exemple #1
0
def cmd_start(message):
    state = get_state(message.chat.id)
    # IF PROMO AND SALES
    if state == config.States.S_PROMOSALES.value:
        set_state(message.chat.id, config.States.S_PROMOSALES.value)
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    # IF CATEGORIES
    elif state == config.States.S_CATEGORIES_PROMO.value or state == config.States.S_CATEGORIES_SALES.value:
        bot.send_message(message.chat.id,
                         config.CATEGORY_ANSWER,
                         reply_markup=markup_CATEGORY)
    #IF START
    else:
        bot.send_message(message.chat.id,
                         "При возникновении проблем с ботом пропишите /start")
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
        set_state(message.chat.id, config.States.S_PROMOSALES.value)
    msg = Message(api_key=config.API_KEY,
                  platform=config.PLATFORM,
                  version=config.VERSION,
                  user_id=str(message.chat.id),
                  message=message.text,
                  intent="/start")
    msg.send()
Exemple #2
0
def TRChatBase(chat_id, message_text, intent):
    msg = Message(
        api_key=CHAT_BASE_TOKEN,
        platform="Telegram",
        version="1.3",
        user_id=chat_id,
        message=message_text,
        intent=intent,
    )
    msg.send()
Exemple #3
0
def user_choosing_sale_section(message):
    if message.text == config.TECH_BUTTON:
        bot.send_message(message.chat.id,
                         config.get_text(config.SRC_SALE_TECH),
                         parse_mode='markdown')
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    elif message.text == config.CLOTH_BUTTON:
        bot.send_message(message.chat.id,
                         config.get_text(config.SRC_SALE_CLOTH),
                         parse_mode='markdown')
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    elif message.text == config.DOMESTIC_BUTTON:
        bot.send_message(message.chat.id,
                         config.get_text(config.SRC_SALE_DOMESTIC),
                         parse_mode='markdown')
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    elif message.text == config.CHILD_BUTTON:
        bot.send_message(message.chat.id,
                         config.get_text(config.SRC_SALE_CHILD),
                         parse_mode='markdown')
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    elif message.text == config.FOOD_BUTTON:
        bot.send_message(message.chat.id,
                         config.get_text(config.SRC_SALE_FOOD),
                         parse_mode='markdown')
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    elif message.text == config.BACK_BUTTON:
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    elif message.text == config.OTHER_BUTTON:
        bot.send_message(message.chat.id,
                         config.get_text(config.SRC_SALE_OTHER),
                         parse_mode='markdown')
        bot.send_message(message.chat.id,
                         config.MAIN_ANSWER,
                         reply_markup=markup_MAIN)
    set_state(message.chat.id, config.States.S_PROMOSALES.value)
    msg = Message(api_key=config.API_KEY,
                  platform=config.PLATFORM,
                  version=config.VERSION,
                  user_id=str(message.chat.id),
                  message=message.text)
    msg.send()
Exemple #4
0
def handle_message(update, context):

    if update.message:

        db_limits = TinyDB(db_users_limits_path)

        username = update.message.from_user.name
        chat_id = update.message.chat.id
        profile_url = update.message.text

        db_limits.insert({"user": username})

        count_messages = len(db_limits.search(query.user == username))

        if count_messages <= messages_limit:
            context.bot.send_message(
                chat_id=chat_id,
                text=messages["loading"].format(count_messages,
                                                messages_limit),
            )
            result, traceback = get_top_posts(
                L,
                context,
                chat_id,
                messages,
                profile_url,
                top_n=config["top_n"],
                lookback_posts=config["lookback_posts"],
            )
        else:
            result, traceback = send_limit_message(context, chat_id, messages)

        # Print to pythonanywhere log
        print(
            username,
            time.ctime(int(time.time())),
            profile_url,
            result,
            traceback,
            sep="    ",
            flush=True,
        )

        # Send data to chatbase
        msg = Message(api_key=config["chatbase_token"],
                      user_id=username,
                      message=profile_url)
        msg.send()

        # Add user and their chat id to database if not exists
        user_exist = db_users.search(query.user == username)
        if len(user_exist) == 0:
            db_users.insert({"user": username, "chat_id": chat_id})
def send_statistic(token, uid, message, intent, user_type=None):
    try:
        if user_type is not None:
            msg = Message(api_key=token,
                          platform="tg",
                          version="0.1",
                          user_id=uid,
                          message=message,
                          type=user_type)
        else:
            if intent != 'unknown':
                msg = Message(api_key=token,
                              platform="tg",
                              version="0.1",
                              user_id=uid,
                              message=message,
                              intent=intent)
            else:
                msg = Message(api_key=token,
                              platform="tg",
                              version="0.1",
                              user_id=uid,
                              message=message,
                              intent=intent,
                              not_handled=True)

        return str(msg.send())
    except:
        pass
def BujukkuChatBase(chat_id, message_text, intent):
    msg = Message(api_key=Resources.CHAT_BASE_TOKEN,
                  platform="Telegram",
                  version="1.3",
                  user_id=chat_id,
                  message=message_text,
                  intent=intent)
    resp = msg.send()
Exemple #7
0
def send_metrik(pfm, user_id, msg, step, handl):
    msg = Message(api_key=metrik_key,
                  platform=pfm,
                  user_id=user_id,
                  message=msg,
                  intent=pfm + "_" + step,
                  not_handled=handl)
    resp = msg.send()
def TRChatBase(chat_id, message_text, intent):
    msg = Message(api_key=Config.CBTOKEN,
                  platform="Telegram",
                  version="1.3",
                  user_id=chat_id,
                  message=message_text,
                  intent=intent)
    resp = msg.send()
Exemple #9
0
def handeled(user_response):
    msg = MsgChat(api_key= "6f6aa25c-e467-49f7-9799-67efb413b829",
            type= "user",
            platform= "web",
            message= user_response,
            version= "1.0",
            user_id= "user-200"
    )
    resp = msg.send()
    print(resp)
Exemple #10
0
def handle_postback(event):

    profile = line_bot_api.get_profile(event.source.user_id)

    #判別空汙等級
    if float(event.postback.data) <= 11:
        pm_level = '第一等級'
        pm_advice = '(一般民眾)正常戶外活動。\n(敏感性族群)正常戶外活動。'
    elif 12 <= float(event.postback.data) <= 23:
        pm_level = '第二等級'
        pm_advice = '(一般民眾)正常戶外活動。\n(敏感性族群)正常戶外活動。'
    elif 24 <= float(event.postback.data) <= 35:
        pm_level = '第三等級'
        pm_advice = '(一般民眾)正常戶外活動。\n(敏感性族群)正常戶外活動。'
    elif 36 <= float(event.postback.data) <= 41:
        pm_level = '第四等級'
        pm_advice = '(一般民眾)正常戶外活動。\n(敏感性族群)有心臟、呼吸道及心血管疾病的成人與孩童感受到癥狀時,應考慮減少體力消耗,特別是減少戶外活動。'
    elif 42 <= float(event.postback.data) <= 47:
        pm_level = '第五等級'
        pm_advice = '(一般民眾)正常戶外活動。\n(敏感性族群)有心臟、呼吸道及心血管疾病的成人與孩童感受到癥狀時,應考慮減少體力消耗,特別是減少戶外活動。'
    elif 48 <= float(event.postback.data) <= 53:
        pm_level = '第六等級'
        pm_advice = '(一般民眾)正常戶外活動。\n(敏感性族群)有心臟、呼吸道及心血管疾病的成人與孩童感受到癥狀時,應考慮減少體力消耗,特別是減少戶外活動。'
    elif 54 <= float(event.postback.data) <= 58:
        pm_level = '第七等級'
        pm_advice = '(一般民眾)任何人如果有不適,如眼痛,咳嗽或喉嚨痛等,應該考慮減少戶外活動。\n(敏感性族群)1.有心臟、呼吸道及心血管疾病的成人與孩童,應減少體力消耗,特別是減少戶外活動。\n2.老年人應減少體力消耗。\n3.具有氣喘的人可能需增加使用吸入劑的頻率。'
    elif 59 <= float(event.postback.data) <= 64:
        pm_level = '第八等級'
        pm_advice = '(一般民眾)任何人如果有不適,如眼痛,咳嗽或喉嚨痛等,應該考慮減少戶外活動。\n(敏感性族群)1.有心臟、呼吸道及心血管疾病的成人與孩童,應減少體力消耗,特別是減少戶外活動。\n2.老年人應減少體力消耗。\n3.具有氣喘的人可能需增加使用吸入劑的頻率。'
    elif 65 <= float(event.postback.data) <= 70:
        pm_level = '第九等級'
        pm_advice = '(一般民眾)任何人如果有不適,如眼痛,咳嗽或喉嚨痛等,應該考慮減少戶外活動。\n(敏感性族群)1.有心臟、呼吸道及心血管疾病的成人與孩童,應減少體力消耗,特別是減少戶外活動。\n2.老年人應減少體力消耗。\n3.具有氣喘的人可能需增加使用吸入劑的頻率。'
    elif float(event.postback.data) >= 71:
        pm_level = '第十等級'
        pm_advice = '(一般民眾)任何人如果有不適,如眼痛,咳嗽或喉嚨痛等,應減少體力消耗,特別是減少戶外活動。\n(敏感性族群)1.有心臟、呼吸道及心血管疾病的成人與孩童,應減少體力消耗,特別是減少戶外活動。\n2.具有氣喘的人可能需增加使用吸入劑的頻率。'

    reply_mes = '◆等級:' + pm_level + '\n◆貼心小建議:' + pm_advice

    output_mes = TextSendMessage(text=reply_mes)

    line_bot_api.reply_message(event.reply_token, output_mes)

    print(profile.display_name)

    msg = Message(
        api_key=chatbase_api_key,
        type="user",
        platform="Line",
        version="1.0",
        user_id=event.source.user_id,
        message="貼心小提醒",
        intent="PostionAdvice",
        not_handled=False,
    )
    resp = msg.send()
Exemple #11
0
def user_choosing_section(message):
    if message.text == config.PROMOCODES_BUTTON:
        set_state(message.chat.id, config.States.S_CATEGORIES_PROMO.value)
        bot.send_message(message.chat.id,
                         config.CATEGORY_ANSWER,
                         reply_markup=markup_CATEGORY)
    elif message.text == config.SALES_BUTTON:
        set_state(message.chat.id, config.States.S_CATEGORIES_SALES.value)
        bot.send_message(message.chat.id,
                         config.CATEGORY_ANSWER,
                         reply_markup=markup_CATEGORY)
    elif message.text == config.CONTACT_BUTTON:
        bot.send_message(message.chat.id,
                         config.get_text(config.SRC_CONTACT),
                         parse_mode='markdown')
    msg = Message(api_key=config.API_KEY,
                  platform=config.PLATFORM,
                  version=config.VERSION,
                  user_id=str(message.chat.id),
                  message=message.text)
    msg.send()
 def test_live_send(self):
     test_api_key = os.environ.get('CB_TEST_API_KEY')
     if test_api_key is None:
         print(
             "Warning: Skipping live integration test without test API key."
         )
         return
     i = Message(api_key=test_api_key,
                 platform="python-lib-test",
                 message="test-message",
                 intent="test-library",
                 version="0.1",
                 user_id="12345")
     resp = i.send()
     self.assertEqual(resp.status_code, 200)
def handle_postback(event):
    
    ## ifLine StroyLine
    if "ifLine" in event.postback.data:
        
        venue = get_venue(event.postback.data)
        status = get_status(venue)
        
        if "guest-ifLine" in event.postback.data:
            
            dist = redisManager.get_userDist(event.source.user_id)
            
            if dist == None:
                
                flora.send_no_dist_message(event.reply_token)
            
                return                
            
            dist_venues = get_currentDist_venues(dist)      
        
            noLine_venues = redisManager.get_noLine_dist_venues(dist_venues)

            flora.send_ifLineResult_message(event.reply_token, venue=venue, status=status, dist=dist, noLine_venues=noLine_venues)
        
        elif "remind-ifLine" in event.postback.data:

            if "no" in event.postback.data:
                flora.send_remind_no_message(event.reply_token)

            else:
                
                chatbase_msg = Message(
                    api_key="api_key",
                    type="user",
                    platform="Line",
                    version="1.0",
                    user_id=event.source.user_id,
                    message="註冊提醒_" + venue,
                    intent="註冊提醒"
                )

                resp =chatbase_msg.send()                 
                
                redisManager.set_ifLine_remind(postback_data = event.postback.data, user_id = event.source.user_id)
                flora.send_remind_yes_message(event.reply_token)
            
        elif "manager-ifLine" in event.postback.data:
            
            if redisManager.get_account(event.source.user_id, venue) != None:
            
                flora.send_correctIfLine_message(event.reply_token, status=status, venue=venue)
                
            else:
                
                flora.send_login_message(event.reply_token, venue=venue, ifRemind=True, action="ifLine")

        elif "correct-ifLine" in event.postback.data:
                
            if "no" in event.postback.data:
                
                flora.send_manager_menu_message(event.reply_token)

            else:

                newStatus = get_ifLine_newStatus(event.postback.data)

                flora.send_ensure_correctIfLine_message(event.reply_token, venue = venue, status=newStatus)

        elif "ensure-ifLine" in event.postback.data:

            if "no" in event.postback.data:

                flora.send_manager_menu_message(event.reply_token)

            # after manager ensure ifLine status, bot will set status and push notification to registed users.
            else:

                newStatus = get_ifLine_newStatus(event.postback.data)
                
                redisManager.set_ifLine_status(venue=venue,status=newStatus)
                
                if isNewStatusOkayForRemind(newStatus=newStatus):

                    push_remind_list = redisManager.get_remind_list(venue=venue)

                    if push_remind_list != None:

                        flora.push_remind_notification(to=push_remind_list, venue=venue, status=newStatus)

                        redisManager.delete_remind_list(venue=venue)

                flora.send_finishCorrect_message(event.reply_token)

    ## currentSituation StroyLine        
    elif "currentSituation" in event.postback.data:
        
        if "guest-currentSituation" in event.postback.data:
            
            venue = get_venue(event.postback.data)
            
            listOfFiles = os.listdir(STATIC_TMP_PATH + "/" + venue)

            listOfFiles.sort(key=lambda x:int(x.split("-")[1]), reverse=True)
            
            listOfFiles = listOfFiles[:3]
            
            pictures = []
            
            for entry in listOfFiles:
                
                picture_path = STATIC_TMP_PATH + "/" + venue + "/" + entry
                
                pic = quote(picture_path)

                timeStamp = entry.split("-")[1][:-3]
                
                struct_time = datetime.datetime.utcfromtimestamp(int(timeStamp))
                
                struct_time = struct_time + datetime.timedelta(hours = 8)
                
                ctime = struct_time.strftime("%Y-%m-%d %H:%M:%S")
                
                picture_dict = { "path": pic, "ctime": ctime } 
                
                pictures.append(picture_dict)
                
            chatbase_msg = Message(
                    api_key="api_key",
                    type="user",
                    platform="Line",
                    version="1.0",
                    user_id=event.source.user_id,
                    message="查看場館照片_" + venue,
                    intent="查看場館照片"
                )

            resp =chatbase_msg.send()

            flora.send_currentSituation_picture_message(event.reply_token, pictures)
                
#             flora.send_ifProblem_message(event.reply_token)
        
        if "manager-currentSituation" in event.postback.data:

            venue = get_venue(event.postback.data)
            
            if redisManager.get_account(event.source.user_id, venue) != None:
            
                flora.send_correctCurrent_message(event.reply_token,venue=venue)

                redisManager.set(key=event.source.user_id + "_correct_currentSituation_venue", value= venue)
                
            else:
                                                                                    
                flora.send_login_message(event.reply_token, venue=venue, ifRemind=True, action="currentSituation")

        elif event.postback.data == "correct-currentSituation-no":

            flora.send_manager_menu_message(event.reply_token)

        elif event.postback.data == "ensure-currentSituation-no":

            path = redisManager.get(event.source.user_id + "_tmp_picture")
            os.remove(path)
            flora.send_manager_menu_message(event.reply_token)

        elif event.postback.data == "ensure-currentSituation-yes":

            flora.send_finishCorrect_message(event.reply_token)

    
    ## askLocation StroyLine         
#     elif "askLocation" in event.postback.data:

#         venue = get_venue(event.postback.data)
       
#         locationInfoDict = redisManager.get_locationInfoDict(venue=venue)
        
#         flora.send_venueLocation_message(event.reply_token, locationInfoDict)
    
    elif "login" in event.postback.data:
        
        venue = get_venue(event.postback.data)
        
        flora.send_login_message(event.reply_token, venue=venue)
        
#         直接給展館位置 + 花博官網交通資訊
                
    elif event.postback.data == "another_question_no":
        flora.send_endConversation_message(event.reply_token)

    elif event.postback.data == "another_question_yes":
        flora.send_menu_message(event.reply_token)
def handle_message(event):
    
    text = event.message.text.lower()

#     秀出三個園區分別的展館
    if text == "聯絡客服":
        
        flora.send_customerService_message(event.reply_token)

    elif text == "后里馬場" or text == "森林園區" or text == "外埔園區" or text == "葫蘆墩公園":
        
        chatbase_msg = Message(
            api_key="api_key", 
            type="user",
            platform="Line",
            version="1.0",
            user_id=event.source.user_id,
            message=event.message.text,
            intent="start_" + event.message.text
        )

        resp =chatbase_msg.send() 

        redisManager.set_userDist(event.source.user_id, dist=text)
        
        flora.send_functionList_message(event.reply_token, dist=text)     
        
    elif text == "查詢不用排隊的展館":
        
        dist = redisManager.get_userDist(event.source.user_id)
        
        if dist == None:
            
            flora.send_no_dist_message(event.reply_token)
            
            return
        
        chatbase_msg = Message(
            api_key="api_key", 
            type="user",
            platform="Line",
            version="1.0",
            user_id=event.source.user_id,
            message=event.message.text,
            intent="查詢不用排隊的展館_" + dist
        )

        resp =chatbase_msg.send()            
        
        
        dist_venues = get_currentDist_venues(dist)      
        
        noLine_venues = redisManager.get_noLine_dist_venues(dist_venues)
        
        flora.send_dist_noLine_venues(event.reply_token, dist=dist, noLine_venues=noLine_venues)
        
    elif text == "查詢特定展館資訊":

        dist = redisManager.get_userDist(event.source.user_id)
        
        if dist == None:
            
            flora.send_no_dist_message(event.reply_token)
            
            return
        
        chatbase_msg = Message(
            api_key="api_key",
            type="user",
            platform="Line",
            version="1.0",
            user_id=event.source.user_id,
            message=event.message.text,
            intent="查詢特定展館資訊_" + dist
        )

        resp =chatbase_msg.send()          
        
    
        dist_venues = get_currentDist_chosenVenues(dist)
        
        flora.send_askDistVenues_message(event.reply_token ,dist_venues)
        
        
    elif "排隊提醒" in text:
        
        venue = get_venue(text)
        
        flora.send_ensureIfLine_message(event.reply_token, venue)        
    
    
#     elif text == "查詢展館是否需要排隊":
#         flora.send_ask_venue(event.reply_token, signal="guest-ifLine")
        
    
#     elif text == "查詢展館人潮現況":
        
#         flora.send_ask_venue(event.reply_token, signal="guest-currentSituation")
        
#     elif text == "查詢哪些展館不用排隊":
        
#         noLine_venues = redisManager.get_noLine_venues()
#         flora.send_noLine_venues(event.reply_token, noLine_venues)
    
#     elif text == "查詢展館如何到達":
#         flora.send_ask_venue(event.reply_token, signal="guest-askLocation")
        
#     elif text == "我在哪裡":
#         flora.send_myLocation_message(event.reply_token)
        
        
        
    # 管理小幫手    
        
    
    elif "管理" in text:
        flora.send_manager_menu_message(event.reply_token)

    elif text == "登入" or text == "login":
        flora.send_ask_venue(event.reply_token, signal="manager-login")        
        
    elif text == "更正展館排隊資訊":
        flora.send_ask_venue(event.reply_token, signal="manager-ifLine")
        
    elif text == "新增展館人潮現況照片":
        flora.send_ask_venue(event.reply_token, signal="manager-currentSituation")
        
        
    # 比較是不是展館名稱 (因為演算法速度把它放最下面)
    elif isVenueEqualMessage(text):
        
        # 未來會有簡寫表,可能要有正名的 code,用dict去轉換
        
        dist = redisManager.get_userDist(event.source.user_id)
        
        title = synonym2title(text)
        
        status = get_status(title)

        if dist == None:

            flora.send_no_dist_message(event.reply_token)

            return
        
        chatbase_msg = Message(
            api_key="api_key",
            type="user",
            platform="Line",
            version="1.0",
            user_id=event.source.user_id,
            message="展館資訊_" + title,
            intent="展館資訊"
        )

        resp =chatbase_msg.send()   

        dist_venues = get_currentDist_venues(dist)            

        noLine_venues = redisManager.get_noLine_dist_venues(dist_venues)

        flora.send_ifLineResult_message(event.reply_token, venue=title.lower(), status=status, dist=dist, noLine_venues=noLine_venues)        
        
#         flora.send_venueFunction_message(event.reply_token, venue = title)           
    
    # 給我檢測用
    elif text == "get queue":
        len_queue = advancedScheduleManager.get_queue()
        flora.pprint(str(len_queue))
        
#     elif text == "run once":
        
#         if scheduleManager.run_once() != None:
#             flora.pprint(scheduleManager.run_once())
#         else:
#             flora.pprint("queue is empty")
            
    elif text == "test":
        
        advancedScheduleManager.test_scheduler(bot=flora)
        
    elif text == "get id":
        if isinstance(event.source, SourceGroup):
            print(event.source)
            print('group id: ' + event.source.group_id)
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text='group id: ' + event.source.group_id))
            
        elif isinstance(event.source, SourceRoom):
            print('group id: ' + event.source.room_id)
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text='room id: ' + event.source.room_id))
        else:
            print(event.source)
            print('user id: ' + event.source.user_id)
            line_bot_api.reply_message(
                event.reply_token, TextSendMessage(text="user id: " + event.source.user_id))        
Exemple #15
0
def handle_message(event):

    profile = line_bot_api.get_profile(event.source.user_id)

    loc_dis_min = {}
    nearest_loc = []

    user_loc = event.message.text
    print(user_loc)

    try:
        gecode_result = gmaps.geocode(user_loc)
        user_loc_abs = np.array(
            list(gecode_result[0]['geometry']['location'].values()))

        for i in data_pm['feeds']:

            device_loc_abs = np.array([i['gps_lat'], i['gps_lon']])

            #Euclidean Distance between two location
            loc_dis = np.sqrt(np.sum(np.square(user_loc_abs - device_loc_abs)))
            loc_dis_min[i['device_id']] = [
                i['s_d0'], loc_dis, i['gps_lat'], i['gps_lon'], i['s_t0'],
                i['s_h0']
            ]

        loc_dis_min = sorted(loc_dis_min.items(), key=lambda e: e[1][1])

        for i in range(5):
            gecode_result = gmaps.reverse_geocode(
                (loc_dis_min[i][1][2], loc_dis_min[i][1][3]), language='zh-TW')
            nearest_loc.append(gecode_result[0]['formatted_address'])

        print(loc_dis_min[0][1][0])

        #滾軸
        carousel_template = CarouselTemplate(columns=[
            CarouselColumn(
                thumbnail_image_url=
                'https://maps.googleapis.com/maps/api/staticmap?center=' +
                str(loc_dis_min[0][1][2]) + ',' + str(loc_dis_min[0][1][3]) +
                '&zoom=16&markers=color:blue%7Clabel:S%7C' +
                str(loc_dis_min[0][1][2]) + ',' + str(loc_dis_min[0][1][3]) +
                '&size=600x300&key=' + static_maps_api_key,
                title=nearest_loc[0][3:23],
                text='➤pm2.5為' + str(loc_dis_min[0][1][0]) + '\n➤溫度為' +
                str(loc_dis_min[0][1][4]) + '\n➤濕度為' +
                str(loc_dis_min[0][1][5]),
                actions=[
                    PostbackTemplateAction(
                        label='貼心小提醒',
                        data=str(loc_dis_min[0][1][0]),
                    )
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://maps.googleapis.com/maps/api/staticmap?center=' +
                str(loc_dis_min[1][1][2]) + ',' + str(loc_dis_min[1][1][3]) +
                '&zoom=16&markers=color:blue%7Clabel:S%7C' +
                str(loc_dis_min[1][1][2]) + ',' + str(loc_dis_min[1][1][3]) +
                '&size=600x300&key=' + static_maps_api_key,
                title=nearest_loc[1][3:23],
                text='➤pm2.5為' + str(loc_dis_min[1][1][0]) + '\n➤溫度為' +
                str(loc_dis_min[1][1][4]) + '\n➤濕度為' +
                str(loc_dis_min[1][1][5]),
                actions=[
                    PostbackTemplateAction(
                        label='貼心小提醒',
                        data=str(loc_dis_min[1][1][0]),
                    )
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://maps.googleapis.com/maps/api/staticmap?center=' +
                str(loc_dis_min[2][1][2]) + ',' + str(loc_dis_min[2][1][3]) +
                '&zoom=16&markers=color:blue%7Clabel:S%7C' +
                str(loc_dis_min[2][1][2]) + ',' + str(loc_dis_min[2][1][3]) +
                '&size=600x300&key=' + static_maps_api_key,
                title=nearest_loc[2][3:23],
                text='➤pm2.5為' + str(loc_dis_min[2][1][0]) + '\n➤溫度為' +
                str(loc_dis_min[2][1][4]) + '\n➤濕度為' +
                str(loc_dis_min[2][1][5]),
                actions=[
                    PostbackTemplateAction(
                        label='貼心小提醒',
                        data=str(loc_dis_min[2][1][0]),
                    )
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://maps.googleapis.com/maps/api/staticmap?center=' +
                str(loc_dis_min[3][1][2]) + ',' + str(loc_dis_min[3][1][3]) +
                '&zoom=16&markers=color:blue%7Clabel:S%7C' +
                str(loc_dis_min[3][1][2]) + ',' + str(loc_dis_min[3][1][3]) +
                '&size=600x300&key=' + static_maps_api_key,
                title=nearest_loc[3][3:23],
                text='➤pm2.5為' + str(loc_dis_min[3][1][0]) + '\n➤溫度為' +
                str(loc_dis_min[3][1][4]) + '\n➤濕度為' +
                str(loc_dis_min[3][1][5]),
                actions=[
                    PostbackTemplateAction(
                        label='貼心小提醒',
                        data=str(loc_dis_min[3][1][0]),
                    )
                ]),
            CarouselColumn(
                thumbnail_image_url=
                'https://maps.googleapis.com/maps/api/staticmap?center=' +
                str(loc_dis_min[4][1][2]) + ',' + str(loc_dis_min[4][1][3]) +
                '&zoom=16&markers=color:blue%7Clabel:S%7C' +
                str(loc_dis_min[4][1][2]) + ',' + str(loc_dis_min[3][1][3]) +
                '&size=600x300&key=' + static_maps_api_key,
                title=nearest_loc[4][3:23],
                text='➤pm2.5為' + str(loc_dis_min[4][1][0]) + '\n➤溫度為' +
                str(loc_dis_min[4][1][4]) + '\n➤濕度為' +
                str(loc_dis_min[4][1][5]),
                actions=[
                    PostbackTemplateAction(
                        label='貼心小提醒',
                        data=str(loc_dis_min[4][1][0]),
                    )
                ])
        ])

        template_message = TemplateSendMessage(alt_text='距離最近的五個測站',
                                               template=carousel_template)
        print(profile.display_name)

        line_bot_api.reply_message(event.reply_token, template_message)

        msg = Message(
            api_key=chatbase_api_key,
            type="user",
            platform="Line",
            version="1.0",
            user_id=event.source.user_id,
            message=event.message.text,
            intent="LinebotSearchPostion",
            not_handled=False,
        )
        resp = msg.send()

    except:

        error_mes = '您輸入的地點附近沒有測站。'
        output_mes = TextSendMessage(text=error_mes)

        print(profile.display_name)
        line_bot_api.reply_message(event.reply_token, output_mes)

        msg = Message(
            api_key=chatbase_api_key,
            type="user",
            platform="Line",
            version="1.0",
            user_id=event.source.user_id,
            message=event.message.text,
            intent="LinebotSearchPostion",
            not_handled=True,
        )
        resp = msg.send()
Exemple #16
0
def handle_message(event):

    profile = line_bot_api.get_profile(event.source.user_id)

    input_str = event.message.text

    print(profile.display_name)
    ##
    arg_ss = input_str.split()[0]
    arg_checkin_year = input_str.split()[1]
    arg_checkin_month = input_str.split()[2]
    arg_checkin_monthday= input_str.split()[3]
    arg_checkout_year = input_str.split()[4]
    arg_checkout_month = input_str.split()[5]
    arg_ckeckout_monthday = input_str.split()[6]
    arg_adults = input_str.split()[7]
    arg_group_children = input_str.split()[8]
    url = 'https://www.booking.com/searchresults.zh-tw.html?ss=\"' + quote(str(arg_ss)) + '\"&checkin_year=' + quote(str(arg_checkin_year)) + '&checkin_month=' + quote(str(arg_checkin_month)) + '&checkin_monthday=' + quote(str(arg_checkin_monthday)) + '&checkout_year=' + quote(str(arg_checkout_year)) +  '&checkout_month=' + quote(str(arg_checkout_month)) + '&ckeckout_monthday=' + quote(str(arg_ckeckout_monthday)) + '&group_adults=' + quote(str(arg_adults)) + '&group_children=' + quote(str(arg_group_children))
    ##
    print("===================================")
    print(url)
    print("===================================")
    ####
    context = ssl._create_unverified_context()

    headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
    #headers = {"User-Agent": "curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8r zlib/1.2.3"}

    request = urllib.request.Request(url, headers = headers)

    response = urllib.request.urlopen(request, context = context)

    soup = BeautifulSoup(response, 'html.parser')

    ##
    ### Hotel Title ###
    name = soup.select('.sr-hotel__name')
    name_list = []

    for i in range(len(name)):
        a = name[i].contents
        name_list.append(a[0].split("\n")[1])

    ### Hotel Price ###
    #price availprice no_rack_rate
    price_list = soup.find_all("strong", {"class":"price"})
    prices_list = []

    for price in price_list:  
    #     print(price.text.replace(u'\xa0', u' ').replace("\n", "").split()[1])
        p = price.text.replace(u'\xa0', u' ').replace("\n", "").split()[1]
        
        if len(p) > 3:
            c = p.split(',')
            Price = c[0] + c[1]
            Price = int(Price)
        
        else:
            Price = int(p)
            
        prices_list.append(Price)

    ### Hotel Score ###
    star = soup.find_all("span",{"class":"review-score-badge"})
    score_list = []


    for i in range(len(star)):
    #     print(star[i].text.split()[0])
        score_list.append(star[i].text.split()[0])

    ### Hotel URL ###
    link = soup.find_all("a",{"class":"hotel_name_link url"})
    url1 = "https://www.booking.com/"
    url_list = []

    for i in range(len(link)):
        url2 = link[i].get('href').split("\n")[1]
        url3 = link[i].get('href').split("\n")[2]
        url = url1 + url2 + url3
        url_list.append(url)

    ### Hotel Image URL ###
    img_url = soup.find_all("img",{"class":"hotel_image"})
    img_list = []

    for i in range(len(img_url)):
        img_list.append(img_url[i].get('src'))


    try:
        # length = min(len(name_list),len(prices_list),len(star),len(link),len(img_url))
        length = min(len(name_list),len(star),len(link),len(img_url))


        print("===================================")
        print(length)
        print(len(name_list))
        print(len(star))
        print(len(link))
        print(len(img_url))
        print("===================================")

        end = length - 2
        name_list = name_list[0:end]
        # prices_list = prices_list[0:end]
        url_list = url_list[0:end]
        score_list = score_list[0:end]
        img_list = img_list[0:end]

        hotel_df = pd.DataFrame({"Hotel_name":name_list,"Hotel_url":url_list,"Hotel_score":score_list,"Hotel_pic":img_list}) #"Hotel_price":prices_list,
        hotel_df = hotel_df.sort_values(by = ['Hotel_score'],ascending=False).reset_index(drop=True)

        hotel_df = hotel_df[:6]
        hotel_df = hotel_df[["Hotel_name","Hotel_url","Hotel_score","Hotel_pic"]]
        print(hotel_df.iloc[0,0])
        print(hotel_df.iloc[0,1])
        print(hotel_df.iloc[0,2])
        print(hotel_df.iloc[0,3])

        carousel_template = CarouselTemplate(

            columns=[
                CarouselColumn(
                    thumbnail_image_url=hotel_df.iloc[0,3],
                    title = hotel_df.iloc[0,0][:20],
                    text = '(⊙0⊙)首推訂房(⊙0⊙)',
                    actions=[
                        URITemplateAction(
                            label='評分為:'+str(hotel_df.iloc[0,2]),
                            uri=hotel_df.iloc[0,1]
                        )
                    ]
                ),
                CarouselColumn(
                    thumbnail_image_url=hotel_df.iloc[1,3],
                    title = hotel_df.iloc[1,0][:20],
                    text = '(⊙ˍ⊙)激推訂房(⊙ˍ⊙)',
                    actions=[
                        URITemplateAction(
                            label='評分為:'+str(hotel_df.iloc[1,2]),
                            uri=hotel_df.iloc[1,1]
                        )
                    ]
                ),
                CarouselColumn(
                    thumbnail_image_url=hotel_df.iloc[2,3],
                    title = hotel_df.iloc[2,0][:20],
                    text = '(ˊ● ω ●ˋ)再推訂房(ˊ● ω ●ˋ)',
                    actions=[
                        URITemplateAction(
                            label='評分為:'+str(hotel_df.iloc[2,2]),
                            uri=hotel_df.iloc[2,1]
                        )
                    ]
                ),
                CarouselColumn(
                    thumbnail_image_url=hotel_df.iloc[3,3],
                    title = hotel_df.iloc[3,0][:20],
                    text = '(♡∀♡)再推一個(♡∀♡)',
                    actions=[
                        URITemplateAction(
                            label='評分為:'+str(hotel_df.iloc[3,2]),
                            uri=hotel_df.iloc[3,1]
                        )
                    ]
                ),
                CarouselColumn(
                    thumbnail_image_url=hotel_df.iloc[4,3],
                    title = hotel_df.iloc[4,0][:20],
                    text = '(´・ω・`)選我選我(´・ω・`)',
                    actions=[
                        URITemplateAction(
                            label='評分為:'+str(hotel_df.iloc[4,2]),
                            uri=hotel_df.iloc[4,1]
                        )
                    ]
                )
            ]     
        )

    except:
        error_message = "天啊!出錯了!\n您可能是遇到了以下問題。\n1.你的指令打錯了。\n指令是:訂房地點(ex:桃園) 訂房日期(ex:2018 6 30) 退房日期(ex:2018 7 2) 訂房人數,分別為大人個數與小孩個數(ex:4 2)\n每個之間都有空格噢\n範例:桃園 2018 6 30 2018 7 2 4 2\n2.您所蒐尋的日期還未提供訂房資訊,要再等一等噢!\n3.沒有相關訂房資訊,建議您換個關鍵字。\n"
        message = TextSendMessage(text=error_message)
        line_bot_api.reply_message(event.reply_token,message)\

        msg = Message(api_key="bf6041f2-134c-4c38-a42e-6540684311d0",
              type="user",
              platform="Line",
              version="1.0",
              user_id=profile.display_name,
              message=error_message,
              intent="LinebotSearchPostion",  
              not_handled=True,           
              )            
        resp = msg.send()


    ##################
    # output = ""
    # for i in range(6):
    #     tmp = hotel_df.iloc[i,0] + " " + hotel_df.iloc[i,1] + " " + hotel_df.iloc[i,2]
    #     output = output + tmp
    #     output = output + "\n"
    #     tmp = ""
    # output = hotel_df.iloc[0,1]

    ####
    # Carousel_template = hotel_df.iloc[0,3]
    # message = TextSendMessage(text=output)
    template_message = TemplateSendMessage(
        alt_text = '距離最近的五間旅館', 
        template = carousel_template
    )
    
    line_bot_api.reply_message(event.reply_token, template_message)

    msg = Message(api_key="bf6041f2-134c-4c38-a42e-6540684311d0",
              type="user",
              platform="Line",
              version="1.0",
              user_id=profile.display_name,
              message=event.message.text,
              intent="LinebotSearchPostion",  
              not_handled=False,           
              )            
    resp = msg.send()