async def _recognize_token(self, context: TurnContext) -> PromptRecognizerResult: token = None if OAuthPrompt._is_token_response_event(context): token = context.activity.value elif OAuthPrompt._is_teams_verification_invoke(context): code = context.activity.value["state"] try: token = await self.get_user_token(context, code) if token is not None: await context.send_activity( Activity(type="invokeResponse", value=InvokeResponse(200))) else: await context.send_activity( Activity(type="invokeResponse", value=InvokeResponse(404))) except Exception: context.send_activity( Activity(type="invokeResponse", value=InvokeResponse(500))) elif context.activity.type == ActivityTypes.message and context.activity.text: match = re.match(r"(?<!\d)\d{6}(?!\d)", context.activity.text) if match: token = await self.get_user_token(context, match[0]) return (PromptRecognizerResult(True, token) if token is not None else PromptRecognizerResult())
async def on_teams_messaging_extension_query( self, turn_context: TurnContext, query: MessagingExtensionQuery): search_query = str(query.parameters[0].value).strip() if search_query == "": turn_context.send_activity( MessageFactory.text( "You cannot enter a blank string for the search")) return search_results = self._get_search_results(search_query) attachments = [] for obj in search_results: hero_card = HeroCard(title=obj["name"], tap=CardAction(type="invoke", value=obj)) attachment = MessagingExtensionAttachment( content_type=CardFactory.content_types.hero_card, content=HeroCard(title=obj["name"]), preview=CardFactory.hero_card(hero_card), ) attachments.append(attachment) return MessagingExtensionResponse( compose_extension=MessagingExtensionResult( type="result", attachment_layout="list", attachments=attachments))
async def on_prompt(self, turn_context: TurnContext, state: Dict[str, object], options: PromptOptions, is_retry: bool): if not turn_context: raise TypeError( 'TextPrompt.on_prompt(): turn_context cannot be None.') if not options: raise TypeError('TextPrompt.on_prompt(): options cannot be None.') if is_retry == True and options.retry_prompt != None: prompt = turn_context.send_activity(options.retry_prompt) else: if options.prompt != None: turn_context.send_activity(options.prompt)
def on_post(self, req, resp): try: auth_header = req.headers['AUTHORIZATION'] except KeyError: resp.status = falcon.HTTP_403 return if req.content_length: activity = Activity().deserialize(json.load(req.stream)) sync_run(self.adapter.authenticate_request(activity, auth_header)) commandline = activity.text conversation = activity.conversation context = TurnContext(self.adapter, activity) commandline = commandline.replace("<at>{}</at>".format(self.name), "") sync_run( context.send_activity(self.bot.command_dispatcher(commandline)))
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)
async def on_teams_messaging_extension_query( self, turn_context: TurnContext, query: MessagingExtensionQuery, # pylint: disable=unused-argument ): search_query = str(query.parameters[0].value).strip() user_configuration = await self.user_config_property.get( turn_context, "UserConfiguration") if user_configuration is not None and "email" in user_configuration: # When the Bot Service Auth flow completes, the action.State will contain # a magic code used for verification. magic_code = "" if query.state is not None: magic_code = query.state token_response = await turn_context.adapter.get_user_token( turn_context, self.connection_name, magic_code) if token_response is None or token_response.token is None: # There is no token, so the user has not signed in yet. # Retrieve the OAuth Sign in Link to use in the MessagingExtensionResult Suggested Actions sign_in_link = await turn_context.adapter.get_oauth_sign_in_link( turn_context, self.connection_name) return MessagingExtensionResponse( compose_extension=MessagingExtensionResult( type="auth", suggested_actions=MessagingExtensionSuggestedAction( actions=[ CardAction( type="openUrl", value=sign_in_link, title="Bot Service OAuth", ) ]), )) # User is signed in, so use their token to search email via the Graph Client client = SimpleGraphClient(token_response.token) search_results = await client.search_mail_inbox(search_query) # Here we construct a ThumbnailCard for every attachment, and provide a HeroCard which will be # displayed if the user selects that item. attachments = [] for message_meta in search_results: message = message_meta["_source"] message_from = message["from"] if "from" in message else None if message_from: subtitle = (f"{message_from['emailAddress']['name']}," f"<{message_from['emailAddress']['address']}>") else: subtitle = "" hero_card = HeroCard( title=message["subject"] if "subject" in message else "", subtitle=subtitle, text=message["bodyPreview"] if "bodyPreview" in message else "", ) thumbnail_card = CardFactory.thumbnail_card( ThumbnailCard( title=subtitle, subtitle=message["subject"], images=[ CardImage( url= "https://botframeworksamples.blob.core.windows.net/samples" "/OutlookLogo.jpg", alt="Outlook Logo", ) ], )) attachment = MessagingExtensionAttachment( content_type=CardFactory.content_types.hero_card, content=hero_card, preview=thumbnail_card, ) attachments.append(attachment) return MessagingExtensionResponse( compose_extension=MessagingExtensionResult( type="result", attachment_layout="list", attachments=attachments)) # The user configuration is NOT set to search Email. if search_query is None: turn_context.send_activity( MessageFactory.text( "You cannot enter a blank string for the search")) return search_results = self._get_search_results(search_query) attachments = [] for obj in search_results: hero_card = HeroCard(title=obj["name"], tap=CardAction(type="invoke", value=obj)) attachment = MessagingExtensionAttachment( content_type=CardFactory.content_types.hero_card, content=HeroCard(title=obj["name"]), preview=CardFactory.hero_card(hero_card), ) attachments.append(attachment) return MessagingExtensionResponse( compose_extension=MessagingExtensionResult( type="result", attachment_layout="list", attachments=attachments))