예제 #1
0
 async def on_message_activity(self,turn_context:TurnContext):
     conmode = await self.conprop.get(turn_context,ConState)
     ordermode = await self.userprop.get(turn_context,Order)
     luis_result = await self.LuisReg.recognize(turn_context)
     intent = LuisRecognizer.top_intent(luis_result)
     await turn_context.send_activity(f"Top Intent : {intent}")
     retult = luis_result.properties["luisResult"]
     item = ''
     if len(retult.entities) != 0:
         await turn_context.send_activity(f" Luis Result {retult.entities[0]}")
         item = retult.entities[0].entity
     if(conmode.orderstatus == EnumOrder.ENTREE):
         await turn_context.send_activity("Please enter a main Entree")
         conmode.orderstatus = EnumOrder.SIDE
     elif(conmode.orderstatus == EnumOrder.SIDE):
         ordermode.entree = item
         await turn_context.send_activity("Please enter a side dish")
         conmode.orderstatus = EnumOrder.DRINK
     elif(conmode.orderstatus == EnumOrder.DRINK):
         await turn_context.send_activity("Please a drink")
         ordermode.side = item
         conmode.orderstatus = EnumOrder.DONE
     elif(conmode.orderstatus == EnumOrder.DONE):
         ordermode.drink = item
         info = ordermode.entree + " " + ordermode.side + "  " + ordermode.drink
         await turn_context.send_activity(info)
         conmode.orderstatus = EnumOrder.ENTREE
예제 #2
0
 async def on_message_activity(self, turn_context:TurnContext):
     luis_result = await self.LuisReg.recognize(turn_context)
     #extract top intent
     intent = LuisRecognizer.top_intent(luis_result)
     await turn_context.send_activity(f"Top Intent: {intent}")
     result = luis_result.properties["luisResult"]
     await turn_context.send_activity(f"Luis Result: {result.entities[0]}")
예제 #3
0
class LuisBot(ActivityHandler):
    def __init__(self):
        self.config = Config()
        self.luis_app = LuisApplication(
            self.config.luis_app_id,
            self.config.luis_endpoint_key,
            self.config.luis_endpoint,
        )
        self.luis_option = LuisPredictionOptions(
            include_all_intents=True,
            include_instance_data=True,
        )
        self.Luis_recognizer = LuisRecognizer(
            application=self.luis_app,
            prediction_options=self.luis_option,
            include_api_results=True)

    async def on_message_activity(self, turn_context: TurnContext):

        weather = Weather()
        luis_result = await self.Luis_recognizer.recognize(turn_context)
        # intent = LuisRecognizer.top_intent(luis_result)
        intent = self.Luis_recognizer.top_intent(luis_result)
        result = luis_result.properties["luisResult"]
        json_str = json.loads((str(result.entities[0])).replace("'", "\""))
        entity = json_str.get("entity")
        weather_info = weather.get_weather_info(entity)

        # await turn_context.send_activity(f"Entity  {result.entities[0]}")
        await turn_context.send_activity(f"Top Intent : {intent}")
        await turn_context.send_activity(f"Entity  {entity}")
        await turn_context.send_activity(f"{weather_info}")
예제 #4
0
    async def on_message_activity(self, turn_context: TurnContext):
        # First, we use the dispatch model to determine which cognitive service (LUIS or QnA) to use.
        recognizer_result = await self.recognizer.recognize(turn_context)

        # Top intent tell us which cognitive service to use.
        intent = LuisRecognizer.top_intent(recognizer_result)

        # Next, we call the dispatcher with the top intent.
        await self._dispatch_to_top_intent(turn_context, intent, recognizer_result)
예제 #5
0
    async def execute_luis_query(
            luis_recognizer: LuisRecognizer,
            turn_context: TurnContext) -> (Intent, object):
        """
        Returns an object with preformatted LUIS results for the bot's dialogs to consume.
        """
        result = None
        intent = None

        try:
            recognizer_result = await luis_recognizer.recognize(turn_context)
            intent = LuisRecognizer.top_intent(recognizer_result)
            print("INTENT", intent)

            if intent == Intent.CREATE_REMINDER.value:
                result = Reminder()
                reminder_entities = recognizer_result.entities.get(
                    "$instance", {}).get("reminder_title", [])
                if len(reminder_entities) > 0:
                    result.title = reminder_entities[0]["text"].title()
                else:
                    result.title = None

                date_entities = recognizer_result.entities.get("datetime", [])

                if date_entities:
                    timex = date_entities[0]["timex"]

                    if timex:
                        result.reminder_time = DatetimeHelper.format_datetime(
                            timex[0])

                else:
                    result.reminder_time = None
            elif intent == Intent.SNOOZE_REMINDER.value:
                text = turn_context.activity.text
                result = Reminder()
                result.id = text.split()[1]

                date_entities = recognizer_result.entities.get("datetime", [])

                if date_entities:
                    timex = date_entities[0]["timex"]

                    if timex:
                        result.reminder_time = DatetimeHelper.format_datetime(
                            timex[0])

        except Exception as exception:
            print(exception)

        return intent, result
    async def on_message_activity(self, turn_context: TurnContext):
        # 要使用共用的data時,需先下這行指令
        user_profile = await self.user_profile_accessor.get(
            turn_context, 
            DialogData
            )
        # 將要被自動化新增的LUIS APP ID寫進dialog_data裡
        user_profile.luis_appid = self.luis_appid

        # 判斷是否為新增訓練語句的對話框,如果是,則進入;如不是,則開始辨識要做的動作
        if user_profile.isTraining == 1 :
            await DialogHelper.run_dialog(self.dialog, turn_context, self.conversation_state.create_property("DialogState"))
        else:            
            # 辨識使用者傳的訊息
            recognizer_result = await self.recognizer.recognize(turn_context)
            # 找出最高可能的意圖
            intent = LuisRecognizer.top_intent(recognizer_result)

            # 針對每個意圖做出不同的動作
            if intent == "創建一個新的LUIS_APP" :
                app_name = recognizer_result.entities['app_name'][0]
                await self.create_luis_app(app_name, turn_context)  
            elif intent == "創建一個entity" : 
                entity_name = recognizer_result.entities['entity_name'][0]
                await self.create_luis_entity(entity_name, turn_context)
            elif intent == "創建一個intent" : 
                intent_name = recognizer_result.entities['intent_name'][0]
                await self.create_luis_intent(intent_name, turn_context)
            elif intent == "新增訓練語句" : 
                await DialogHelper.run_dialog(self.dialog, turn_context, self.conversation_state.create_property("DialogState"))
                # 當判斷出為「新增訓練語句」的意圖,更改flag,使其下次直接進入用來新增訓練語句的對話框
                user_profile.isTraining  = 1
            elif intent == "訓練LUIS_APP" : 
                await self.train_luis(turn_context)
            elif intent == "PUBLISH_LUIS_APP" : 
                await self.publish_luis(turn_context)
            elif intent == "確認在哪一個LUIS_APP" : 
                await self.check_luis_app_name(turn_context)
            else : 
                await turn_context.send_activity(f"luis無法辨識")
예제 #7
0
    async def on_message_activity(self, turn_context: TurnContext):
        turn_context.activity.address = ''
        ## DB insert old user
        id_res = self.db_func.DB_query('SELECT ID FROM user_info')
        user_id = turn_context.activity.recipient.id
        #    if userid not in our db, add it
        if user_id not in id_res:
            insert_query = 'INSERT INTO user_info (ID, counter) VALUES (\'' + user_id + '\', 0);'
            self.db_func.DB_insert(insert_query)
            self.db_func.DB_commit()

        ## QnA Maker's response
        response = await self.qna_maker.get_answers(turn_context)
        #check_list = await self.qna_maker.get_questions(turn_context)
        ## LUIS's result & intent
        recognizer_result = await self.recognizer.recognize(turn_context)
        # parse intent and entity
        intent = LuisRecognizer.top_intent(recognizer_result)
        print(intent)
        ## get user input and make response
        luis_result = recognizer_result.properties["luisResult"]
        entity = ''

        # check if user typing in qna maker
        if response and len(response) > 0 and (turn_context.activity.text !=
                                               response[0].answer):
            await turn_context.send_activity(
                MessageFactory.text(response[0].answer))

    # 個人化推薦
        elif turn_context.activity.text == '個人化推薦':
            todayrecom = todaytop3eat()
            await turn_context.send_activity("今天最低溫為 %s, 為您推薦以下料理:" %
                                             todayrecom[0])
            todaylist = []
            for tt in range(3):
                restaurants_dict = googlemaps_API("北車", 3, todayrecom[1][tt])
                todaylist.append(
                    CardFactory.hero_card(
                        HeroCard(
                            title=restaurants_dict[0]['name'],
                            text='推薦指數 : ' +
                            str(restaurants_dict[0]['rating']),
                            images=[
                                CardImage(url=show_photo(restaurants_dict[0]
                                                         ['photo_reference']))
                            ],
                            buttons=[
                                CardAction(
                                    type="openUrl",
                                    title="地圖",
                                    value=
                                    "https://www.google.com/maps/search/?api=1&query="
                                    + str(restaurants_dict[0]['location_x']) +
                                    "," +
                                    str(restaurants_dict[0]['location_y']) +
                                    "&query_place_id=" +
                                    str(restaurants_dict[0]['place_id'])),
                                CardAction(type="imBack",
                                           title="點此看評論",
                                           value=restaurants_dict[0]['name'] +
                                           "_評論"),
                                CardAction(type="imBack",
                                           title="加入我的最愛",
                                           value=restaurants_dict[0]['name'] +
                                           "_加入最愛")
                            ])))
            msg = MessageFactory.carousel(todaylist)
            await turn_context.send_activity(msg)
        elif "加入最愛" in turn_context.activity.text:  ## add favorite button
            rest_name = turn_context.activity.text.split("_")[0]
            message = self.favor.add_favorite(user_id, rest_name)
            await turn_context.send_activity(message)
        elif turn_context.activity.text == '瀏覽紀錄':
            res = self.history.get_history(user_id)
            if (res == []):
                await turn_context.send_activity("還沒有瀏覽紀錄,趕快搜尋餐廳吧~GOGO")
            else:
                history_list = []
                for length in range(len(res)):
                    rest_name = res[length]
                    rest_location = find_position_with_xy(rest_name)
                    (x, y) = googlemaps_search_location(rest_name)
                    history_list.append(
                        CardFactory.hero_card(
                            HeroCard(
                                title=rest_name,
                                subtitle=rest_location,
                                buttons=[
                                    CardAction(
                                        type="openUrl",
                                        title="地圖",
                                        value=
                                        "https://www.google.com/maps/search/?api=1&query="
                                        + str(x) + ',' + str(y))
                                ])))
                message = MessageFactory.carousel(history_list)
                await turn_context.send_activity(message)
        elif turn_context.activity.text == '我的最愛':
            res = self.favor.get_favorite(user_id)
            if (res == []):
                await turn_context.send_activity("還沒有最愛的餐廳,趕快搜尋餐廳並加入最愛吧~GOGO")
            else:
                fav_list = []
                for length in range(len(res)):
                    rest_name = res[length]
                    rest_location = find_position_with_xy(rest_name)
                    (x, y) = googlemaps_search_location(rest_name)
                    fav_list.append(
                        CardFactory.hero_card(
                            HeroCard(
                                title=rest_name,
                                subtitle=rest_location,
                                buttons=[
                                    CardAction(
                                        type="openUrl",
                                        title="地圖",
                                        value=
                                        "https://www.google.com/maps/search/?api=1&query="
                                        + str(x) + ',' + str(y))
                                ])))
                message = MessageFactory.carousel(fav_list)
                await turn_context.send_activity(message)
        elif "加入最愛" in turn_context.activity.text:  ## add favorite button
            rest_name = turn_context.activity.text.split("_")[0]
            message = self.favor.add_favorite(user_id, rest_name)
            await turn_context.send_activity(message)
        # 歷史紀錄
        elif turn_context.activity.text == '瀏覽紀錄':
            res = self.history.get_history(user_id)
            print(user_id)
            if (res is None):
                await turn_context.send_activity("還沒有瀏覽紀錄,趕快搜尋餐廳吧~")
            else:
                history_list = []
                for length in range(len(res)):
                    rest_name = res[length]
                    rest_location = find_position_with_xy(rest_name)
                    history_list.append(
                        CardFactory.hero_card(
                            HeroCard(title=rest_name, subtitle=rest_location)))
                message = MessageFactory.carousel(history_list)
                await turn_context.send_activity(message)
        # IG
        elif "_IG" in turn_context.activity.text:
            hashtag = turn_context.activity.text.split("_")[0].split(
                ' ')[0].split('-')[0].split('/')[0].split("'")[0].split('&')[0]
            url = "https://www.instagram.com/explore/tags/" + str(hashtag)
            # print(url)
            await turn_context.send_activity("稍等一下唷! 美食公道伯正在幫你尋找餐廳的IG熱門貼文...")
            asa = []
            asa.append(
                CardFactory.hero_card(
                    HeroCard(
                        title=hashtag + '的IG熱門文章',
                        images=[
                            CardImage(
                                url=
                                'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQB1DfQKJ-vfC16ybbNPP0N7FVVV6bNEC3W9Q&usqp=CAU'
                            )
                        ],
                        buttons=[
                            CardAction(type="openUrl",
                                       title="前往IG熱門文章",
                                       value=str(url))
                        ])))
            message = MessageFactory.carousel(asa)

            await turn_context.send_activity(message)
        # 找評論

        elif "評論" in turn_context.activity.text:
            await turn_context.send_activity("稍等一下唷! 美食公道伯正在幫你尋找餐廳評論...")
            # 展宏的func
            re = webcrawl(turn_context.activity.text)
            # 佑誠的func
            blog_re = []
            blog_re = blogcrawler(turn_context.activity.text)

            review_list = []
            for index in range(len(blog_re)):
                url = str(blog_re[index][2])
                review_list.append(
                    CardFactory.hero_card(
                        HeroCard(title=blog_re[index][1],
                                 images=[CardImage(url=blog_re[index][3])],
                                 buttons=[
                                     CardAction(type="openUrl",
                                                title="前往網頁",
                                                value=str(url))
                                 ])))

            if re:
                url = str(re["愛食記"][1])
                review_list.append(
                    CardFactory.hero_card(
                        HeroCard(title=re["愛食記"][0],
                                 images=[CardImage(url=re["愛食記"][2])],
                                 buttons=[
                                     CardAction(type="openUrl",
                                                title="前往網頁",
                                                value=str(url))
                                 ])))

            if len(review_list) != 0:
                message = MessageFactory.carousel(review_list)
            else:
                message = "未查詢到這間餐廳的相關評論文章喔~ 歡迎您發布首則評論!"

            rest_name = turn_context.activity.text.split("_")[0]
            self.history.add_history(user_id, rest_name)

            message = MessageFactory.carousel(review_list)
            await turn_context.send_activity(message)

            # 書文的func

            # line address
        elif ("{" in turn_context.activity.text
              and "}" in turn_context.activity.text):
            line_address_json = json.loads(turn_context.activity.text)
            print('line_address_json', line_address_json)
            x = line_address_json['latitude']
            y = line_address_json['longitude']
            restaurants_dict = googlemaps_search_nearby(x, y, 'steak')
            # 沒有餐廳的狀況
            if (len(restaurants_dict) == 0):
                message = "您附近沒有相對應的餐廳可以推薦呦,輸入『吃』來繼續👀"
            else:
                restaurants_list = []
                for i in range(len(restaurants_dict)):
                    restaurants_list.append(
                        CardFactory.hero_card(
                            HeroCard(
                                title=restaurants_dict[i]['name'],
                                text='推薦指數 : ' +
                                str(restaurants_dict[i]['rating']) + "👍",
                                images=[
                                    CardImage(
                                        url=show_photo(restaurants_dict[i]
                                                       ['photo_reference']))
                                ],
                                buttons=[
                                    CardAction(
                                        type="openUrl",
                                        title="地圖",
                                        value=
                                        "https://www.google.com/maps/search/?api=1&query="
                                        +
                                        str(restaurants_dict[i]['location_x'])
                                        + "," +
                                        str(restaurants_dict[i]['location_y'])
                                        + "&query_place_id=" +
                                        str(restaurants_dict[i]['place_id'])),
                                    CardAction(
                                        type="imBack",
                                        title="點此看IG熱門貼文",
                                        value=restaurants_dict[i]['name'] +
                                        "_IG"),
                                    CardAction(
                                        type="imBack",
                                        title="點此看評論",
                                        value=restaurants_dict[i]['name'] +
                                        "_評論"),
                                    CardAction(
                                        type="imBack",
                                        title="加入我的最愛",
                                        value=restaurants_dict[i]['name'] +
                                        "_加入最愛")
                                ])))
                    if (i == 9):
                        break

                message = MessageFactory.carousel(restaurants_list)
                await turn_context.send_activity(message)
        #如果推薦給使用者的都不喜歡吃 就隨機推薦
        elif turn_context.activity.text == '都不喜歡':
            recom_list = [
                '鍋貼', '牛排', '燒烤', '水餃', '飯', '拉麵', '鐵板燒', '炸物', '壽喜燒', '吃到飽'
            ]
            #res = [random.randrange(0, 9, 1) for i in range(3)]
            res = random.sample(range(10), 3)  #產生不重複的
            #print("result:", list2)

            message = MessageFactory.carousel([
                CardFactory.hero_card(
                    HeroCard(subtitle='請選擇您想吃的類型: 😗',
                             buttons=[
                                 CardAction(type="imBack",
                                            title=recom_list[res[0]],
                                            value="我想吃" + recom_list[res[0]]),
                                 CardAction(type="imBack",
                                            title=recom_list[res[1]],
                                            value="我想吃" + recom_list[res[1]]),
                                 CardAction(type="imBack",
                                            title=recom_list[res[2]],
                                            value="我想吃" + recom_list[res[2]]),
                                 CardAction(type="imBack",
                                            title="都不喜歡 😡",
                                            value="都不喜歡")
                             ]))
            ])
            await turn_context.send_activity(message)
        else:
            ## LUIS's result & intent
            recognizer_result = await self.recognizer.recognize(turn_context)
            # parse intent and entity
            intent = LuisRecognizer.top_intent(recognizer_result)
            print(intent)
            ## get user input and make response
            luis_result = recognizer_result.properties["luisResult"]
            entity = ''
            if luis_result.entities:
                entities_list = []
                for ll in luis_result.entities:
                    print(turn_context.activity.text)
                    print(ll)
                    ll.entity = ll.entity.replace(" ", '')
                    entities_list.append(ll.entity)
                print(entities_list)
                print(len(entities_list))
                if len(entities_list) == 1:
                    entity = entities_list[0]
                # two entites situation
                else:
                    entity = entities_list[0] + '^' + entities_list[1]
                    print("double entity:", entity)
            entity = entity.replace("\x08", '')

            if intent == "使用者食物類別" and "_$" not in turn_context.activity.text and "_IG" not in turn_context.activity.text:

                message = MessageFactory.carousel([
                    CardFactory.hero_card(
                        HeroCard(
                            title='您想吃的食物為:' + str(entity),
                            subtitle='請選擇您的預算區間: 🤑',
                            buttons=[
                                CardAction(type="imBack",
                                           title="$$$",
                                           value="我想吃" + str(entity) + "_$$$"),
                                CardAction(type="imBack",
                                           title="$$",
                                           value="我想吃" + str(entity) + "_$$"),
                                CardAction(type="imBack",
                                           title="$",
                                           value="我想吃" + str(entity) + "_$")
                            ]))
                ])
                await turn_context.send_activity(message)

                # msg = '請輸入您目前的地點或是附近的景點 🧐(例如:北車、公館)(小提示:點擊Line的+號可以傳地址上來呦!)'

                # await turn_context.send_activity(msg)

            elif intent == "使用者地理位置" and "_$" not in turn_context.activity.text and "_IG" not in turn_context.activity.text:
                if entity == "":
                    entity = turn_context.activity.text
                    print(entity)
                message = MessageFactory.carousel([
                    CardFactory.hero_card(
                        HeroCard(
                            title='您的所在位置為:' + str(entity),
                            subtitle='請選擇您的預算區間: 🤑',
                            buttons=[
                                CardAction(type="imBack",
                                           title="$$$",
                                           value="我在" + str(entity) + "_$$$"),
                                CardAction(type="imBack",
                                           title="$$",
                                           value="我在" + str(entity) + "_$$"),
                                CardAction(type="imBack",
                                           title="$",
                                           value="我在" + str(entity) + "_$")
                            ]))
                ])
                await turn_context.send_activity(message)

            # find 2 entites in sequence
            elif "^" in entity:
                entity = entity.split("^")
                food = entity[0]
                location = entity[1]
                restaurants_dict = googlemaps_API(location, 2, food)

                # 沒有餐廳的狀況
                if (len(restaurants_dict) == 0):
                    message = "您附近沒有相對應的餐廳可以推薦呦,輸入『我想吃...』來繼續👀"
                else:
                    restaurants_list = []
                    for i in range(len(restaurants_dict)):
                        restaurants_list.append(
                            CardFactory.hero_card(
                                HeroCard(
                                    title=restaurants_dict[i]['name'],
                                    text='推薦指數 : ' +
                                    str(restaurants_dict[i]['rating']) + "👍",
                                    images=[
                                        CardImage(url=show_photo(
                                            restaurants_dict[i]
                                            ['photo_reference']))
                                    ],
                                    buttons=[
                                        CardAction(
                                            type="openUrl",
                                            title="地圖",
                                            value=
                                            "https://www.google.com/maps/search/?api=1&query="
                                            + str(restaurants_dict[i]
                                                  ['location_x']) + "," +
                                            str(restaurants_dict[i]
                                                ['location_y']) +
                                            "&query_place_id=" +
                                            str(restaurants_dict[i]
                                                ['place_id'])),
                                        CardAction(
                                            type="imBack",
                                            title="點此看IG熱門貼文",
                                            value=restaurants_dict[i]['name'] +
                                            "_IG"),
                                        CardAction(
                                            type="imBack",
                                            title="點此看評論",
                                            value=restaurants_dict[i]['name'] +
                                            "_評論"),
                                        CardAction(
                                            type="imBack",
                                            title="加入我的最愛",
                                            value=restaurants_dict[i]['name'] +
                                            "_加入最愛")
                                    ])))
                        if (i == 9):
                            break

                    message = MessageFactory.carousel(restaurants_list)
                    await turn_context.send_activity(message)

            elif ('_$' in turn_context.activity.text):
                money_status = 1
                msg = turn_context.activity.text
                # 判斷price_level
                if ('_$$' in turn_context.activity.text):
                    money_status = 2
                    msg = msg.replace('_$$', '')
                elif ('_$$$' in turn_context.activity.text):
                    money_status = 3
                    msg = msg.replace('_$$$', '')
                msg = msg.replace('_$', '')
                msg = msg.replace('_', '')
                msg = msg.replace('我想吃', '')
                msg = msg.replace('我想喝', '')
                msg = msg.replace('我要吃', '')
                msg = msg.replace('我要喝', '')
                msg = msg.replace('我在', '')
                if (intent == '使用者食物類別'):
                    restaurants_dict = googlemaps_API("北車", money_status, msg)
                    print(restaurants_dict)
                elif (intent == '使用者地理位置'):
                    restaurants_dict = googlemaps_API(msg, money_status, '')
                    print(restaurants_dict)
                print('money_status:', money_status)
                print('msg:', msg)
                # 沒有餐廳的狀況
                if not restaurants_dict:
                    message = "您附近沒有相對應的餐廳可以推薦呦,輸入『我想吃...』來繼續👀"
                    await turn_context.send_activity(message)
                else:
                    # good_list = opendata_earth.get_earth_data()
                    # vegetable_list = opendata_vegetable.get_vege_data()

                    restaurants_list = []
                    for i in range(len(restaurants_dict)):
                        restaurants_list.append(
                            CardFactory.hero_card(
                                HeroCard(
                                    title=restaurants_dict[i]['name'],
                                    text='推薦指數 : ' +
                                    str(restaurants_dict[i]['rating']) + " 👍",
                                    images=[
                                        CardImage(url=show_photo(
                                            restaurants_dict[i]
                                            ['photo_reference']))
                                    ],
                                    buttons=[
                                        CardAction(
                                            type="openUrl",
                                            title="地圖",
                                            value=
                                            "https://www.google.com/maps/search/?api=1&query="
                                            + str(restaurants_dict[i]
                                                  ['location_x']) + "," +
                                            str(restaurants_dict[i]
                                                ['location_y']) +
                                            "&query_place_id=" +
                                            str(restaurants_dict[i]
                                                ['place_id'])),
                                        CardAction(
                                            type="imBack",
                                            title="點此看IG熱門貼文",
                                            value=restaurants_dict[i]['name'] +
                                            "_IG"),
                                        CardAction(
                                            type="imBack",
                                            title="點此看評論",
                                            value=restaurants_dict[i]['name'] +
                                            "_評論"),
                                        CardAction(
                                            type="imBack",
                                            title="加入我的最愛",
                                            value=restaurants_dict[i]['name'] +
                                            "_加入最愛")
                                    ])))

                        if (i == 9):
                            break

                    message = MessageFactory.carousel(restaurants_list)
                    await turn_context.send_activity(message)

            elif turn_context.activity.address != '':
                turn_context.send_activity(turn_context.activity.address)
            # non-type
            else:
                message = MessageFactory.carousel([
                    CardFactory.hero_card(
                        HeroCard(title="無法了解您的需求,美食公道伯在這邊先推薦幾家給您😉",
                                 subtitle='請選擇您想吃的類型: 😗',
                                 buttons=[
                                     CardAction(type="imBack",
                                                title="咖啡廳",
                                                value="我想吃咖啡廳"),
                                     CardAction(type="imBack",
                                                title="牛排",
                                                value="我想吃牛排"),
                                     CardAction(type="imBack",
                                                title="火鍋",
                                                value="我想吃火鍋"),
                                     CardAction(type="imBack",
                                                title="都不喜歡 😡",
                                                value="都不喜歡")
                                 ]))
                ])
                await turn_context.send_activity(message)
예제 #8
0
 def test_top_intent_returns_top_intent_if_score_equals_min_score(self):
     default_intent: str = LuisRecognizer.top_intent(self._mocked_results,
                                                     min_score=0.4)
     self.assertEqual(default_intent, "Greeting")
예제 #9
0
 def test_top_intent_throws_type_error_if_results_is_none(self):
     none_results: RecognizerResult = None
     with self.assertRaises(TypeError):
         LuisRecognizer.top_intent(none_results)
예제 #10
0
 def test_top_intent_returns_default_intent_if_provided(self):
     default_intent: str = LuisRecognizer.top_intent(
         self._mocked_results, "Test2", 0.5)
     self.assertEqual(default_intent, "Test2")
예제 #11
0
 def test_top_intent_returns_default_intent_if_min_score_is_higher(self):
     default_intent: str = LuisRecognizer.top_intent(self._mocked_results,
                                                     min_score=0.5)
     self.assertEqual(default_intent, "None")
예제 #12
0
 def test_top_intent_returns_top_intent(self):
     greeting_intent: str = LuisRecognizer.top_intent(self._mocked_results)
     self.assertEqual(greeting_intent, "Greeting")
예제 #13
0
    async def execute_luis_query(
            luis_recognizer: LuisRecognizer,
            turn_context: TurnContext) -> (Intent, object):
        """
        Returns an object with preformatted LUIS results for the bot's dialogs to consume.
        """
        result = None
        intent = None

        try:
            recognizer_result = await luis_recognizer.recognize(turn_context)
            intent = LuisRecognizer.top_intent(recognizer_result)
            #ajout ---
            #retult = recognizer_result.properties["recognizerResult"]
            #await turn_context.send_activity(f" Luis Result {recognizer_result.entities}")
            #-------------------------

            #intent = (
            #sorted(
            #recognizer_result.intents,
            #key=recognizer_result.intents.get,
            #reverse=True,
            #)[:1][0]
            #if recognizer_result.intents
            #else None
            #)

            if intent == Intent.BOOK_FLIGHT.value:
                result = BookingDetails()

                # We need to get the result from the LUIS JSON which at every level returns an array.
                to_entities = recognizer_result.entities.get("$instance",
                                                             {}).get("To", [])

                if len(to_entities) > 0:
                    result.destination = to_entities[0]["text"].capitalize()

                from_entities = recognizer_result.entities.get(
                    "$instance", {}).get("From", [])
                if len(from_entities) > 0:
                    result.origin = from_entities[0]["text"].capitalize()

                budget_entities = recognizer_result.entities.get(
                    "$instance", {}).get("budget", [])
                if len(budget_entities) > 0:
                    result.budget = budget_entities[0]["text"]

                # This value will be a TIMEX. And we are only interested in a Date so grab the first result and drop
                # the Time part. TIMEX is a format that represents DateTime expressions that include some ambiguity.
                # e.g. missing a Year.

                date_entities = recognizer_result.entities.get("str_date", [])
                if date_entities:
                    timex = date_entities[0]["datetime"][0]["timex"]
                    if timex:
                        datetime = timex[0].split("T")[0]
                        result.travel_date = datetime
                    else:
                        result.travel_date = None

                date_return_entities = recognizer_result.entities.get(
                    "$instance", {}).get("end_date", [])
                if date_return_entities:
                    timex = date_return_entities[0]["datetime"][0]["timex"]
                    if timex:
                        datetime = timex[0].split("T")[0]
                        result.return_date = datetime
                    else:
                        result.return_date = None

        except Exception as exception:
            print(exception)

        return intent, result
예제 #14
0
 async def on_message_activity(self, turn_context: TurnContext):
     result = await self.LuisReg.recognize(turn_context)
     entity_list = list(result.entities.keys())
     intent = LuisRecognizer.top_intent(result)
     l = ['it', 'management', 'softskills']
     i = ['listes_cours', 'listes_livre', 'listes_formation']
     a = ['Acheter_livre', 'suivre_cours', 'suivre_formation']
     if (intent == "None"):
         await turn_context.send_activity(
             "j'ai pas compris ! réenvoyer votre question s'il vous plait!")
     if (result.text.lower() in l and intent == "Departement"):
         await turn_context.send_activity(
             "ceci est un domaine disponible chez nous pour e-learning")
     elif (intent == "domaine"):
         if (result.text.lower() in l):
             await turn_context.send_activity(
                 "ceci est un domaine disponible chez nous pour e-learning")
         elif (entity_list != ['$instance']):
             await turn_context.send_activity(
                 f"{result.entities[entity_list[1]][0]} est un domaine du {entity_list[1]}"
             )
         else:
             await turn_context.send_activity("Comment je peux vous aider ?"
                                              )
     elif (intent == "services"):
         await turn_context.send_activity(
             "on est une librairie en ligne , vente des livres , des formation à attendre et des cours à suivre dans plusieurs domaines . je suis votre assistant fidéle"
         )
     elif (intent in i):
         test = getList(intent)
         url = "https://projetaziz.sharepoint.com/sites/library/SitePages/" + test + ".aspx"
         await turn_context.send_activity(
             f"vous pouvez voir {intent} en visitant le lien suivant : " +
             url)
     elif (intent in a):
         if (entity_list == ['$instance']):
             await turn_context.send_activity(
                 f"c'est compris que vous voulez {intent} mais spécifiez plus un exemple du domaine du service s'il vous plait; i.e IT(java,cisco,security...) / Management(leading,RH) / Softskills(communication,gestion du stress...)"
             )
         else:
             for i in entity_list:
                 if (i != '$instance'):
                     st = ' '.join([
                         str(elem) for elem in result.entities[i]
                     ]).replace(' ', '_')
                     if (st in l):
                         await turn_context.send_activity(
                             f"c'est compris que vous voulez {intent} mais spécifiez plus un exemple du "
                             + st)
                     else:
                         action = intent.split("_")
                         test = getData(intent, st)
                         if (len(test) != 1):
                             if (test[0] == "Livre"):
                                 image = "https://i.pinimg.com/474x/9a/12/c8/9a12c8fe2d0755250f57da8aa2cd9787.jpg"
                             elif (test[0] == "Cours"):
                                 image = "https://png.pngtree.com/png-vector/20190719/ourlarge/pngtree-e-learning-line-icon-online-internet-education-symbol-graduation-png-image_1550378.jpg"
                             elif (test[0] == "Formation"):
                                 image = "https://png.pngtree.com/png-vector/20190719/ourlarge/pngtree-e-learning-line-icon-online-internet-education-symbol-graduation-png-image_1550378.jpg"
                             await turn_context.send_activity(
                                 "voici les " + action[1] +
                                 " que vous cherchez :")
                             k = 1
                             while (k < len(test)):
                                 url = CONFIG.PRODUCT_URL + str(
                                     test[k]['id']
                                 ) + "&type=SP.Data." + test[0] + "ListItem"
                                 reply = self.create_adaptive_card_attachment(
                                     url, test[k]['Title'], image,
                                     test[k]['Type'], test[k]['Price'],
                                     test[k]['Description'],
                                     test[k]['Author'])
                                 response = MessageFactory.attachment(reply)
                                 await turn_context.send_activity(response)
                                 k = k + 1
                         else:
                             if (action[1] == "formation"):
                                 await turn_context.send_activity(
                                     "la " + action[1] +
                                     " que vous souhaitez commander n'est disponible chez nous maintenant"
                                 )
                             else:
                                 await turn_context.send_activity(
                                     "le " + action[1] +
                                     " que vous souhaitez commander n'est disponible chez nous maintenant"
                                 )
예제 #15
0
    async def act_step(self,
                       step_context: WaterfallStepContext) -> DialogTurnResult:
        if not self.recognizer.is_configured:
            await step_context.context.send_activity(
                MessageFactory.text(
                    "NOTE: LUIS is not configured. To enable all capabilities, add 'LuisAppId', 'LuisAPIKey' and "
                    "'LuisAPIHostName' to the appsettings.json file.",
                    input_hint=InputHints.ignoring_input,
                ))

        # Get the intent and the sentiment
        luis_result = await self.recognizer.recognize(step_context.context)
        intent = LuisRecognizer.top_intent(luis_result)
        entities = luis_result.entities
        sentiment = luis_result.properties["sentiment"]["label"]
        message = ""
        options = {
            "genre": "",
            "confirmation": "",
            "sentiment": "",
            "songs": self.songs
        }

        print(intent)

        # If the user greeted back
        if intent == "Greetings":
            print("Got a greeting")
            if sentiment == "neutral":
                return await step_context.begin_dialog(
                    self.recommendation_dialog_id, options)
            elif sentiment == "positive":
                message_text = "That's great to hear!"
                prompt_message = MessageFactory.text(
                    message_text, message_text, InputHints.expecting_input)
                await step_context.context.send_activity(prompt_message)

                options["genre"] = "pop"
                return await step_context.begin_dialog(
                    self.recommendation_dialog_id, options)
            elif sentiment == "negative":
                message_text = "Sorry to hear that."
                prompt_message = MessageFactory.text(
                    message_text, message_text, InputHints.expecting_input)
                # Send the user a consent message
                await step_context.context.send_activity(prompt_message)

                # Set the genre to classical and begin recommendation dialogue
                options["genre"] = "classical"
                return await step_context.begin_dialog(
                    self.recommendation_dialog_id, options)
        elif intent == "Recommendation":
            if "genre" in entities:
                options["genre"] = entities["genre"][0]
            return await step_context.begin_dialog(
                self.recommendation_dialog_id, options)
        else:
            didnt_understand_text = (
                "Sorry, I understand you. Please ask me about what kind of music you're looking for"
            )
            didnt_understand_message = MessageFactory.text(
                didnt_understand_text, didnt_understand_text,
                InputHints.ignoring_input)
            await step_context.context.send_activity(didnt_understand_message)

        return await step_context.next(None)