Exemple #1
0
def process_message(message):
    print(message)

    qrs = make_qrs_set()

    sender = message["sender"]["id"]
    save_customer_data(sender)

    if "text" in message["message"]:
        msg = message["message"]["text"]
        if msg == "최신 패치 내역":
            # DB에서 패치 내역 불러와서 contents 처럼 한 str로 처리해주면 됨
            recentData = get_recent_patch()
            contents = make_text_from_data(recentData)
            response = Text(text=contents, quick_replies=qrs)
        elif msg == "최신 패치 내역 링크":
            recentData = get_recent_patch()
            # DB에서 title, subtitle, image_url, item_url(게시글 id 만 가져오면 됨)
            elem = get_element(
                recentData["subject"],
                recentData["date"],
                recentData["thumbnail_src"],
                recentData["notification_id"],
            )
            response = GenericTemplate(elements=[elem], quick_replies=qrs)
        elif msg == "기능 설명":
            contents = "입력창 위의 버튼을 눌러\n⚡최신 패치 내역⚡을 보거나\n📢카트라이더 패치 안내 게시판📢으로 이동할 수 있습니다😍"
            response = Text(text=contents, quick_replies=qrs)
        else:
            contents = "버튼을 눌러 내용을 확인해주세요!😊"
            response = Text(text=contents, quick_replies=qrs)
    return response.to_dict()
Exemple #2
0
def process_message(message):
    app.logger.debug('Message received: {}'.format(message))

    if 'sticker_id' in message['message']:        
        return Text(text="What do you want me to do?")

    elif 'attachments' in message['message']:
        # only images are supportes as attachments
        if message['message']['attachments'][0]['type'] == 'image':
            return process_image(message["message"]["attachments"][0]["payload"]["url"])

    elif 'quick_reply' in message['message']:
        match = analyzer.hangul_pattern.search(message['message'].get('text'))
        if match:
            # read the payload and create a list of new quick replies without the dish we are currently getting informations for
            payload = message['message']["quick_reply"]["payload"]
            dishes = json.loads(payload) # payload consists of a list of dishes in json format
            dishes = filter_ko_dish_from_list(dishes, message['message'].get('text'))
            qrs = dishes_to_quick_reply(dishes)

            # look up the informations for this dish
            cur_dish = match.group(0)
            return process_dish_name(cur_dish, qrs)

    elif 'text' in message['message']:
        match = analyzer.hangul_pattern.search(message['message'].get('text'))
        if match:
            return process_dish_name(match.group(0))
        else:
            return Text(text="I can only look up dishes written in Hangul. Please try again.")
    
    return Text(text=HELP)
Exemple #3
0
    def handle_response(self, text, qrs_list=None):
        """Handles generic response sending"""

        if qrs_list:
            qrs = process_quick_rpls(qrs_list)
            response = Text(text=text, quick_replies=qrs).to_dict()
        else:
            response = Text(text=text).to_dict()
        res = self.send(response, 'RESPONSE')
        app.logger.info('Response: {}'.format(res))
Exemple #4
0
def process_dish_name(dish, quick_replies = ''):
    dish_info = analyzer.get_response(dish)
    # we got the dish in the db, now process the info
    if dish_info:
        send_addition_image_for_dish(dish)
        response = analyzer.dish_info_to_string(dish_info)
        # include optional quick replies to our final Text()
        if quick_replies:
            return Text(text=response, quick_replies=quick_replies)
        return Text(text=response)
    return Text(text="I can't seem to find information for a dish with that name.")
Exemple #5
0
    def message(self, message):
        print('message')
        print(message)                
        get_sender = Text(text= str(message['sender']['id']))
        get_text = Text(text= str(message['message']['text']))
        try:
        	chck_payload = Text(text= str(message['message']['quick_reply']['payload']))
        except KeyError:
        	chck_payload = 'text'
        text = get_text.to_dict()
        text = text['text']
        check = self.read(text, chck_payload)
        print(check)
        # problem hereeeee
        if check != 2:
        	print('check')
        	response = self.movie_route()
        	if self.questions_check[response[0]] == 'quick':
        		print(response)
        		quick_reply = [quick_replies.QuickReply(title=i, payload='quick') for i in response[1]]
        		quick_reply += [quick_replies.QuickReply(title='Go back', payload='quick')]
        		quick_replies_set = quick_replies.QuickReplies(quick_replies=quick_reply)
        		text = { 'text': response[0]}
        		text['quick_replies'] = quick_replies_set.to_dict()
        		self.send(text, 'RESPONSE')
        	else:
        		text = {'text': response[0]}
        		self.send(text, 'RESPONSE')
        		print('carousel')
        		print(self.movies)
        		elems  = []
        		i = 0
        		while i < len(self.movies[0]):
        			btn = elements.Button(title='Read More', payload=movies[2][i], button_type='postback')
        			elem = elements.Element(
        				title=self.movies[2][i],
        				image_url=self.movies[0][i],
        				subtitle=self.movies[1][i],
        				buttons=[
        					btn
        				]
        				)
        			elems.append(elem)
        			i+=1
        		res = templates.GenericTemplate(elements=elems)        		
        		messenger.send(res.to_dict(), 'RESPONSE')
	        	quick_reply = [quick_replies.QuickReply(title='Go back', payload='quick')]
	        	quick_replies_set = quick_replies.QuickReplies(quick_replies=quick_reply)
	        	default = {'quick_replies': quick_replies_set.to_dict()}
	        	self.send(default, 'RESPONSE')
        		print(self.movie_responses['Movies'])
Exemple #6
0
def process_message(message):
    app.logger.debug('Message received: {}'.format(message))

    if 'attachments' in message['message']:
        if message['message']['attachments'][0]['type'] == 'location':
            app.logger.debug('Location received')
            response = Text(text='{}: lat: {}, long: {}'.format(
                message['message']['attachments'][0]['title'],
                message['message']['attachments'][0]['payload']['coordinates']
                ['lat'], message['message']['attachments'][0]['payload']
                ['coordinates']['long']))
            return response.to_dict()

    if 'text' in message['message']:
        msg = message['message']['text'].lower()
        response = Text(text='Sorry didn\'t understand that: {}'.format(msg))
        if 'text' in msg:
            response = Text(text='This is an example text message.')
        if 'image' in msg:
            response = Image(url='https://unsplash.it/300/200/?random')
        if 'video' in msg:
            response = Video(
                url='http://techslides.com/demos/sample-videos/small.mp4')
        if 'quick replies' in msg:
            qr1 = quick_replies.QuickReply(title='Location',
                                           content_type='location')
            qr2 = quick_replies.QuickReply(title='Payload',
                                           payload='QUICK_REPLY_PAYLOAD')
            qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
            response = Text(text='This is an example text message.',
                            quick_replies=qrs)
        if 'payload' in msg:
            txt = 'User clicked {}, button payload is {}'.format(
                msg, message['message']['quick_reply']['payload'])
            response = Text(text=txt)
        if 'webview-compact' in msg:
            btn = get_button(ratio='compact')
            elem = get_element(btn)
            response = GenericTemplate(elements=[elem])
        if 'webview-tall' in msg:
            btn = get_button(ratio='tall')
            elem = get_element(btn)
            response = GenericTemplate(elements=[elem])
        if 'webview-full' in msg:
            btn = get_button(ratio='full')
            elem = get_element(btn)
            response = GenericTemplate(elements=[elem])

        return response.to_dict()
Exemple #7
0
def process_message(messenger, message):
    if "attachments" in message["message"]:
        if message["message"]["attachments"][0]["type"] == "location":
            logger.debug("Location received")
            attachments = message["message"]["attachments"]
            response = Text(
                text="{}: lat: {}, long: {}".format(
                    message["message"]["attachments"][0]["title"],
                    attachments[0]["payload"]["coordinates"]["lat"],
                    attachments[0]["payload"]["coordinates"]["long"],
                )
            )
            res = messenger.send(response.to_dict(), "RESPONSE")
            logger.debug("Response: {}".format(res))
            return True

    if (
        "quick_reply" in message["message"]
        and "payload" in message["message"]["quick_reply"]
    ):
        payload = message["message"]["quick_reply"]["payload"]
        process_postback(messenger, payload)
        return True

    if "text" in message["message"]:
        msg = message["message"]["text"]
        if msg.lower() in ["help", "info"]:
            text = {
                "text": _(
                    u"Oh you need some help 🆘!"
                    " This is the main menu, select what you need below 👇🏼"
                ),
                "quick_replies": get_main_menu().to_dict(),
            }
        else:
            user["msg"] = msg
            text = {
                "text": _(
                    u"I didn't get you %(first_name)s"
                    "!\nYou said : %(msg)s\n"
                    "\nThis is the main menu, select what you need below 👇🏼",
                    **user
                ),
                "quick_replies": get_main_menu().to_dict(),
            }

    if not text:
        text = {
            "text": _(
                u"%(first_name)s\n"
                "This is the main menu, select what you need below 👇🏼"
            ),
            "quick_replies": get_main_menu().to_dict(),
        }

    messenger.send(text, "RESPONSE")
    return True
Exemple #8
0
	def postback(self, message):
		payload = message['postback']['payload'].split()
		url_video = find_ydl_url(payload[1])
		filesize = url_video["filesize"]
		payload2 = url_video['url']
		payload1 = payload[0]
		ytb_id = payload[1:]


		if 'viewvideo' in payload1:
			if filesize < 25690112:

				response = Video(url=payload2)
			else:
				response = Text(text="Messenger à bloqué votre video, parce qu'elle est trop volumineuse😞😞")
		else:
			response = Text(text='This is an example text message.')
		action = response.to_dict()
		self.send(action)
		return 'success'
Exemple #9
0
def process_image(url):
    if '.gif' in url:
        return Text(text="Sadly i can't analyze gif files. Lets try it again with a standart image format.")

    #let the user know we're analyzing the image
    app.logger.debug('Image received')
    messenger.send(Text("Analyzing the image...").to_dict(), 'RESPONSE')
    messenger.send_action(SenderAction(sender_action='typing_on').to_dict())

    # first check the image size and type
    error = analyzer.check_image_info(url)
    if error:
        return Text(text=error) 

    # then let the analyzer do its job and get a list of dishes that are visible in the image
    dishes = analyzer.get_response_image(url)
    qrs = dishes_to_quick_reply(dishes)
    if not qrs:
        return Text(text='I didn\'t find any dishes. Try again with a different angle or try writting the dish in Hangul.') 
    return Text(text='Choose a dish for more informations.', quick_replies=qrs)
Exemple #10
0
def process_message(messenger, message):
    if 'attachments' in message['message']:
        if message['message']['attachments'][0]['type'] == 'location':
            logger.debug('Location received')
            attachments = message['message']['attachments']
            response = Text(text='{}: lat: {}, long: {}'.format(
                message['message']['attachments'][0]['title'], attachments[0]
                ['payload']['coordinates']['lat'], attachments[0]['payload']
                ['coordinates']['long']))
            res = messenger.send(response.to_dict(), 'RESPONSE')
            logger.debug('Response: {}'.format(res))
            return True

    if ('quick_reply' in message['message']
            and 'payload' in message['message']['quick_reply']):
        payload = message['message']['quick_reply']['payload']
        process_postback(messenger, payload)
        return True

    if 'text' in message['message']:
        msg = message['message']['text']
        if msg.lower() in ['help', 'info']:
            text = {
                "text":
                _(u'Oh you need some help 🆘!'
                  ' This is the main menu, select what you need bellow 👇🏼'),
                "quick_replies":
                get_main_menu().to_dict()
            }
        else:
            user['msg'] = msg
            text = {
                "text":
                _(
                    u'I didn\'t get you %(first_name)s'
                    '!\nYou said : %(msg)s\n'
                    '\n This is the main menu, select what you need bellow 👇🏼',
                    **user),
                "quick_replies":
                get_main_menu().to_dict()
            }

    if not text:
        text = {
            "text":
            _(u'%(first_name)s\n'
              'This is the main menu, select what you need bellow 👇🏼'),
            "quick_replies":
            get_main_menu().to_dict()
        }

    messenger.send(text, 'RESPONSE')
    return True
Exemple #11
0
    def process_message(self, message):
        """Handles message processing on the part of facebook"""

        app.logger.info('Message received: {}'.format(message))

        user_id = message['sender']['id']
        callback = False

        if "message" in message:
            if 'attachments' in message['message']:
                print('entered')
                response = Text(
                    text=
                    "Apologies, but I'm only able to understand text input!")
                return (response.to_dict(), callback)
            elif 'text' in message['message']:
                message_text = message['message']['text']

        elif "postback" in message:
            return self.postback(message)

        #run logic
        text, quick_rpls, elastic_hits = detect_intent_texts(
            user_id, message_text)

        if quick_rpls is None and elastic_hits is None:
            response = Text(text=text)

        elif elastic_hits is None:
            qrs = process_quick_rpls(quick_rpls)
            response = Text(text=text, quick_replies=qrs)

        elif elastic_hits and text is None:
            response = display_recipe_hits(elastic_hits)

        elif elastic_hits and text:
            response = display_recipe_hits(elastic_hits)
            callback = True

        return (response.to_dict(), callback)
Exemple #12
0
    def generate_info_message(self):

        response = Text(text=random.choice(responses["no-exact-match"]))
        return response.to_dict()
Exemple #13
0
    def message(self, message):
        app.logger.debug(message)
        global dialogue
        if 'text' in message['message']:
            msg = message['message']['text'].lower()
            if len(dialogue) == 6:
                dialogue = set()

            # Greetings
            if msg in [
                    "hi", "hi there", "hello", "sain bainuu", "сайн уу", "hey",
                    "yo"
            ]:
                user_info = self.get_user()
                response = Image(
                    url='https://i.ytimg.com/vi/penG2V8bMBE/maxresdefault.jpg')
                self.send(response.to_dict(), 'RESPONSE')
                response = Text(
                    text=
                    'Hello {}! I’m SMART CITY chatbot 🤖, I can offer you municipality service everywhere at any time. You can message me about road issues. '
                    .format(user_info['first_name']))
                self.send(response.to_dict(), 'RESPONSE')
                qr1 = quick_replies.QuickReply(title='Open issue',
                                               payload='open_issue')
                qr2 = quick_replies.QuickReply(title='Live city',
                                               payload='live_city')
                qrs = quick_replies.QuickReplies(quick_replies=[qr1, qr2])
                response = Text(text='How can I help you today?',
                                quick_replies=qrs)
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Greetings')

            # Phone number
            if dialogue == {'Greetings', 'Name'}:
                response = Text(text='Please enter your phone number:')
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Phone')

            # Problem description
            elif dialogue == {'Greetings', 'Name', 'Phone'}:
                response = Text(text='Please describe the problem:')
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Problem')

            # Location
            elif dialogue == {'Greetings', 'Name', 'Phone', 'Problem'}:
                qr = quick_replies.QuickReply(title='Location',
                                              content_type='location')
                qrs = quick_replies.QuickReplies(quick_replies=[qr])
                response = Text(text='Please send the location of problem:',
                                quick_replies=qrs)
                self.send(response.to_dict(), 'RESPONSE')

        # Name
        if message['message'].get('quick_reply'):
            if message['message']['quick_reply'].get(
                    'payload') == 'open_issue' and 'Greetings' in dialogue:
                response = Text(text='Please enter your full name:')
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Name')

        # Live city
        if message['message'].get('quick_reply'):
            if message['message']['quick_reply'].get(
                    'payload') == 'live_city' and 'Greetings' in dialogue:
                btn = get_button(ratio='compact')
                elem = get_element(btn)
                response = GenericTemplate(elements=[elem])
                self.send(response.to_dict(), 'RESPONSE')

        # Picture
        if message['message'].get('attachments'):
            if message['message']['attachments'][0].get('type') == 'location':
                response = Text(text='Please send a picture of a problem:')
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Location')
            # Final state
            elif message['message']['attachments'][0].get('type') == 'image':
                response = Text(
                    text=
                    'Your ticket has been opened and we will get on it as fast as possible. If you '
                    'want to add another issue, please just greet again. Thank you!. '
                )
                self.send(response.to_dict(), 'RESPONSE')
                dialogue.add('Image')