def replySearch(self, request, isback=False): if (isback == False): userId = request.data['events'][0]['source']['userId'] try: oldnotify_user = SearchLog.objects.get(user_id=userId) print(userId + "<使用者查詢過>") messagetext = 'https://www.google.com/maps/search/?api=1&query={0},{1}'.format( oldnotify_user.latitude, oldnotify_user.longitude) except SearchLog.DoesNotExist: messagetext = "請選擇您的查詢條件" else: messagetext = "請選擇您的查詢條件" line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN) line_bot_api.reply_message( request.data['events'][0]['replyToken'], TextSendMessage( text=messagetext, quick_reply=QuickReply(items=[ QuickReplyButton(action=LocationAction(label="送出地標查詢", )), QuickReplyButton(action=PostbackAction( label="選擇條件", data="Condition", )), QuickReplyButton(action=PostbackAction( label="Gogoro電池站查詢", data="Gogoro", )), ])))
def quick_reply(token): items = [QuickReplyButton(action=LocationAction(label='位置情報を送信する', text="位置情報を送信する"))] text = '位置情報を送信して下さい!\n最寄駅とその前後の駅を設定します。\n位置情報を送り直すことで再設定することができます!' messages = TextSendMessage(text=text, quick_reply=QuickReply(items=items)) line_bot_api.reply_message(token, messages=messages)
def handle_text_message(event): text = event.message.text if 'อากาศ' == text or 'weather' == text.lower(): quick_reply = QuickReply(items=[ QuickReplyButton(action=LocationAction(label='Send Location')), QuickReplyButton( action=PostbackAction(label='Tokyo Weather', data='weather=tokyo', display_text='Tokyo Weather')), QuickReplyButton( action=PostbackAction(label='Seoul Weather', data='weather=seoul', display_text='Seoul Weather')), QuickReplyButton( action=PostbackAction(label='London Weather', data='weather=london', display_text='London Weather')) ]) reply_message = TextSendMessage( text="Let me know your location or place", quick_reply=quick_reply) line_bot_api.reply_message(event.reply_token, messages=reply_message) if 'weather in ' in text.lower(): weather_data = weather.get_weather_by_place(text.split(" ")[2]) if isinstance(weather_data, str): line_bot_api.reply_message(event.reply_token, TextSendMessage(text=weather_data)) else: bubble_container = weather.get_weather_message(weather_data) line_bot_api.reply_message( event.reply_token, FlexSendMessage(alt_text="Weather Forecast", contents=bubble_container))
def test_location(self): arg = { 'label': 'Location' } self.assertEqual( self.serialize_as_dict(arg, type=self.LOCATION), LocationAction(**arg).as_json_dict() )
def replySearchForGogoro(self, request): line_bot_api = LineBotApi(LINE_CHANNEL_ACCESS_TOKEN) line_bot_api.reply_message( request.data['events'][0]['replyToken'], TextSendMessage( text="請送出您目前的地標", quick_reply=QuickReply(items=[ QuickReplyButton(action=LocationAction(label="送出地標查詢", )), QuickReplyButton(action=PostbackAction( label="回上一頁", data="ok", )), ])))
def food_quick_reply(): message = TextSendMessage( text="請選擇功能", quick_reply=QuickReply(items=[ QuickReplyButton( action=MessageAction(label="時段推薦", text="/時段推薦")), #回傳文字 QuickReplyButton(action=LocationAction(label="定位搜尋")), #傳回定位資訊 QuickReplyButton(action=URIAction( label="菜單搜尋", uri='https://liff.line.me/1655990146-4dZdvw9P', alt_uri='https://liff.line.me/1655990146-4dZdvw9P')), #網頁連結 ])) return message
def GPS(event): if event.message.text == "GPS": try: line_bot_api.reply_message( event.reply_token, TextSendMessage( text='你在哪裡?', quick_reply=QuickReply(items=[ QuickReplyButton(action=LocationAction(label="定位")) ]))) except Exception as msg: print(msg) return True else: return False
def arrival_locationpicker(): return FlexSendMessage("目的地設定", BubbleContainer( size="mega", body=BoxComponent( layout="vertical", contents=[ TextComponent( text="目的地を設定してください", size="sm" ), ] ), styles=BubbleStyle(body=BlockStyle(background_color="#ffffff")) ), quickreply=QuickReply(items=[ QuickReplyButton(action=LocationAction(label="label")) ]))
def handle_text_message(event): # reply_text_message = TextSendMessage(event.message.text) # 創造一個QuickReplyButton text_quickreply = QuickReplyButton( action=MessageAction(label="小馮怎麼叫", text="AAA")) location_quickreply = QuickReplyButton(action=LocationAction( label="where are you?")) # 創造一個QuickReplyButton array,放入剛剛的Button quick_reply_array = QuickReply( items=[text_quickreply, location_quickreply]) reply_text_message = TextSendMessage(event.message.text, quick_reply=quick_reply_array) line_bot_api.reply_message(event.reply_token, reply_text_message)
def hander_postback(event): global wanna_eat text=event.postback.data if text=='アメちゃん': line_bot_api.reply_message(event.reply_token,ImageSendMessage( original_content_url='https://1.bp.blogspot.com/-ZELov-QvHaU/UVWMfIiV3bI/AAAAAAAAPIM/xxWcxLdHrwk/s1600/candy.png', preview_image_url='https://1.bp.blogspot.com/-ZELov-QvHaU/UVWMfIiV3bI/AAAAAAAAPIM/xxWcxLdHrwk/s1600/candy.png' )) elif text=='お土産': survenier=ButtonsTemplate( text='お土産ならここやな', actions=[ URIAction(label='お土産', uri='line://app/1598486025-lMb5nvo4'), ]) line_bot_api.reply_message(event.reply_token,TemplateSendMessage(alt_text='お土産',template=survenier)) elif text=='作り方': how_to_make=ButtonsTemplate( text='このホームページ通りにやったらできるで。\nしらんけど。', actions=[ URIAction(label='作り方', uri='https://cookpad.com/'), ]) line_bot_api.reply_message(event.reply_token,TemplateSendMessage(alt_text='作り方',template=how_to_make)) elif text=='お店': #検索ボットを利用 restaurant=ButtonsTemplate( text='今の場所から近いお店伝えるで。ええか?', actions=[ LocationAction(label='お願い'), ]) template_message=TemplateSendMessage(alt_text='位置情報送信しますか?',template=restaurant) line_bot_api.reply_message(event.reply_token,template_message) #データの取得方法を探す。 elif text=='串カツ': wanna_eat='串カツ' line_bot_api.push_message(event.source.user_id,TextSendMessage(text='ごめん、ちょっと待ってな。')) elif text=='肉まん': wanna_eat='肉まん' line_bot_api.push_message(event.source.user_id,TextSendMessage(text='ごめん、ちょっと待ってな。')) elif text=='お好み焼き': wanna_eat='お好み焼き' line_bot_api.push_message(event.source.user_id,TextSendMessage(text='ごめん、ちょっと待ってな。')) elif text=='たこ焼き': wanna_eat='たこ焼き' line_bot_api.push_message(event.source.user_id,TextSendMessage(text='ごめん、ちょっと待ってな。')) elif text=='ありがとう': line_bot_api.reply_message(event.reply_token,TextSendMessage(text='おおきに'))
def PostBack(event): with open('develop/Ancate_content.json') as f: data = json.loads(f.read()) with open('develop/quickreply.json') as f: data2 = f.read() USER = { 'Id': event.source.user_id, 'Name': line_bot_api.get_profile(event.source.user_id).display_name, 'reply_token': event.reply_token } messages = TextSendMessage( text='Sample', quick_reply=QuickReply(items=[ QuickReplyButton(action=MessageAction(label="label", text="text")), QuickReplyButton(action=CameraAction(label="Camera")), QuickReplyButton(action=LocationAction(label="Location")), QuickReplyButton(action=DatetimePickerAction( label="Datetime", mode="time", data="test")) ])) line_bot_api.push_message(USER['Id'], messages=messages) return
def handle_text_message(event): text = event.message.text print_source(event) if 'aqi' == text.lower(): line_bot_api.reply_message( event.reply_token, messages=TextSendMessage( text='Please share your location to get an accurate AQI krub', quick_reply=QuickReply(items=[ QuickReplyButton(action=LocationAction( label='Share Location')) ]))) if 'มองบน' in text.lower(): image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn( image_url= 'https://media.giphy.com/media/5Wi5ydRYRM28q9Gvyv/giphy.gif', action=MessageAction(label='มองบน', text='มองบน')) ]) line_bot_api.reply_message( event.reply_token, TemplateSendMessage(alt_text='มองบนเรยจ้า', template=image_carousel_template)) if 'lineqa' in text.lower(): image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn( image_url= 'https://media.giphy.com/media/4VUugEkI9a9DsKTmW1/giphy.gif', action=MessageAction(label='Daebak', text='대박!')) ]) line_bot_api.reply_message( event.reply_token, TemplateSendMessage(alt_text='대박!', template=image_carousel_template)) if 'อากาศ' == text or 'weather' == text.lower(): quick_reply = QuickReply(items=[ QuickReplyButton(action=LocationAction(label='Send Location')), QuickReplyButton( action=PostbackAction(label='Tokyo Weather', data='weather=tokyo', display_text='Tokyo Weather')), QuickReplyButton( action=PostbackAction(label='Seoul Weather', data='weather=seoul', display_text='Seoul Weather')), QuickReplyButton( action=PostbackAction(label='London Weather', data='weather=london', display_text='London Weather')) ]) reply_message = TextSendMessage( text="Let me know your location or place", quick_reply=quick_reply) line_bot_api.reply_message(event.reply_token, messages=reply_message) m = re.match('weather in (.*)', text.lower()) if m is not None: place_name = m.group(1) weather_data = weather.get_weather_data(place_name) latlng_data, address = weather.get_latlng_from_place_name(place_name) # weather_aqi_data = weather.get_weather_aqi_by_place_name(place_name) weather_aqi_station_id = weather_aqi.get_nearest_station( latlng_data['lat'], latlng_data['lng']) weather_aqi_data = weather_aqi.get_aqi_data(weather_aqi_station_id) if isinstance(weather_data, str): line_bot_api.reply_message(event.reply_token, TextSendMessage(text=weather_data)) else: messages = [] weather_msg = weather.get_weather_message(weather_data) messages.append( FlexSendMessage(alt_text="Weather Forecast", contents=weather_msg)) if weather_aqi_data is not None: weather_aqi_msg = weather_aqi.get_aqi_message(weather_aqi_data) messages.append( FlexSendMessage(alt_text="Air Quality Index", contents=weather_aqi_msg)) # weather_aqi_msg = weather.get_weather_aqi_message(weather_aqi_data) # messages.append(weather_aqi_msg) # weather.get_weather_aqi_message_v2(weather_aqi_data) # weather_aqi_msg_v2 = weather.get_weather_aqi_message_v2(weather_aqi_data) # messages.append(weather_aqi_msg_v2) line_bot_api.reply_message(event.reply_token, messages=messages) n = re.match('flight (.*)', text.lower()) if n is not None: latest_flight = flight_api.get_latest_flight(n.group(1).upper()) if latest_flight is not None: flight_metadata = flight_api.get_flight_metadata( latest_flight['flight_number'], latest_flight['adshex']) if flight_metadata['success'] is True: flight_bubble = flight_api.create_flight_message( latest_flight['flight_number'], latest_flight['adshex'], flight_metadata['payload']) messages = [] messages.append( FlexSendMessage(alt_text="Flight Information", contents=flight_bubble)) line_bot_api.reply_message(event.reply_token, messages) line_bot_api.reply_message( event.reply_token, TextSendMessage( text= 'Sorry, I can\'t find your flight: {}. Please try another flight number' .format(n.group(1).upper()))) p = re.match('(^[A-Z]{3}-[A-Z]{3}$)', text.upper()) if p is not None: text = p.group(1).upper() origin = text.split('-')[0] destination = text.split('-')[1] flight_route_data = flight_api.get_flight_by_route(origin, destination) if flight_route_data is not None: carouesel_container = flight_api.create_flight_route_message( flight_route_data) line_bot_api.reply_message( event.reply_token, FlexSendMessage(alt_text="Flight {0} Route Info".format(text), contents=carouesel_container)) line_bot_api.reply_message( event.reply_token, TextSendMessage( text='Sorry, There is no flight for "{}" route.'.format(text))) q = re.match('airport (.*)', text.lower()) if q is not None: text = q.group(1).lower() airports = flight_api.get_airport_code(text) if airports is not None: quick_reply_items = [] for airport in airports: airport_name = ( airport['title'][:14] + ' ({0})'.format(airport['url'].split('/')[-1])) if len( airport['title'] ) > 14 else airport['title'] + ' ({0})'.format( airport['url'].split('/')[-1]) quick_reply_items.append({ "type": "action", "action": { "type": "postback", "label": airport_name, "data": "airport={0}".format(airport['url'].split('/')[-1]) } }) line_bot_api.reply_message( event.reply_token, TextSendMessage( text='Here are possible airports', quick_reply=QuickReply(items=quick_reply_items)))
def handle_text_message(event): text = event.message.text if text == 'Hello': line_bot_api.reply_message(event.reply_token, TextSendMessage('Hi There!!')) elif text.lower() == 'getridch': carousel_template = CarouselTemplate(columns=[ CarouselColumn( text='What you can do', title='Seller', actions=[ CameraAction(label='Take a photo'), # CameraRollAction(label='Choose a photo'), ]), CarouselColumn( text='What you can do', title='Buyer', actions=[ PostbackAction(label='Get near by trash', data='getNearbyLocation', text='Show location'), # MessageAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage(alt_text='Carousel alt text', template=carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'menu': line_bot_api.reply_message( event.reply_token, TextSendMessage( text='Quick reply', quick_reply=QuickReply(items=[ QuickReplyButton(action=PostbackAction(label="getridch", data="getridch")), QuickReplyButton(action=CameraAction(label="Camera")), QuickReplyButton(action=CameraRollAction( label="Camera Roll")), QuickReplyButton(action=LocationAction(label="Location")), QuickReplyButton(action=DatetimePickerAction( label="Date", data="data3", mode="date")), ]))) elif text == 'profile': if isinstance(event.source, SourceUser): profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message( event.reply_token, TextSendMessage(text='Display name: ' + profile.user_id)) else: line_bot_api.reply_message( event.reply_token, TextSendMessage( text="Bot can't use profile API without user ID")) elif text == 'flex': bubble = BubbleContainer( direction='ltr', hero=ImageComponent(url='https://example.com/cafe.jpg', size='full', aspect_ratio='20:13', aspect_mode='cover', action=URIAction(uri='http://example.com', label='label')), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='Brown Cafe', weight='bold', size='xl'), # review BoxComponent( layout='baseline', margin='md', contents=[ IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/grey_star.png'), IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/gold_star.png'), IconComponent( size='sm', url='https://example.com/grey_star.png'), TextComponent(text='4.0', size='sm', color='#999999', margin='md', flex=0) ]), # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents=[ BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Place', color='#aaaaaa', size='sm', flex=1), TextComponent(text='Shinjuku, Tokyo', wrap=True, color='#666666', size='sm', flex=5) ], ), BoxComponent( layout='baseline', spacing='sm', contents=[ TextComponent(text='Time', color='#aaaaaa', size='sm', flex=1), TextComponent( text="10:00 - 23:00", wrap=True, color='#666666', size='sm', flex=5, ), ], ), ], ) ], ), footer=BoxComponent( layout='vertical', spacing='sm', contents=[ # callAction, separator, websiteAction SpacerComponent(size='sm'), # callAction ButtonComponent( style='link', height='sm', action=URIAction(label='CALL', uri='tel:000000'), ), # separator SeparatorComponent(), # websiteAction ButtonComponent(style='link', height='sm', action=URIAction( label='WEBSITE', uri="https://example.com")) ]), ) message = FlexSendMessage(alt_text="hello", contents=bubble) line_bot_api.reply_message(event.reply_token, message) elif text == 'confirm': confirm_template = ConfirmTemplate(text='Do it?', actions=[ MessageAction(label='Yes', text='Yes!'), MessageAction(label='No', text='No!') ]) template_message = TemplateSendMessage(alt_text='Confirm alt text', template=confirm_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'list': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='What you can do', title='Seller', actions=[ CameraAction(label='Take a photo'), PostbackAction(label='ping', data='ping') ]), CarouselColumn(text='Options', title='Buyer', actions=[ PostbackAction(label='Test ping with text', data='ping', text='ping'), MessageAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage(alt_text='Carousel alt text', template=carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'KBTG': confirm_template = ConfirmTemplate(text='Confirm Address : KBTG ?', actions=[ PostbackAction( label='Confirm', data='cfaddress'), PostbackAction(label='cancel', data='getridch', text='cancel'), ]) template_message = TemplateSendMessage(alt_text='Confirm alt text', template=confirm_template) line_bot_api.reply_message(event.reply_token, template_message)
def test_push_text_message_with_quick_reply(self): responses.add(responses.POST, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push', json={}, status=200) self.tested.push_message( 'to', TextSendMessage( text='Hello, world', quick_reply=QuickReply(items=[ QuickReplyButton(image_url='https://example.com', action=PostbackAction(label="label1", data="data1")), QuickReplyButton( action=MessageAction(label="label2", text="text2")), QuickReplyButton(action=DatetimePickerAction( label="label3", data="data3", mode="date")), QuickReplyButton(action=CameraAction(label="label4")), QuickReplyButton(action=CameraRollAction(label="label5")), QuickReplyButton(action=LocationAction(label="label6")), ]))) request = responses.calls[0].request self.assertEqual(request.method, 'POST') self.assertEqual( request.url, LineBotApi.DEFAULT_API_ENDPOINT + '/v2/bot/message/push') self.assertEqual( json.loads(request.body), { "to": "to", "messages": [{ "type": "text", "text": "Hello, world", "quickReply": { "items": [ { "type": "action", "imageUrl": "https://example.com", "action": { "type": "postback", "label": "label1", "data": "data1", } }, { "type": "action", "action": { "type": "message", "label": "label2", "text": "text2", } }, { "type": "action", "action": { "type": "datetimepicker", "label": "label3", "data": "data3", "mode": "date", } }, { "type": "action", "action": { "type": "camera", "label": "label4", } }, { "type": "action", "action": { "type": "cameraRoll", "label": "label5", } }, { "type": "action", "action": { "type": "location", "label": "label6", } }, ] } }] })
def create_response(self): return TextSendMessage( text=self._context['text'], quick_reply=QuickReply(items=[ QuickReplyButton(action=LocationAction(label='location')) ]))
def handle_message(event): input_msg = event.message.text # ランダム : ランダムに1店舗紹介する。 # テキストで返して、その後に2通目のメッセージで詳細を見ますか?でyesならリッチメッセージを送る仕掛け欲しい。postbackactionじゃな。 # if input_msg in ["ランダム", "random"]: # output_msg = random.choice(restaurant_names) # line_bot_api.reply_message( # event.reply_token, # TextSendMessage(text=output_msg)) # ちかく:近くのおすすめ店舗を紹介する。 if input_msg in ["近くのお店", "ちかく", "近く", "near"]: line_bot_api.reply_message( event.reply_token, TextSendMessage( text='位置情報から近くの店を検索する', quick_reply=QuickReply(items=[ QuickReplyButton(action=LocationAction(label="位置情報の画面へ")), ]))) elif input_msg in ["お気に入りからランダム", "ランダム"]: conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format( user, password, host, port_db, database)) cur = conn.cursor() df = pd.read_sql( "SELECT favorite_restaurant_name FROM favorite_restaurants WHERE user_id = '{}'" .format(event.source.user_id), con=conn) favorite_restaurant_names = list(df.favorite_restaurant_name.values) conn.commit() cur.close() conn.close() num_lists = range(len(favorite_restaurant_names)) if len(num_lists) > 10: favorite_restaurant_nums = random.sample(num_lists, k=6) #仕様上10個まで。 else: favorite_restaurant_nums = random.sample(num_lists, k=len(num_lists)) favorite_restaurants = [] for favorite_restaurant_num in favorite_restaurant_nums: for restaurant in restaurants: if favorite_restaurant_names[ favorite_restaurant_num] == restaurant.name: favorite_restaurants.append(restaurant) favorite_carousel_columns = [] for favorite_restaurant in favorite_restaurants: if json.loads(favorite_restaurant.image_url.replace( '\'', '"'))["shop_image1"] != "": image_url = json.loads( favorite_restaurant.image_url.replace('\'', '"'))["shop_image1"] else: image_url = img_restaurant_default try: if json.loads(favorite_restaurant.pr.replace( '\'', '"'))["pr_short"] != "": pr = json.loads(favorite_restaurant.pr.replace( '\'', '"'))["pr_short"][:60] else: pr = "おすすめのお店です" except JSONDecodeError: pr = "おすすめのお店です" favorite_carousel_column = CarouselColumn( thumbnail_image_url=image_url, title=favorite_restaurant.name, text=pr, actions=[ URIAction(label='ぐるなびへ', uri=favorite_restaurant.url_mobile), MessageAction(label='位置情報をみる', text='位置情報 ' + favorite_restaurant.name), MessageAction( label="お気に入りから削除する", text="お気に入り削除" + ' ' + favorite_restaurant.name) # event.source.user_id ]) favorite_carousel_columns.append(favorite_carousel_column) if len(favorite_carousel_columns) > 0: line_bot_api.reply_message( event.reply_token, TemplateSendMessage(alt_text='Carousel template', template=CarouselTemplate( columns=favorite_carousel_columns))) else: output_msg = "まだお気に入りがありません。" line_bot_api.reply_message(event.reply_token, TextSendMessage(text=output_msg)) elif input_msg in ["お気に入り一覧", "一覧"]: conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format( user, password, host, port_db, database)) cur = conn.cursor() df = pd.read_sql( "SELECT favorite_restaurant_name FROM favorite_restaurants WHERE user_id = '{}'" .format(event.source.user_id), con=conn) print(df) favorite_restaurant_names = list(df.favorite_restaurant_name.values) conn.commit() cur.close() conn.close() if len(favorite_restaurant_names) > 0: output_msg = "" for favorite_restaurant_name in favorite_restaurant_names: output_msg += "•" + favorite_restaurant_name + "\n" output_msg = output_msg[:-1] else: output_msg = "まだお気に入りがありません。" line_bot_api.reply_message(event.reply_token, TextSendMessage(text=output_msg)) elif input_msg in ["ランキング"]: conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format( user, password, host, port_db, database)) cur = conn.cursor() df = pd.read_sql( "SELECT count(*) as favorites, favorite_restaurant_name FROM favorite_restaurants GROUP BY favorite_restaurant_name", con=conn) df = df.sort_values('favorites', ascending=False) restaurant_names = df["favorite_restaurant_name"].values.tolist() conn.commit() cur.close() conn.close() if len(restaurant_names) > 10: restaurant_names = restaurant_names[:10] ranking_restaurants = [] for restaurant_name in restaurant_names: for restaurant in restaurants: if restaurant.name == restaurant_name: ranking_restaurants.append(restaurant) ranking_carousel_columns = [] for i in range(len(ranking_restaurants)): # for ranking_restaurant in ranking_restaurants: if json.loads(ranking_restaurants[i].image_url.replace( '\'', '"'))["shop_image1"] != "": image_url = json.loads( ranking_restaurants[i].image_url.replace( '\'', '"'))["shop_image1"] else: image_url = img_restaurant_default try: if json.loads(ranking_restaurants[i].pr.replace( '\'', '"'))["pr_short"] != "": pr = str(i + 1) + "位: " + json.loads( ranking_restaurants[i].pr.replace( '\'', '"'))["pr_short"][:50] else: pr = str(i + 1) + "位: " + "おすすめのお店です" except JSONDecodeError: pr = str(i + 1) + "位: " + "おすすめのお店です" conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format( user, password, host, port_db, database)) cur = conn.cursor() cur.execute( "SELECT FROM favorite_restaurants WHERE user_id = '{}' and favorite_restaurant_name = '{}';" .format(event.source.user_id, ranking_restaurants[i].name)) if cur.fetchone() is None: label_favorite = "お気に入りに追加する" text_favorite = "お気に入り追加" else: # もうお気に入りされている。 label_favorite = "お気に入りから削除する" text_favorite = "お気に入り削除" conn.commit() cur.close() conn.close() ranking_carousel_column = CarouselColumn( thumbnail_image_url=image_url, title=ranking_restaurants[i].name, text=pr, actions=[ URIAction(label='ぐるなびへ', uri=ranking_restaurants[i].url_mobile), MessageAction(label='位置情報をみる', text='位置情報 ' + ranking_restaurants[i].name), MessageAction( label=label_favorite, text=text_favorite + ' ' + ranking_restaurants[i].name) # event.source.user_id ]) ranking_carousel_columns.append(ranking_carousel_column) if len(ranking_carousel_columns) > 0: line_bot_api.reply_message( event.reply_token, TemplateSendMessage(alt_text='Carousel template', template=CarouselTemplate( columns=ranking_carousel_columns))) elif input_msg in ["ジャンル別"]: quickreply_items = [] for category in restaurant_categories: item = QuickReplyButton( action=MessageAction(label=category, text=category + "のランキング")) quickreply_items.append(item) line_bot_api.reply_message( event.reply_token, TextSendMessage(text='ジャンルを選んで下さい。', quick_reply=QuickReply(items=quickreply_items))) elif "ランキング" in input_msg: # ジャンル別ランキング for category in restaurant_categories: if category in input_msg: # DBからそのジャンルのfavoritesランキングを抽出する。 conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format( user, password, host, port_db, database)) cur = conn.cursor() df_favorites = pd.read_sql( "SELECT count(*) as favorites, favorite_restaurant_name FROM favorite_restaurants GROUP BY favorite_restaurant_name", con=conn) df_favorites = df_favorites.rename( columns={'favorite_restaurant_name': 'name'}) df_restaurant2 = df_restaurant.copy(deep=False) df_favorites_ranking = pd.merge(df_restaurant2, df_favorites, on='name', how='outer') df_favorites_ranking = df_favorites_ranking[[ "name", "favorites", "category2", "image_url", "url", "url_mobile", "pr" ]] dict_category = { "和食": "Japanese", "韓国料理": "Korean", "中華": "Chinese", "イタリアン": "Italian", "カフェ": "Cafe", "居酒屋": "Izakaya", "ほか": "others" } df_favorites_ranking = df_favorites_ranking[ df_favorites_ranking["category2"] == dict_category[category]] df_favorites_ranking = df_favorites_ranking.sort_values( "favorites", ascending=False) if len(df_favorites_ranking) > 10: df_favorites_ranking = df_favorites_ranking[:9] recommend_carousel_columns = [] for index, row in df_favorites_ranking.reset_index().iterrows( ): print(index, row["name"], row.favorites) if json.loads(row.image_url.replace( '\'', '"'))["shop_image1"] != "": image_url = json.loads(row.image_url.replace( '\'', '"'))["shop_image1"] else: # image_url = "https://i.picsum.photos/id/10/200/300.jpg" image_url = img_restaurant_default try: if json.loads(row.pr.replace('\'', '"'))["pr_short"] != "": pr = str(index + 1) + "位: " + json.loads( row.pr.replace('\'', '"') )["pr_short"][: 40] # 60文字までという制限がある。オーバーの時は"..."を表示する。 else: pr = str( index + 1) + "位: " + "おすすめのお店です" # もう少し、良いメッセージにする。 except JSONDecodeError: pr = str(index + 1) + "位: " + "おすすめのお店です" cur.execute( "SELECT FROM favorite_restaurants WHERE user_id = '{}' and favorite_restaurant_name = '{}';" .format(event.source.user_id, row["name"])) if cur.fetchone() is None: label_favorite = "お気に入りに追加する" text_favorite = "お気に入り追加" else: # もうお気に入りされている。 # is not None label_favorite = "お気に入りから削除する" text_favorite = "お気に入り削除" recommend_carousel_column = CarouselColumn( thumbnail_image_url=image_url, title=row["name"], text=pr, actions=[ URIAction(label='ぐるなびへ', uri=row.url_mobile), MessageAction(label='位置情報をみる', text='位置情報 ' + row["name"]), MessageAction(label=label_favorite, text=text_favorite + ' ' + row["name"]) # event.source.user_id ]) recommend_carousel_columns.append( recommend_carousel_column) conn.commit() cur.close() conn.close() line_bot_api.reply_message( event.reply_token, TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate( columns=recommend_carousel_columns))) # おすすめ : カルーセルで数店舗紹介する。仕様上10店舗まで。 elif input_msg in [ "あなたへのおすすめ", "おすすめのお店", "おすすめ", "オススメ", "recommendation", "r", "re" ]: #一旦動く。 # recommend logic(ランダム) recommend_carousel_columns = [] # recommend_restaurant_nums = [10,0,11,12] recommend_restaurant_nums = [14, 15, 16, 17, 18, 19] # num_lists = range(0, len(restaurant_names)) # recommend_restaurant_nums = random.choices(num_lists, k=6) #仕様上10個まで。それ以上は、moreにすると良さそう。 conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format( user, password, host, port_db, database)) # conn = sqlite3.connect('restaurants.db') cur = conn.cursor() for i in recommend_restaurant_nums: if json.loads(restaurants[i].image_url.replace( '\'', '"'))["shop_image1"] != "": image_url = json.loads(restaurants[i].image_url.replace( '\'', '"'))["shop_image1"] else: # image_url = "https://i.picsum.photos/id/10/200/300.jpg" image_url = img_restaurant_default try: if json.loads(restaurants[i].pr.replace( '\'', '"'))["pr_short"] != "": pr = json.loads( restaurants[i].pr.replace('\'', '"') )["pr_short"][:60] # 60文字までという制限がある。オーバーの時は"..."を表示する。 else: pr = "おすすめのお店です" # もう少し、良いメッセージにする。 except JSONDecodeError: pr = "おすすめのお店です" cur.execute( "SELECT FROM favorite_restaurants WHERE user_id = '{}' and favorite_restaurant_name = '{}';" .format(event.source.user_id, restaurants[i].name)) if cur.fetchone() is None: label_favorite = "お気に入りに追加する" text_favorite = "お気に入り追加" else: # もうお気に入りされている。 # is not None label_favorite = "お気に入りから削除する" text_favorite = "お気に入り削除" recommend_carousel_column = CarouselColumn( thumbnail_image_url=image_url, title=restaurants[i].name, text=pr, actions=[ URIAction(label='ぐるなびへ', uri=restaurants[i].url_mobile), MessageAction(label='位置情報をみる', text='位置情報 ' + restaurants[i].name), MessageAction(label=label_favorite, text=text_favorite + ' ' + restaurants[i].name) # event.source.user_id ]) recommend_carousel_columns.append(recommend_carousel_column) conn.commit() cur.close() conn.close() line_bot_api.reply_message( event.reply_token, TemplateSendMessage( alt_text='Carousel template', template=CarouselTemplate(columns=recommend_carousel_columns))) # 位置情報へを押された場合、"位置情報 (レストラン名)"とメッセージをトーク画面に返して、同時にそれをinputとして読み取って位置情報を返す。 elif "位置情報" in input_msg: for restaurant in restaurants: if restaurant.name in input_msg: line_bot_api.reply_message( event.reply_token, LocationSendMessage(title=restaurant.name, address=restaurant.address, latitude=restaurant.latitude, longitude=restaurant.longitude)) # お気に入りに追加するを押された場合、"お気に入り追加 (レストラン名)"とメッセージをトーク画面に返して、同時にそれをinputとして読み取って位置情報を返す。 elif "お気に入り追加" in input_msg: for restaurant in restaurants: # splitして、[command, name]もあり。 if restaurant.name in input_msg: conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format( user, password, host, port_db, database)) cur = conn.cursor() cur.execute( "INSERT INTO favorite_restaurants(user_id,favorite_restaurant_name) \ SELECT '{}', '{}' \ WHERE NOT EXISTS(SELECT 1 FROM favorite_restaurants WHERE user_id = '{}' AND favorite_restaurant_name = '{}')" .format(event.source.user_id, restaurant.name, event.source.user_id, restaurant.name)) conn.commit() cur.close() conn.close() elif "お気に入り削除" in input_msg: for restaurant in restaurants: if restaurant.name in input_msg: conn = psycopg2.connect("postgresql://{}:{}@{}:{}/{}".format( user, password, host, port_db, database)) cur = conn.cursor() cur.execute("DELETE FROM favorite_restaurants \ WHERE user_id = '{}' AND favorite_restaurant_name = '{}'" \ .format(event.source.user_id, restaurant.name)) conn.commit() cur.close() conn.close() else: output_msg = "知ってる言葉は\nちかく、ランダム、一覧、ランキング、ジャンル別、おすすめ。" line_bot_api.reply_message(event.reply_token, TextSendMessage(text=output_msg))
def handle_text_message(event): text = event.message.text profile = line_bot_api.get_profile(event.source.user_id) if text == 'profile': if isinstance(event.source, SourceUser): # profile = line_bot_api.get_profile(event.source.user_id) line_bot_api.reply_message(event.reply_token, [ TextSendMessage(text='Display name: ' + profile.display_name), TextSendMessage(text='Status message: ' + profile.status_message) ]) else: line_bot_api.reply_message( event.reply_token, TextSendMessage( text="Bot can't use profile API without user ID")) elif text == 'bye': if isinstance(event.source, SourceGroup): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_group(event.source.group_id) elif isinstance(event.source, SourceRoom): line_bot_api.reply_message(event.reply_token, TextSendMessage(text='Leaving group')) line_bot_api.leave_room(event.source.room_id) else: line_bot_api.reply_message( event.reply_token, TextSendMessage(text="Bot can't leave from 1:1 chat")) elif text == 'confirm': confirm_template = ConfirmTemplate(text='Do it?', actions=[ MessageAction(label='Yes', text='Yes!'), MessageAction(label='No', text='No!'), ]) template_message = TemplateSendMessage(alt_text='Confirm alt text', template=confirm_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'buttons': buttons_template = ButtonsTemplate( title='My buttons sample', text='Hello, my buttons', actions=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping'), PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(label='Translate Rice', text='米') ]) template_message = TemplateSendMessage(alt_text='Buttons alt text', template=buttons_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'carousel': carousel_template = CarouselTemplate(columns=[ CarouselColumn(text='hoge1', title='fuga1', actions=[ URIAction(label='Go to line.me', uri='https://line.me'), PostbackAction(label='ping', data='ping') ]), CarouselColumn(text='hoge2', title='fuga2', actions=[ PostbackAction(label='ping with text', data='ping', text='ping'), MessageAction(label='Translate Rice', text='米') ]), ]) template_message = TemplateSendMessage(alt_text='Carousel alt text', template=carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'image_carousel': image_carousel_template = ImageCarouselTemplate(columns=[ ImageCarouselColumn( text='hoge1', image_url='https://via.placeholder.com/1024x1024', action=DatetimePickerAction(label='datetime', data='datetime_postback', mode='datetime')), ImageCarouselColumn( text='hoge1', image_url='https://via.placeholder.com/1024x1024', action=DatetimePickerAction( label='date', data='date_postback', mode='date')) ]) template_message = TemplateSendMessage( alt_text='ImageCarousel alt text', template=image_carousel_template) line_bot_api.reply_message(event.reply_token, template_message) elif text == 'imagemap': pass elif text == 'image': bubble = BubbleContainer( direction='ltr', hero=ImageComponent( url='http://gosehat.heroku.com/static/image/logo_new.png', size='full', aspect_ratio='20:13', aspect_mode='cover', # action=URIAction(uri='http://example.com', label='label') ), body=BoxComponent( layout='vertical', contents=[ # title TextComponent(text='Tentang Aplikasi', weight='bold', size='xl'), # review # BoxComponent( # layout='baseline', # margin='md', # contents=[ # IconComponent(size='sm', url='https://example.com/gold_star.png'), # IconComponent(size='sm', url='https://example.com/grey_star.png'), # IconComponent(size='sm', url='https://example.com/gold_star.png'), # IconComponent(size='sm', url='https://example.com/gold_star.png'), # IconComponent(size='sm', url='https://example.com/grey_star.png'), # TextComponent(text='4.0', size='sm', color='#999999', margin='md', # flex=0) # ] # ), # info BoxComponent( layout='vertical', margin='lg', spacing='sm', contents= 'GoSehat merupakan aplikasi konsultasi kesehatan yang dibangun oleh :' '1. Arvianti Yulia Maulfa, 2. Entin Martiana Kusumaningtyas, 3. Fadilah Fahrul Hardiansyah ' '' # BoxComponent( # layout='baseline', # spacing='sm', # contents=[ # TextComponent( # text='GoSehat merupakan aplikasi konsultasi kesehatan yang dibangun oleh :' # '1. Arvianti Yulia Maulfa, 2. Entin Martiana Kusumaningtyas, 3. Fadilah Fahrul Hardiansyah ' # '', # color='#aaaaaa', # size='sm', # # flex=1 # ), # # TextComponent( # # text='Shinjuku, Tokyo', # # wrap=True, # # color='#666666', # # size='sm', # # flex=5 # # ) # ], # ), # BoxComponent( # layout='baseline', # spacing='sm', # contents=[ # TextComponent( # text='Time', # color='#aaaaaa', # size='sm', # flex=1 # ), # TextComponent( # text="10:00 - 23:00", # wrap=True, # color='#666666', # size='sm', # flex=5, # ), # ], # ), # ], ) ], ), # footer=BoxComponent( # layout='vertical', # spacing='sm', # contents=[ # # callAction, separator, websiteAction # SpacerComponent(size='sm'), # # callAction # ButtonComponent( # style='link', # height='sm', # action=URIAction(label='CALL', uri='tel:000000'), # ), # # separator # SeparatorComponent(), # # websiteAction # ButtonComponent( # style='link', # height='sm', # action=URIAction(label='WEBSITE', uri="https://example.com") # ) # ] # ), ) message = FlexSendMessage(alt_text="hello", contents=bubble) line_bot_api.reply_message(event.reply_token, message) elif text.lower() == 'tentang aplikasi': url = request.url_root + '/static/image/tentang.png' app.logger.info("url=" + url) text = 'GoSehat merupakan aplikasi konsultasi kesehatan yang dibangun oleh:\n1. Arvianti Yulia Maulfa \n2. Entin ' \ 'Martiana Kusumaningtyas \n3. Fadilah Fahrul Hardiansyah\n' line_bot_api.reply_message(event.reply_token, [ ImageSendMessage(url, url), TextSendMessage(text=text), ]) elif text.lower() == 'informasi aplikasi': text = 'GoSehat adalah chatbot (aplikasi pintar) yang dapat digunakan untuk ' \ 'konsultasi kesehatan secara gratis! Anda dapat bertanya seputar kesehatan seperti pengobatan,' \ 'pencegahan, atau penyebab suatu penyakit. \n\nCukup kirim pesan apa yang ingin Anda tanyakan atau ' \ 'memilih menu yang tersedia ya.\ncontoh: "Saya sering mengalami pusing, mual, batuk. Saya ' \ 'sakit apa ?" atau menanyakan informasi seperti "Haloo, untuk obat maag apa ya?" \n\nTahapan pemakaian ' \ 'aplikasi GoSehat :\n1. Ketikkan pesan seperti pada contoh diatas atau pilih menu \n2. Anda bisa ' \ 'mengetikkan gejala untuk mendeteksi penyakit pada tubuh Anda\n3. Anda bisa mengetikkan nama penyakit ' \ 'untuk mengetahui jenis penyakit\n4. Tunggu hingga aplikasi memberikan Anda jawaban\n\nTetap jaga ' \ 'kesehatan ya!' line_bot_api.reply_message( event.reply_token, TextSendMessage(text=text), ) elif text == 'quick_reply': line_bot_api.reply_message( event.reply_token, TextSendMessage( text='Quick reply', quick_reply=QuickReply(items=[ QuickReplyButton( action=PostbackAction(label="label1", data="data1")), QuickReplyButton( action=MessageAction(label="label2", text="text2")), QuickReplyButton(action=DatetimePickerAction( label="label3", data="data3", mode="date")), QuickReplyButton(action=CameraAction(label="label4")), QuickReplyButton(action=CameraRollAction(label="label5")), QuickReplyButton(action=LocationAction(label="label6")), ]))) else: conn = create_connection() cursor = conn.cursor() # set user_id dan profile (untuk nama) user_id = event.source.user_id name_user = line_bot_api.get_profile(event.source.user_id).display_name time = dt.datetime.now() if dt.datetime.now() < dt.datetime.now().replace( hour=12, minute=0, second=0) and dt.datetime.now() > dt.datetime.now().replace( hour=0, minute=0, second=0): salam = "Selamat Pagi " elif dt.datetime.now() > dt.datetime.now().replace( hour=12, minute=0, second=0) and dt.datetime.now() < dt.datetime.now().replace( hour=18, minute=0, second=0): salam = "Selamat Siang " elif dt.datetime.now() > dt.datetime.now().replace( hour=18, minute=0, second=0): salam = "Selamat Malam " else: salam = "Assalamualaikum " # MENU if text == '\informasi': messages = "Masukkan informasi yang ingin dicari.\nContoh : 'Apa penyakit maag ?'" save_menuinformasi(user_id, name_user, text, conn) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=(messages))) elif text == '\konsultasi': save_menukonsultasi(user_id, name_user, text, conn) messages = "Masukkan keluhan Anda.\nContoh : 'Saya merasa demam, mual pusing muntih. Saya sakit apa ?'" line_bot_api.reply_message(event.reply_token, TextSendMessage(text=(messages))) else: cursor.execute("SELECT status FROM menu WHERE id_user = '******'") count_menu = cursor.fetchall() # print("DEBUG> count menu = ", count_menu) if len(count_menu) != 0: if count_menu[0][0] == '\informasi': disease_id = 0 sinonim, penyakit, messages_info = get_info(text) if len(penyakit) == 0: messages = check_greeting(sinonim) save_history(user_id, name_user, text, messages, "", disease_id, time, conn) else: messages = salam + name_user + "\n" + messages_info[0][0] save_history(user_id, name_user, text, messages_info[0][0], "", disease_id, time, conn) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=(messages))) delete_menukonsultasi(user_id, conn) elif count_menu[0][0] == '\konsultasi': messages = message_bot(user_id, name_user, salam, text, time, conn) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=(messages))) delete_menukonsultasi(user_id, conn) else: decision = decide_process(text) print("DEBUG> pilihan = ", decision) if decision == "informasi": disease_id = 0 sinonim, penyakit, messages_info = get_info(text) if len(penyakit) == 0 and len(sinonim) <= 2: # gabung_sinonim = ' '.join(sinonim) messages = check_greeting(sinonim) save_history(user_id, name_user, text, messages, "", disease_id, time, conn) else: messages = salam + name_user for msg in messages_info: messages = messages + "\n\n" + msg[0][0] save_history(user_id, name_user, text, messages, "", disease_id, time, conn) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=(messages))) else: messages = message_bot(user_id, name_user, salam, text, time, conn) line_bot_api.reply_message(event.reply_token, TextSendMessage(text=(messages))) delete_menukonsultasi(user_id, conn)