Ejemplo n.º 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()
Ejemplo n.º 2
0
 def test_to_json(self):
     api_key = '1234'
     platform = '1'
     message = '2'
     intent = '3'
     version = '4'
     user_id = '5'
     time_stamp = int(round(time.time() * 1e3))
     i = Message(api_key=api_key,
                 platform=platform,
                 message=message,
                 intent=intent,
                 version=version,
                 user_id=user_id,
                 type=MessageTypes.USER,
                 not_handled=True,
                 time_stamp=time_stamp)
     i.set_as_feedback()
     self.assertEqual(
         json.loads(i.to_json()),
         {
             'api_key': api_key,
             'platform': platform,
             'message': message,
             'intent': intent,
             'version': version,
             'user_id': user_id,
             'time_stamp': time_stamp,
             'type':
             MessageTypes.USER,  # since we did not set as type agent
             'not_handled': True,
             'feedback': True
         })
Ejemplo n.º 3
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()
Ejemplo n.º 4
0
def TRChatBase(chat_id, message_text, intent):
    msg = Message(api_key=Config.CHAT_BASE_TOKEN,
                  platform="Telegram",
                  version="1.3",
                  user_id=chat_id,
                  message=message_text,
                  intent=intent)
    resp = msg.send()
Ejemplo n.º 5
0
 def __init__(self, user_id, message, intent: str = "", not_handled: bool = False):
     self.api_key = STATISTICS_TOKEN
     self.platform = "tg"
     Message.__init__(self,
                      api_key=self.api_key,
                      platform=self.platform,
                      user_id=user_id,
                      message=message,
                      intent=intent,
                      not_handled=not_handled)
Ejemplo n.º 6
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)
Ejemplo n.º 7
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()
Ejemplo n.º 8
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()
Ejemplo n.º 9
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})
Ejemplo n.º 10
0
 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)
Ejemplo n.º 11
0
def chatbaseMessage(intent, user, mesage=None):
    return Message(api_key=os.getenv("CHATBASE_TOKEN"),
                   platform="Telegram",
                   message=mesage,
                   intent=intent,
                   version="1.0",
                   user_id=user)
Ejemplo n.º 12
0
def processChatbase(req, res):
    result = req.get("queryResult")
    intentname = result.get("intent")

    #message de base
    ##à modifier: 'api_key = ''' changer l'API key
    set = MessageSet(api_key='56bd0b2b-4b67-4522-8933-1ff443a8a922',
                     platform='Dialogflow',
                     version="0.1",
                     user_id=req.get("session"))
    #not_handled integration
    if result.get("action") == "input.unknown":
        msg = set.new_message(intent=intentname.get("displayName"),
                              message=result.get("queryText"),
                              not_handled=True)
    #handled
    else:
        msg = set.new_message(intent=intentname.get("displayName"),
                              message=result.get("queryText"))

        msg2 = Message(
            api_key='56bd0b2b-4b67-4522-8933-1ff443a8a922',
            platform='Dialogflow',
            version="0.1",
            user_id=req.get("session"),
            #message
            intent=intentname.get("displayName"),
            type=MessageTypes.AGENT)

        set.append_message(msg2)
#   #message envoyé a chatbase
    resp = set.send()

    return None
Ejemplo n.º 13
0
def _analyze(message: str, intent: str, user_id: int or str):
    msg = Message(api_key=CHATBASE_API_KEY,
                  platform="telegram",
                  message=message,
                  intent=intent,
                  user_id=user_id if type(user_id) == str else str(user_id),
                  version="3")
    return AsyncTask(msg.send).wait()
Ejemplo n.º 14
0
def _analyze(message: str, intent: str, user_id: Union[int, str]):
    return Message(
        api_key=Config.CHATBASE_API_KEY,
        platform="telegram",
        message=message,
        intent=intent,
        user_id=user_id if isinstance(user_id, str) else str(user_id),
        version="3").send()
Ejemplo n.º 15
0
 async def _make_request(self):
     url = "https://chatbase.com/api/message"
     async with aiohttp.ClientSession() as session:
         async with session.post(url,
                                 data=self.to_json(),
                                 headers=Message.get_content_type()) as response:
             logger.info(f"Chatbase response {response}")
             return response
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
Ejemplo n.º 17
0
 def send(self):
     """Send the message set to the Chatbase API"""
     try:
         url = ("https://chatbase.com/api/messages?api_key=%s" %
                self.api_key)
         requests.post(url,
                       data=self.to_json(),
                       headers=Message.get_content_type())
     except HTTPError:
         pass
Ejemplo n.º 18
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()
Ejemplo n.º 19
0
 def test_type_setting(self):
     # instance the entity in function to eliminate test-case bleeding
     i = Message()
     i.set_as_type_user()
     self.assertEqual(i.type, MessageTypes.USER)
     i.set_as_type_agent()
     self.assertEqual(i.type, MessageTypes.AGENT)
Ejemplo n.º 20
0
    def publish(self, userQuery, botResponse, not_handled, userId):
        time_stamp = int(round(time.time() * 1e3))  # Mandatory

        # Create an instance of MessageSet to collect all the messages
        message_set = MessageSet(api_key=str(self.api_key),
                                 platform=self.platform,
                                 version=self.version,
                                 user_id=userId)
        # Create an instance of Message for the user message and set values in the constructor
        msg1 = Message(api_key=self.api_key,
                       platform=self.platform,
                       message=userQuery,
                       intent=self.intent,
                       version=self.version,
                       user_id=userId,
                       type=MessageTypes.USER,
                       not_handled=not_handled,
                       time_stamp=time_stamp)
        # Set the message as "handled" because the NLP was able to successfully decode the intent
        msg1.set_as_feedback()

        # Create an instance of Message for the bot response message and set values in the constructor
        msg2 = Message(api_key=self.api_key,
                       platform=self.platform,
                       message=botResponse,
                       version=self.version,
                       user_id=userId,
                       type=MessageTypes.AGENT)

        print("User id", userId)
        # Push messages into the collection (MessageSet)
        message_set.append_message(msg1)
        message_set.append_message(msg2)

        # Send the messages
        response = message_set.send()
        print('Response code for sending Chatbase Message', response.content)
Ejemplo n.º 21
0
 def new_message(self,
                 intent="",
                 message="",
                 type=MessageTypes.USER,
                 not_handled=False,
                 time_stamp=None):
     """Add a message to the internal messages list and return it"""
     self.messages.append(
         Message(api_key=self.api_key,
                 platform=self.platform,
                 version=self.version,
                 user_id=self.user_id,
                 intent=intent,
                 message=message,
                 type=type,
                 not_handled=not_handled,
                 time_stamp=time_stamp))
Ejemplo n.º 22
0
def processChatbase(req, res):
    result = req.get("result")
    metadata = result.get("metadata")
    fulfillment = result.get("fulfillment")
    status = req.get("status")

    #message de base
    set = MessageSet(api_key='56bd0b2b-4b67-4522-8933-1ff443a8a922',
                     platform='Dialogflow',
                     version="0.1",
                     user_id=req.get("sessionId"))
    #not_handled integration
    if result.get(
            "action") == "input.unknown" or fulfillment.get("speech") != "":
        msg = set.new_message(intent=metadata.get("intentName"),
                              message=result.get("resolvedQuery"),
                              not_handled=True)
    #handled
    else:
        msg = set.new_message(intent=metadata.get("intentName"),
                              message=result.get("resolvedQuery"))

        msg2 = Message(
            api_key='56bd0b2b-4b67-4522-8933-1ff443a8a922',
            platform='Dialogflow',
            version="0.1",
            user_id=req.get("sessionId"),
            #message
            intent=metadata.get("intentName"),
            type=MessageTypes.AGENT)

        set.append_message(msg2)
    #message envoyé a chatbase
    resp = set.send()

    return None
Ejemplo n.º 23
0
 def test_not_handled_setting(self):
     i = Message()
     i.set_as_not_handled()
     self.assertTrue(i.not_handled)
     i.set_as_handled()
     self.assertFalse(i.not_handled)
Ejemplo n.º 24
0
 def __init__(self, *args, **kwargs):
     super(TestMessage, self).__init__(*args, **kwargs)
     self.inst = Message()
Ejemplo n.º 25
0
 def test_ts_method(self):
     self.assertTrue(type(Message.get_current_timestamp()) is int)
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))        
Ejemplo n.º 28
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()
Ejemplo n.º 29
0
 def test_message_set_append_message(self):
     api_key = '1234'
     platform = '1'
     message = '2'
     intent = '3'
     version = '4'
     user_id = '5'
     time_stamp = int(round(time.time() * 1e3))
     msg1 = Message(api_key=api_key,
                    platform=platform,
                    message=message,
                    intent=intent,
                    version=version,
                    user_id=user_id,
                    type=MessageTypes.USER,
                    not_handled=True,
                    time_stamp=time_stamp)
     msg1.set_as_feedback()
     msg2 = Message(api_key=api_key,
                    platform=platform,
                    message=message,
                    version=version,
                    user_id=user_id,
                    type=MessageTypes.AGENT)
     message_set = MessageSet(api_key=api_key,
                              platform=platform,
                              version=version,
                              user_id=user_id)
     message_set.append_message(msg1)
     message_set.append_message(msg2)
     msg1 = message_set.messages[0]
     self.assertEqual(
         json.loads(msg1.to_json()),
         {
             'api_key': api_key,
             'platform': platform,
             'message': message,
             'intent': intent,
             'version': version,
             'user_id': user_id,
             'time_stamp': time_stamp,
             'type':
             MessageTypes.USER,  # since we did not set as type agent
             'not_handled': True,
             'feedback': True
         })
     msg2 = message_set.messages[1]
     self.assertEqual(
         json.loads(msg2.to_json()),
         {
             'api_key': api_key,
             'platform': platform,
             'message': message,
             'intent': msg2.intent,
             'version': version,
             'user_id': user_id,
             'time_stamp': msg2.time_stamp,
             'type': MessageTypes.AGENT,  # since we did set as type agent
             'not_handled': False,
             'feedback': False
         })
Ejemplo n.º 30
0
 def test_feedback_setting(self):
     i = Message()
     i.set_as_feedback()
     self.assertTrue(i.feedback)
     i.set_as_not_feedback()
     self.assertFalse(i.feedback)