def incoming():
    message = messages_from_json([request.args['message']])[0]

    if not any(isinstance(message, allowed_type) for allowed_type in ALLOWED_MESSAGE_TYPES):
        logging.debug('Ignoring non allowed message of type {}'.format(message.type))
        return '', 200

    if message.mention and message.mention != Config.BOT_USERNAME:
        logging.debug('Dropping message mentioning another bot. Message is mentioning {}'.format(message.mention))
        return '', 200

    user = BotUser.get_by_id(message.from_user)

    if message.mention:
        # handle the case where we're mentioned inline
        if message.body == '':
            translated = "What do you want translated?"
        elif user.current_state_data()['language'] is None:
            translated = gizoogleshit.gizoogleit(message.body)
        elif user.current_state_data()['language'] == "thug":
            translated = gizoogleshit.gizoogleit(message.body)
        else:
            translated = getTranslation.translateshit(user.current_state_data()['language'], message.body)
        outgoing_messages = [TextMessage(to=message.from_user, body=translated, chat_id=message.chat_id)]
    else:
        outgoing_messages = state_machine.handle_message(message.from_user, message)

    logging.debug('Processing message: {}'.format(message))

    if len(outgoing_messages) > 0:
        kik.send_messages(outgoing_messages)

    return '', 200
def incoming():
	# print 'kuch to hua2'
	if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
		return Response(status=403)
	messages = messages_from_json(request.json['messages'])
	msg = TextMessage()

	for message in messages:
 		if isinstance(message, TextMessage):
 			# print message.body
 			# kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="thank you for messaging TwerkBabes. Your daily source of Twerkers")])
 			# kik.send_messages([VideoMessage(to=message.from_user,chat_id=message.chat_id,video_url="http://199.217.117.213:9999/static/tt.mp4")])
 			# kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="We hope you enjoyed this twerk babe! See more by going to url.com")])
 			# break
 			random_index = randint(0,len(dir_list)-1)
 			file_name = dir_list[random_index]
 			if message.body == 'more twerk':
 				kik.send_messages([VideoMessage(to=message.from_user,chat_id=message.chat_id,video_url="http://107.170.21.148/videos/"+file_name),TextMessage(to=message.from_user,chat_id=message.chat_id,body="We hope you enjoyed this twerk babe! See more by going to url.com",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse('more twerk')])])])
 			else:
 				kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="thank you for messaging TwerkBabes. Your daily source of Twerkers"),VideoMessage(to=message.from_user,chat_id=message.chat_id,video_url="http://107.170.21.148/videos/"+file_name),TextMessage(to=message.from_user,chat_id=message.chat_id,body="We hope you enjoyed this twerk babe! See more by going to url.com",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse('more twerk')])])])
 			break
 	# msg.keyboards.append(SuggestedResponseKeyboard(to=message.from_user,hidden=False,responses=[TextResponse('OK')]))


	return Response(status=200)
Beispiel #3
0
 def test_single_element(self):
     input = [{'type': 'text', 'from': 'aleem', 'body': 'Yo text message!'}]
     output = messages_from_json(input)
     self.assertEqual(len(output), 1)
     self.assertIsInstance(output[0], TextMessage)
     self.assertEqual(output[0].type, 'text')
     self.assertEqual(output[0].from_user, 'aleem')
     self.assertEqual(output[0].body, 'Yo text message!')
Beispiel #4
0
def text_to_image():
	messages = messages_from_json(request.json['messages'])
	from_user,chat_id,body = filter_messages(messages)
	send_message(from_user,chat_id,'will return {0} as a picture soon!'.format(body))
	url = textFunction(body)
	pic = str(scrapeImage(url))
	send_pic_message(from_user,chat_id,random.choice(pic))
	return 'ok'
Beispiel #5
0
 def test_single_element(self):
     input = [{'type': 'text', 'from': 'aleem', 'body': 'Yo text message!'}]
     output = messages_from_json(input)
     self.assertEqual(len(output), 1)
     self.assertIsInstance(output[0], TextMessage)
     self.assertEqual(output[0].type, 'text')
     self.assertEqual(output[0].from_user, 'aleem')
     self.assertEqual(output[0].body, 'Yo text message!')
     self.assertEqual(input[0]['type'], 'text')
Beispiel #6
0
    def handle_message_request(self, request):

        messages = messages_from_json(request.json['messages'])

        for message in messages:
            if isinstance(message, TextMessage):
                self.handle_text_message(message)
            else:
                self.handle_unknown_message(message)
Beispiel #7
0
    def handle_message_request(self, request):

        messages = messages_from_json(request.json['messages'])

        for message in messages:
            if isinstance(message, TextMessage):
                self.handle_text_message(message)
            else:
                self.handle_unknown_message(message)
Beispiel #8
0
def receive():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        to = message.from_user
        chat_id = message.chat_id
        mention = message.mention

        if not db.session.query(Game).filter(Game.id == chat_id).count():
            print("No game found in db, creating a new game instance and adding to db")
            game = Game(chatId=chat_id, state=StateType.INITIAL)
            db.session.add(game)
            db.session.commit()

        game = db.session.query(Game).filter(Game.id == chat_id).first()
        print ("Restoring existing instance with state ", game.state)

        if isinstance(message, StartChattingMessage):
            Handler.handle_intro(to, game, None)
        elif isinstance(message, TextMessage):
            print 'type %r' % type(message.body)
            body = message.body.lower()
            if not body and mention and game.state == StateType.INITIAL:
                Handler.handle_song(to, game, None, song=music.get_song_from_playlist())
                return Response(status=200)

            if game.state == StateType.ANSWER_TIME:
                Handler.handle_answer(to, game, body)
                return Response(status=200)

            fn = srs.srs.get(body)
            if not fn:
                if body in music.Genre.GENRES and (
                                game.state == StateType.GENRE_SELECT or game.state == StateType.INITIAL):
                    Handler.handle_song(to, game, body, song=music.get_song_from_genre(body, game.difficulty))
                elif game.state == StateType.ARTIST_SELECT or game.state == StateType.INITIAL:
                    print 'type %r' % type(message.body)
                    logging.info(u'MATCHING ARTIST: {artist}'.format(artist=body))
                    try:
                        song = music.get_song_from_artist(body, game.difficulty)
                    except Exception as e:
                        print 'Exception: %r' % e
                        Handler.handle_error(to, game)
                        return Response(status=200)

                    Handler.handle_song(to, game, body, song=song)
                else:
                    Handler.handle_fallback(to, game, body)
                return Response(status=200)
            getattr(Handler, fn)(to, game, body)
        else:
            Handler.handle_fallback(to, game, None)
        return Response(status=200)
Beispiel #9
0
 def test_unknown_message(self):
     input = [{'type': 'some-unknown-type', 'from': 'aleem', 'to': 'laura', 'someProperty': 'aValue'}]
     output = messages_from_json(input)
     self.assertEqual(len(output), 1)
     self.assertIsInstance(output[0], UnknownMessage)
     self.assertEqual(output[0].type, 'some-unknown-type')
     self.assertEqual(output[0].from_user, 'aleem')
     self.assertEqual(output[0].to, 'laura')
     self.assertEqual(output[0].raw_message, input[0])
     self.assertEqual(input[0]['type'], 'some-unknown-type')
Beispiel #10
0
	def send_messages(self, request):

		if not self.kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
			return Response(status=403)

		messages = messages_from_json(request.json['messages'])
		for message in messages:
			if isinstance(message, TextMessage):
				self.kik.send_messages(self.__choose_response(message))

		return Response(status=200)
Beispiel #11
0
    def send_messages(self, request):

        if not self.kik.verify_signature(
                request.headers.get('X-Kik-Signature'), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json['messages'])
        for message in messages:
            if isinstance(message, TextMessage):
                self.kik.send_messages(self.__choose_response(message))

        return Response(status=200)
Beispiel #12
0
def index_kik():
    """
    Main entry point for Kik POSTing to us.
    Get messages in batches an iter through each message, deciding what to do
    """
    # Make sure it's Kik sending us messages
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        context0 = {'from_user': message.from_user, 'chat_id': message.chat_id}
        # Respond to mentions: we must send only one batch of messages
        if message.mention is not None:
            say(
                message.chat_id, context0,
                "Whoah Whoah Whoah! One at a time please. Are you trying to overload my circuts?!"
            )
            continue
        # check to see if we've seen this user before, collect their previous context
        if retrieveContext(message.chat_id, message.from_user):
            context0 = retrieveContext(message.chat_id, message.from_user)
        context0['platform'] = 'KIK'
        if isinstance(message, TextMessage):
            storeContext(message.chat_id,
                         message.from_user,
                         context0,
                         msg=message.body)
            selectActionFromText(message.chat_id, message.from_user,
                                 message.body, context0)
        elif isinstance(message, PictureMessage):
            # Always do a fitroom search when we get a picture message
            context0['user_img_url'] = message.pic_url
            context0['search_type'] = 'image'
            storeContext(message.chat_id, message.from_user, context0)
            doSearchEncounter(message.chat_id, context0)

        elif isinstance(message, StartChattingMessage):
            # User has started a chart for the first time; this is sent only once every for each user
            sendWelcomeMessage(message.chat_id, context0)
        else:
            # don't know how to respond to other messages e.g. videos
            say(
                message.chat_id, context0,
                "I'm new here. I'll be learning as I'm going. Try sending me a pic of a dress you'd like to search for"
            )

    return Response(
        status=200
    )  # If we return anything besides 200, Kik will try 3 more time to send the message
Beispiel #13
0
def incoming():
    """
    Handle all webhook calls from the Kik API to this server.

    This function is basically the very first communication point with any
    information or requests coming from the Kik API.
    """
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        current_state = None
        first_chat = None

        if isinstance(message, TextMessage):
            kik.send_messages([
                TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body=message.body
                )
            ])
        elif isinstance(message, PictureMessage):
            current_state, first_chat = assign_state_first_chat(message.chat_id)
            if (current_state):
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="current_state has been assigned"
                    )
                ])
            else:
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="current_state is empty"
                    )
                ])
            kik.send_messages([
                TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body="I have received an image"
                )
            ])

    return Response(status=200)
Beispiel #14
0
        def main():
            if not self.kik.verify_signature(
                    request.headers.get('X-Kik-Signature'),
                    request.get_data()):
                return Response(status=403)

            messages = messages_from_json(request.json['messages'])
            print "--Received Messages", messages
            to_send = None
            for message in messages:
                self.kik.send_messages([
                    IsTypingMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    is_typing=True)
                ])

                if isinstance(message, TextMessage):
                    split = message.body.split(" ")
                    command = split[0]
                    if not self.case_sensitive:
                        command = command.lower()
                    text_data = " ".join(split[1:])
                    if command == self.command_list_command:
                        r = [
                            TextMessage(to=message.from_user,
                                        chat_id=message.chat_id,
                                        body=self.command_list())
                        ]
                    elif self.functions.has_key(command):
                        r = self.functions[command](text_data)

                    else:
                        r = [
                            TextMessage(to=message.from_user,
                                        chat_id=message.chat_id,
                                        body="Unknown command.")
                        ]

                    for m in r:
                        if m.to == None:
                            m.to = message.from_user
                        if m.chat_id == None:
                            m.chat_id = message.chat_id
                        if m.keyboards == []:
                            keyboard = self.make_keyboard()
                            if len(keyboard.responses) > 0:
                                m.keyboards.append(keyboard)

                    self.kik.send_messages(r)
            return Response(status=200)
Beispiel #15
0
 def test_unknown_message(self):
     input = [{
         'type': 'some-unknown-type',
         'from': 'aleem',
         'to': 'laura',
         'someProperty': 'aValue'
     }]
     output = messages_from_json(input)
     self.assertEqual(len(output), 1)
     self.assertIsInstance(output[0], UnknownMessage)
     self.assertEqual(output[0].type, 'some-unknown-type')
     self.assertEqual(output[0].from_user, 'aleem')
     self.assertEqual(output[0].to, 'laura')
     self.assertEqual(output[0].raw_message, input[0])
Beispiel #16
0
 def test_multiple_elements(self):
     input = [{'type': 'text', 'from': 'aleem', 'body': 'Yo text message!'},
              {'type': 'link', 'from': 'laura', 'url': 'http://yo.text/message'}]
     output = messages_from_json(input)
     self.assertEqual(len(output), 2)
     self.assertIsInstance(output[0], TextMessage)
     self.assertEqual(output[0].type, 'text')
     self.assertEqual(output[0].from_user, 'aleem')
     self.assertEqual(output[0].body, 'Yo text message!')
     self.assertEqual(input[0]['type'], 'text')
     self.assertIsInstance(output[1], LinkMessage)
     self.assertEqual(output[1].type, 'link')
     self.assertEqual(output[1].from_user, 'laura')
     self.assertEqual(output[1].url, 'http://yo.text/message')
     self.assertEqual(input[1]['type'], 'link')
Beispiel #17
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, TextMessage):
            kik.send_messages([
                TextMessage(to=message.from_user,
                            chat_id=message.chat_id,
                            body=get_response(message))
            ])

    return Response(status=200)
Beispiel #18
0
    def incoming_messages():
        signature = request.headers.get('X-Kik-Signature')
        raw_body = request.get_data()

        if not kik.verify_signature(signature, raw_body):
            return '', 403

        json_body = json.loads(raw_body)
        messages = messages_from_json(json_body['messages'])

        logging.debug(messages)

        # Handle the message in a different thread so we can return a 200 right away
        Thread(target=messages_handler, args=[messages]).start()

        return '', 200
Beispiel #19
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403) 
   
    messages = messages_from_json(request.json['messages'])
    for message in messages:
        if isinstance(message, StartChattingMessage):
            kik.send_messages([
            TextMessage(
            to=message.from_user,
            chat_id = message.chat_id,
            body='Hello Im the Mad Lib Bot! Send me pictures and Ill tell a wacky random story based on the tags of the image. Ill take the first 5 pics :)'
            ),
            ])  

        elif isinstance(message, PictureMessage):
            global counter
            global words
            result = clarifai_api.tag_image_urls(message.pic_url)
            one = result["results"]
            two = one[0]
            three = two['result']
            four = three['tag']
            five = four['classes']
            if counter == 5:
                poem = "Marcy had a little " + words[0] + " whose " + words[1] + " was white as " + words[2] + "  This " + words[3] +  " would follow Mary wherever she would go. Mary also like to go " + words[4]+ "ing."
	        kik.send_messages([
	        TextMessage(
	        to=message.from_user,
	        chat_id=message.chat_id,
	        body=poem 
	        ),

	       ])
            words.append(five[1])
            counter +=1
            left = 5 - counter
            mes = str(left) + " pictures left to go!"  
	    kik.send_messages([
	    TextMessage(
	    to=message.from_user,
	    chat_id=message.chat_id,
	    body=mes 
	    ),

	   ])
    return Response(status=200)
Beispiel #20
0
def handleRequest():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, TextMessage):
            kik.send_messages([
                TextMessage(
                    to      = message.from_user,
                    chat_id = message.chat_id,
                    body    = message.body
                )
            ])

        return Response(status=200)
Beispiel #21
0
def incoming():
    """Handle incoming traffic."""
    if not utility.kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                        request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])
    try:
        for message in messages:
            if isinstance(message, TextMessage):
                print(message.from_user, ':', message.body)
                print_sentiment_scores(message)
            else:
                utility.handle_secondary_message_types(message)
    except (IndexError, AttributeError) as error:
        print("No messages found.", error)
    return Response(status=200)
Beispiel #22
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)
    print("Checking for messages...")
    messages = messages_from_json(request.json['messages'])
    print(str(messages))
    for message in messages:
        if isinstance(message, TextMessage):
            print("Message '{}' recieved from '{}'".format(message.body, message.from_user))
            message_to_send = str(random_quote())
            print("Sending message: {}".format(message_to_send))
            kik.send_messages([
                TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body=message_to_send
                )
            ])
    return Response(status=200)
Beispiel #23
0
def incoming():

    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, TextMessage):
            body_lower = message.body.lower()
            if body_lower == "another one":
                kik.send_messages([
                PictureMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    pic_url="http://40.media.tumblr.com/108878995b5b74bb89618dab799ded58/tumblr_nzwkikqhcH1titub2o1_1280.jpg"
                )
            ])
            elif body_lower == "ayy lmao":
                kik.send_messages([
                TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body=message.body
                )
            ])
            else:
                pepe_dict = requests.get(pepe_url, headers={'Authorization' : 'Client-ID %s' %imgur_client}).json()

                pepe_data = pepe_dict['data']['images']

                pimage_list = [pepe['link'] for pepe in pepe_data if pepe['type'] == 'image/jpeg' and pepe['nsfw'] is None]
                
                kik.send_messages([
                PictureMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    pic_url=random.choice(pimage_list)
                )
            ])
                
        return Response(status=200)
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403,
                        response="Unable to verify message signature.")

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, TextMessage):
            result = parser.process_text_message(message)
            if result != 200:
                qr = queue.send_all()
                if qr != 200:
                    incoming_error_handler(result, qr)
                return Response(status=result)

    # Note the function call to send_all().
    # As per documentation, send_all() returns an appropriate response code based upon success or failure.
    return Response(status=queue.send_all())
Beispiel #25
0
 def test_multiple_elements(self):
     input = [{
         'type': 'text',
         'from': 'aleem',
         'body': 'Yo text message!'
     }, {
         'type': 'link',
         'from': 'laura',
         'url': 'http://yo.text/message'
     }]
     output = messages_from_json(input)
     self.assertEqual(len(output), 2)
     self.assertIsInstance(output[0], TextMessage)
     self.assertEqual(output[0].type, 'text')
     self.assertEqual(output[0].from_user, 'aleem')
     self.assertEqual(output[0].body, 'Yo text message!')
     self.assertIsInstance(output[1], LinkMessage)
     self.assertEqual(output[1].type, 'link')
     self.assertEqual(output[1].from_user, 'laura')
     self.assertEqual(output[1].url, 'http://yo.text/message')
Beispiel #26
0
def incoming():
    print('coming in here')
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, TextMessage):
            kik.send_messages([
                ####### NEW #######
                VideoMessage(message.from_user,
                             message.chat_id,
                             video_url=giffy(message),
                             loop=True,
                             autoplay=True)
                ###################
            ])

    return Response(status=200)
Beispiel #27
0
def index_kik():
    """
    Main entry point for Kik POSTing to us.
    Get messages in batches an iter through each message, deciding what to do
    """
    # Make sure it's Kik sending us messages
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)
    
    messages = messages_from_json(request.json['messages'])

    for message in messages:
        context0 = {'from_user':message.from_user,'chat_id':message.chat_id}
        # Respond to mentions: we must send only one batch of messages
        if message.mention is not None: 
            say(message.chat_id,context0,"Whoah Whoah Whoah! One at a time please. Are you trying to overload my circuts?!")
            continue
        # check to see if we've seen this user before, collect their previous context
        if retrieveContext(message.chat_id,message.from_user):
            context0 = retrieveContext(message.chat_id,message.from_user)
        context0['platform'] = 'KIK'
        if isinstance(message, TextMessage):
            storeContext(message.chat_id,message.from_user,context0,msg=message.body)
            selectActionFromText(message.chat_id,message.from_user,message.body,context0)
        elif isinstance(message, PictureMessage):
            # Always do a fitroom search when we get a picture message
            context0['user_img_url'] = message.pic_url
            context0['search_type'] = 'image'
            storeContext(message.chat_id,message.from_user,context0)
            doSearchEncounter(message.chat_id, context0)
        
        elif isinstance(message, StartChattingMessage):
            # User has started a chart for the first time; this is sent only once every for each user
            sendWelcomeMessage(message.chat_id,context0)
        else:
            # don't know how to respond to other messages e.g. videos
            say(message.chat_id,context0,"I'm new here. I'll be learning as I'm going. Try sending me a pic of a dress you'd like to search for")
             
    return Response(status=200) # If we return anything besides 200, Kik will try 3 more time to send the message
Beispiel #28
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])
    chat_record = ChatRecord(json.dumps(request.json['messages']))
    db.session.add(chat_record)
    db.session.commit()

    for message in messages:
        if isinstance(message, TextMessage):
            logging.info(message)


            if "Hi" in message.body or "Hello" in message.body or "Sup" in message.body:
                text = 'Hi {0}! Welcome to Propos.ai ChatBot. The first Text based solution for voicing your concerns on bad service. Type "HELP" at any time for further instructions or just start Ranting with Hashtag_Business (e.g. #eCorps), we will distribute to the right parties accordingly.'.format(message.from_user)
                send_text(message.from_user, message.chat_id, text)
            elif 'Get started' in message.body:
                send_text(message.from_user, message.chat_id, 'Alrightee ... ', ["Where were you?", "I want to voice a concern", "Business place I can propose to"])    
            else:
                text = 'I don\'t understand your message, please Tap "Get started"'
                send_text(message.from_user, message.chat_id, text, ["Get started"]) 

    return Response(status=200)
Beispiel #29
0
 def test_empty_array(self):
     input = []
     output = messages_from_json(input)
     self.assertEqual(output, [])
Beispiel #30
0
 def GetMessages(self):
     return messages_from_json(request.json['messages'])
Beispiel #31
0
def show_menu():
	#Assuming the func = main_init;
	#Handle the message here first	
	messages = messages_from_json(request.json['messages'])
	filter_messages(messages)
	return 'ok'
def incoming():

    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        game_chat_id = message.chat_id
        temp_game = Hangman()

        if message.from_user in ["furrylife100"]:
            logprint("BLOCKING: " + message.from_user + " said " +
                     message.body)
            return Response(status=200)

        with KikDB() as kikdb:
            try:
                kikdb.cursor.execute(KikDB.query_checkExist, (game_chat_id, ))
                existance = tuple(kikdb.cursor.fetchone())
                if not existance[0]:
                    logprint("RECORD DOES NOT EXIST\nMain: Creating game")
                    kikdb.mysqlExec(
                        KikDB.query_reg,
                        (game_chat_id, json.dumps(temp_game.jsondump())))
                    temp_game.initiateSession(message)
                    kikdb.mysqlDelScheduler(False, game_chat_id, False, "")
                else:
                    logprint("RECORD EXISTS, RETRIEVING DATA for chat id: " +
                             game_chat_id)
                    kikdb.mysqlExec(KikDB.query_retrieve, (game_chat_id, ))
                    result = kikdb.cursor.fetchone()
                    logprint("RETRIEVED INFO: " + str(json.loads(result[0])))
                    temp_game.loadFromDB(json.loads(result[0]))
                    #temp_game.loadFromDB(json.loads(result[0].decode("utf-8", "ignore")))
                    logprint("END RETRIEVING DATA")
                    temp_game.initiateSession(message)
                    kikdb.mysqlDelScheduler(True, game_chat_id,
                                            temp_game.game_status,
                                            temp_game.custom_chooser)
                    if temp_game.check:
                        logprint(
                            "Main: Game ended. Deleting chat session from database"
                        )
                        kikdb.mysqlExec(KikDB.query_del, (game_chat_id, ))
                        logprint(
                            "Main: Deleting scheduler if it exists as well")
                        label_game_chat_id = "EVENT" + game_chat_id[:55]
                        query = KikDB.query_drop_event % (label_game_chat_id, )
                        kikdb.mysqlExec(query, None)
                        break
            except KikError as e:
                logprint("Something went wrong:", str(e))
                logging.error(e, exc_info=True)
                #traceback.print_tb(e.__traceback__)
                logprint("=" * 150)

                return Response(status=200)
            except Exception as err:
                logprint("Something that wasn't Kik went wrong:", str(err))
                logprint("KIK SEND_MESSAGE")
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body=
                        "Sorry, service is currently down. Try again later!")
                ])
                logging.error(err, exc_info=True)
                #traceback.print_tb(err.__traceback__)
                logprint("=" * 150)
                return Response(status=200)

            #logprint("UPDATING DATABASE with %s" % temp_game.jsondump())
            kikdb.mysqlExec(KikDB.query_overwrite,
                            (json.dumps(temp_game.jsondump()),
                             (game_chat_id, )))

    logprint("=" * 150)
    return Response(status=200)
Beispiel #33
0
def receive():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        to = message.from_user
        chat_id = message.chat_id
        mention = message.mention

        if not db.session.query(Game).filter(Game.id == chat_id).count():
            print(
                "No game found in db, creating a new game instance and adding to db"
            )
            game = Game(chatId=chat_id, state=StateType.INITIAL)
            db.session.add(game)
            db.session.commit()

        game = db.session.query(Game).filter(Game.id == chat_id).first()
        print("Restoring existing instance with state ", game.state)

        if isinstance(message, StartChattingMessage):
            Handler.handle_intro(to, game, None)
        elif isinstance(message, TextMessage):
            body = message.body.lower()
            if not body and mention and game.state == StateType.INITIAL:
                Handler.handle_song(to,
                                    game,
                                    None,
                                    song=music.get_song_from_playlist())
                return Response(status=200)

            if game.state == StateType.ANSWER_TIME:
                Handler.handle_answer(to, game, body)
                return Response(status=200)

            fn = srs.srs.get(body)
            if not fn:
                if body in music.Genre.GENRES and (
                        game.state == StateType.GENRE_SELECT
                        or game.state == StateType.INITIAL):
                    Handler.handle_song(to,
                                        game,
                                        body,
                                        song=music.get_song_from_genre(
                                            body, game.difficulty))
                elif game.state == StateType.ARTIST_SELECT or game.state == StateType.INITIAL:
                    print 'MATCHING ARTIST: {}'.format(body)
                    try:
                        song = music.get_song_from_artist(
                            body, game.difficulty)
                    except Exception as e:
                        print 'Exception: %r' % e
                        Handler.handle_error(to, game)
                        return Response(status=200)

                    Handler.handle_song(to, game, body, song=song)
                else:
                    Handler.handle_fallback(to, game, body)
                return Response(status=200)
            getattr(Handler, fn)(to, game, body)
        else:
            Handler.handle_fallback(to, game, None)
        return Response(status=200)
Beispiel #34
0
    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """

        # Verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        for message in messages:
            self.message = message
            self.user = self.kik_api.get_user(message.from_user)

            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):
                self.send_message("Welcome to StudyHelper!")

            # Check if the user has sent a picture
            elif isinstance(message, PictureMessage):
                if self.quiz.is_empty(
                ) or self.awaiting_action == UPLOAD_NOTES:
                    if self.quiz.is_empty():
                        self.send_message("Thanks! Reading notes...")
                        self.send_message("Creating questions...")
                        self.quiz.add_notes_from_picture(message.pic_url)

                    elif self.next_action == ADD_NOTES:
                        self.quiz.add_notes_from_picture(message.pic_url)

                    elif self.next_action == REPLACE_NOTES:
                        self.quiz.replace_notes_from_picture(message.pic_url)

                    self.send_message_with_responses(
                        "What would you like to do now?",
                        ["Add More", "Replace", "Cancel", "Start Quiz"])

                    self.awaiting_action = UPLOAD_NOTES
                    self.awaiting_response = UPLOADING_MORE_NOTES

                else:
                    # Saves the picture url
                    self.pic_url = message.pic_url
                    self.send_message_with_responses(
                        "I already have some notes, should I add to them or replace them?",
                        ["Add", "Replace", "Cancel"])

                    self.awaiting_response = REPLACE_NOTES

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                # Prompt user to upload notes if there are none
                if self.awaiting_response == UPLOAD_NOTES:
                    self.send_message(
                        "To get started, please take a picture of your notes.")
                    self.send_message("Then the quizzing can begin")

                elif self.awaiting_response == CANCEL:
                    response = message.body.strip().lower()[0]

                    if response == 'c':
                        if self.quiz.is_empty():
                            self.awaiting_action = UPLOAD_NOTES
                            self.awaiting_response = UPLOAD_NOTES
                        else:
                            self.send_message_with_responses(
                                "Okay! What would you like to do now?", [
                                    "Add More", "Replace", "Cancel",
                                    "Start Quiz"
                                ])

                            self.awaiting_action = UPLOAD_NOTES
                            self.awaiting_response = UPLOADING_MORE_NOTES

                # If the user
                elif self.awaiting_response == UPLOADING_MORE_NOTES:
                    response = message.body.strip().lower()[0]

                    if response == 'a':
                        self.send_message(
                            "Okay! Please upload the notes to add, or type 'Cancel'."
                        )
                        self.awaiting_response = CANCEL
                        self.awaiting_action = UPLOAD_NOTES
                        self.next_action = ADD_NOTES

                    elif response == 'r':
                        self.send_message(
                            "Okay! Please upload notes to replace, or type 'Cancel'."
                        )
                        self.awaiting_response = CANCEL
                        self.awaiting_action = UPLOAD_NOTES
                        self.next_action = REPLACE_NOTES

                    elif response == 'c':
                        self.send_message("Okay!")
                        self.quiz.reset()
                        self.awaiting_response = UPLOAD_NOTES
                        self.awaiting_action = NO_ACTION

                    elif response == 's':
                        self.send_message("Okay! Starting the quiz...")
                        self.awaiting_response = ANSWER
                        self.awaiting_action = NO_ACTION

                elif self.awaiting_response == REPLACE_NOTES:
                    response = message.body.strip().lower()[0]

                    if response == 'a':
                        self.send_message("Okay! Adding new notes...")
                        self.quiz.add_notes_from_picture(message.pic_url)

                    elif response == 'r':
                        self.send_message("Okay! Replacing notes...")
                        self.quiz.replace_notes_from_picture(message.pic_url)

                    elif response == 'c':
                        self.send_message("Okay! Keeping old notes...")

                    self.awaiting_response = ANSWER

                # After the questions have run out, checks if user wants to continue or stop
                elif self.awaiting_response == CONTINUE_QUIZZING:
                    response = message.body.strip().lower()[0]

                    if response == 'y':
                        self.quiz.regenerate_questions()
                        self.send_message("Okay! Starting over...")
                        self.awaiting_response = ANSWER

                    elif response == 'n':
                        self.send_message("Okay!")
                        self.awaiting_response = UPLOAD_NOTES

                # Check the user's answer
                elif self.awaiting_response == ANSWER:
                    self.quiz.check_answer(self, self.message.body)

            # If its not a text message, give them another chance to use the suggested responses
            else:
                self.send_message(
                    "Sorry {}, I didn't get that. Try again?".format(
                        self.user.first_name))

            if not self.quiz.is_empty() and self.awaiting_response == ANSWER:
                # Tries to ask user a question, returns false if it fails
                if not self.quiz.ask_next_question(self):
                    self.send_message_with_responses(
                        "You've gone through all of the questions, would you like to start over?",
                        ["Yes", "No"])
                    self.awaiting_response = CONTINUE_QUIZZING
                else:
                    self.awaiting_response = ANSWER

            # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
            # 5 messages per user).

            if self.response_messages != []:
                self.kik_api.send_messages(self.response_messages)

            self.response_messages = []

        return Response(status=200)
Beispiel #35
0
 def test_empty_array(self):
     input = []
     output = messages_from_json(input)
     self.assertEqual(output, [])
Beispiel #36
0
 def extract_message(self, request):
     return messages_from_json(request.json['messages'])
Beispiel #37
0
def incoming():
    global state
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)
    messages = messages_from_json(request.json['messages'])
    for message in messages:
        if isinstance(message, TextMessage):
            print("aaaaa")
            b = TextMessage(to=message.from_user,
                            body="lalalalal",
                            chat_id=message.chat_id)
            print("bbbbbb")
            b.keyboards.append(
                SuggestedResponseKeyboard(to=message.from_user,
                                          hidden=False,
                                          responses=[TextResponse("aaa")]))
            print("ccccccc")
            kik.send_messages([b])
            '''
            if state==1:
                sql = "INSERT INTO comment (date, menu_id, name, comment) VALUES (%s, %s, %s, %s)"
                val = (today.date, today.menu_id, message.from_user, message.body)
                mycursor.execute(sql, val)
                mydb.commit()
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Okay, got that!")])
                state = 0
            elif message.body.lower() in ["hi", "hello", "hi!", "hello!", "hey"]:
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Hi, I'm your rating lunch bot, if you wanna rate your lunch, type\"rate lunch\", if you wanna see the menu, type\"see menu\"")])
                state = 0
            elif message.body.lower() == "rate lunch":
                kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is your lunch menu: "+today.menu+"\nhow do you like your lunch?")])
                state = 1
                print(state)
            elif message.body.lower() == "see menu":
            	kik.send_messages([
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Here is your lunch menu: "+today.menu)])#need to communicate with database
            	state = 0
            else:
                kik.send_messages([
                TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body="I don't understand, you can type\"rate lunch\" to rate your lunch or \"see menu\" to see the menu")])
                state=0
                '''
        return Response(status=200)
Beispiel #38
0
def incoming():
    global kik_api
    """Handle incoming messages to the bot. All requests are authenticated using the signature in
    the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
    :return: Response
    """
    # verify that this is a valid request
    if not kik_api.verify_signature(request.headers.get("X-Kik-Signature"),
                                    request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json["messages"])

    response_messages = []

    if custom_module is not None and hasattr(custom_module,
                                             "ModuleMessageController"):
        message_controller = custom_module.ModuleMessageController(
            bot_username, config_file)
    else:
        message_controller = MessageController(bot_username, config_file)

    for message in messages:
        # noinspection PyBroadException
        try:
            LazyKikUser.character_persistent_class = message_controller.character_persistent_class
            user_db = message_controller.character_persistent_class.get_user(
                message.from_user)
            user = LazyKikUser.init(
                user_db) if user_db is not None else LazyKikUser.init_new_user(
                    message.from_user, bot_username)
            with force_locale(message_controller.get_config().get(
                    "BaseLanguage", "en")):
                response_messages += message_controller.process_message(
                    message, user)
        except:
            error_id = hashlib.md5(
                (str(int(time.time())) +
                 message.from_user).encode('utf-8')).hexdigest()
            print(
                "Message-Error: {error_id} ({bot_username})\n---\nTrace: {trace}\n---\nReq: {request}\n---\nResp: {response}"
                .format(error_id=error_id,
                        bot_username=bot_username,
                        trace=traceback.format_exc(),
                        request=json.dumps(message.__dict__,
                                           indent=4,
                                           sort_keys=True),
                        response=json.dumps(
                            response_messages,
                            default=lambda o: getattr(o, '__dict__', str(o)),
                            indent=4,
                            sort_keys=True)))

            if isinstance(message, TextMessage) and len(message.body) < 100:
                resp_keyboard = [
                    MessageController.generate_text_response(message.body),
                    MessageController.generate_text_response("Hilfe")
                ]
            else:
                resp_keyboard = [
                    MessageController.generate_text_response("Hilfe")
                ]

            response_messages += [
                TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body=
                    _("Leider ist ein Fehler aufgetreten. Bitte versuche es erneut.\n\n"
                      +
                      "Sollte der Fehler weiterhin auftreten, mach bitte einen Screenshot und sprich @{admin_user} per PM an.\n\n"
                      + "Fehler-Informationen: {error_id}").format(
                          error_id=error_id,
                          admin_user=message_controller.get_config().get(
                              "Admins", "admin1").split(',')[0].strip()),
                    keyboards=[
                        SuggestedResponseKeyboard(responses=resp_keyboard)
                    ])
            ]

        # noinspection PyBroadException
        try:
            kik_api.send_messages(response_messages)
        except:
            error_id = hashlib.md5(
                (str(int(time.time()))).encode('utf-8')).hexdigest()
            print(
                "Kik-Send-Error: {error_id} ({bot_username})\n---\nTrace: {trace}\n---\nReq: {request}\n---\nResp: {response}"
                .format(error_id=error_id,
                        bot_username=bot_username,
                        trace=traceback.format_exc(),
                        request=json.dumps([m.__dict__ for m in messages],
                                           indent=4,
                                           sort_keys=True),
                        response=json.dumps(
                            response_messages,
                            default=lambda o: getattr(o, '__dict__', str(o)),
                            indent=4,
                            sort_keys=True)))
            error_response_messages = []
            for resp_message in response_messages:  # type: Message
                error_response_messages.append(
                    TextMessage(
                        to=resp_message.to,
                        chat_id=resp_message.chat_id,
                        body=
                        "Leider ist ein Fehler aufgetreten. Bitte versuche es erneut.\n\n"
                        "Sollte der Fehler weiterhin auftreten, mach bitte einen Screenshot und sprich @{admin_user} per PM an.\n\n"
                        "Fehler-Informationen: {error_id}".format(
                            error_id=error_id,
                            admin_user=message_controller.get_config().get(
                                "Admins", "admin1").split(',')[0].strip()),
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                MessageController.generate_text_response(
                                    "Hilfe")
                            ])
                        ]))

            kik_api.send_messages(error_response_messages)

    return Response(status=200)
Beispiel #39
0
    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """
        # verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        response_messages = []

        for message in messages:
            user = self.kik_api.get_user(message.from_user)
            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):

                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="haloo {}, pilihlah salah satu?".format(
                            user.first_name),
                        # keyboards are a great way to provide a menu of options for a user to respond with!
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("ga")
                            ])
                        ]))

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                user = self.kik_api.get_user(message.from_user)
                message_body = message.body.lower()
                print(message_body)
                sql = """insert into tb_inbox(user, message)
                        values ('%s','%s')""" % (user.first_name, message_body)
                print("Berhasil Menginputkan")

                curs.execute(sql)

                conn.commit()

                if message_body.split()[0] in ["hi", "hello", "hallo"]:
                    query = "SELECT in_message FROM tb_perintah"
                    curs.execute(query)
                    menu = curs.fetchall()
                    print(message_body)
                    print(menu)
                    msg = "List Menu !!\n"
                    iterasi = 1
                    for x in menu:
                        for y in x:
                            print(y)
                            msg = msg + "" + str(iterasi) + ". " + y + "\n"
                        iterasi += 1
                    response_messages.append(
                        TextMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    body=msg.format(user.first_name),
                                    keyboards=[
                                        SuggestedResponseKeyboard(responses=[
                                            TextResponse("1"),
                                            TextResponse("2"),
                                            TextResponse("3"),
                                            TextResponse("4"),
                                            TextResponse("5")
                                        ])
                                    ]))

                    query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','1')" % (
                        user.first_name, message_body)
                    curs.execute(query)
                    conn.commit()

                elif message_body.startswith("#"):

                    msg = message_body.split()

                    print(msg[0])

                    query = "SELECT query FROM tb_perintah WHERE marker = '%s' " % (
                        msg[0])

                    print(query)

                    try:

                        curs.execute(query)

                    except:

                        print("ERROR")

                    menu = curs.fetchone()

                    print(menu[0])

                    if menu != None:

                        try:

                            msgProdi = msg[6] + " " + msg[7]

                            print(msgProdi)

                            qry = menu[0] % ("%" + msg[3] + "%",
                                             "%" + msgProdi + "%")

                        except:

                            print("INDEX MESSAGE TIDAK DITEMUKAN")

                            qry = menu[0]

                        print(qry)

                        curs.execute(qry)

                        data = curs.fetchall()

                        iterasi = 0

                        teks = ""

                        msgNew = ""

                        for row in data:

                            for i in curs.description:
                                print(i[0])

                                print(row[iterasi])

                                msgNew = msgNew + (i[0] + " = " +
                                                   str(row[iterasi]) + "\n")

                                iterasi += 1

                                # if iterasi == i*4:

                                #     msgNew = "\n"

                                # else:

                                #     msgNew = ""

                            iterasi = 0

                    query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','0')" % (
                        user.first_name, message_body)

                    print(query)

                    curs.execute(query)

                    conn.commit()

                    response_messages.append(
                        TextMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    body=msgNew))

                else:
                    print(int(message_body))
                    query = "SELECT * FROM tb_perintah WHERE id_perintah = %i " % (
                        int(message_body))
                    curs.execute(query)
                    menu = curs.fetchone()
                    print(message.from_user)
                    print(message.chat_id)
                    print(menu[2])
                    response_messages.append(
                        TextMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    body=menu[2].format(user.first_name)))

                query = "INSERT INTO tb_outbox (user,message,status) VALUES('%s','%s','1')" % (
                    user.first_name,
                    message_body,
                )
                curs.execute(query)
                conn.commit()

            else:

                response_messages.append(
                    TextMessage(to=message.from_user,
                                chat_id=message.chat_id,
                                body="maaf itu apa ya {}?".format(
                                    user.first_name),
                                keyboards=[
                                    SuggestedResponseKeyboard(responses=[
                                        TextResponse("Good"),
                                        TextResponse("Bad")
                                    ])
                                ]))

            # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
            # 5 messages per user).

            self.kik_api.send_messages(response_messages)

        return Response(status=200)
Beispiel #40
0
def webhook():
    """Webhook."""
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])
    chat_record = ChatRecord(json.dumps(request.json['messages']))
    db.session.add(chat_record)
    db.session.commit()

    for message in messages:
        if isinstance(message, TextMessage):
            logging.info(message)

            if '$' in message.body:
                send_text(message.from_user, message.chat_id, 'Looking up...')

                for symbol in re.findall(r'\$\w(?:\w)*(?:\.\w+)?',
                                         message.body):
                    symbol = symbol[1:]

                    yahoo = Share(symbol)
                    if yahoo.get_price():
                        text = 'Price of {} is {}'.format(
                            symbol, yahoo.get_price())
                        send_text(message.from_user, message.chat_id, text)
                        send_link(
                            message.from_user,
                            message.chat_id,
                            url='https://finance.yahoo.com/q?s={}'.format(
                                symbol),
                            title='Yahoo finace: {}'.format(symbol),
                            pic_url='https://chart.finance.yahoo.com/z?s={}'.
                            format(symbol),
                        )
                    else:
                        text = 'We couldn\'t find a ticker with {}.'.format(
                            symbol)
                        send_text(message.from_user, message.chat_id, text)

                        keyboards = [
                            '$' + t['symbol']
                            if '^' not in t['symbol'] else t['symbol']
                            for t in lookup(symbol)
                        ][:4]
                        if keyboards:
                            text = 'Are you looking for...'
                            send_text(message.from_user, message.chat_id, text,
                                      keyboards)
                        else:
                            text = 'What are you looking for?'
                            send_text(message.from_user, message.chat_id, text)

            elif '^' in message.body:
                send_text(message.from_user, message.chat_id, 'Looking up...')

                for symbol in re.findall(r'\^\w(?:\w)*(?:\.\w+)?',
                                         message.body):
                    send_link(
                        message.from_user,
                        message.chat_id,
                        url='https://finance.yahoo.com/q?s={}'.format(symbol),
                        title='Yahoo finace: {}'.format(symbol),
                        pic_url='https://chart.finance.yahoo.com/z?s={}'.
                        format(symbol),
                    )

            elif 'lookup' in message.body.lower():
                lookup_text = re.findall(r'lookup (\w+)', message.body.lower())
                if lookup_text:
                    text = 'Are you looking for...'
                    keyboards = [
                        '$' + t['symbol'] for t in lookup(lookup_text[0])
                    ][:8]
                    send_text(message.from_user, message.chat_id, text,
                              keyboards)
                else:
                    text = 'What are you looking for?'
                    send_text(message.from_user, message.chat_id, text)

            else:
                if 'hi' in message.body.lower(
                ) or 'hello' in message.body.lower():
                    text = 'Hi {}!'.format(message.from_user)
                else:
                    text = 'I don\'t understand message'
                send_text(message.from_user, message.chat_id, text)
                text = 'For live stock quotes type "$" followed by a ticker symbol or "lookup" followed by a company name.'  # noqa
                send_text(message.from_user, message.chat_id, text)
                text = 'For example, if you want to look up Apple, type "$AAPL" or "lookup Apple".'
                send_text(message.from_user, message.chat_id, text)
                text = 'For index quotes, start with "^". For example, "^DJI" for Dow Jones Industrial Average.'
                send_text(message.from_user, message.chat_id, text)
                text = 'Try it now:'
                send_text(message.from_user, message.chat_id, text,
                          ["Lookup Apple"])

    return Response(status=200)
Beispiel #41
0
def incoming():
	if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
		return Response(status=403)
	messages = messages_from_json(request.json['messages'])
	for message in messages:
 		if isinstance(message, TextMessage):
 			random_index_video = randint(0,len(video_list)-1)
 			video_file = "n.mp4"; #video_list[random_index_video]
 			print 'video_file: ',video_file
 			random_index_pic = randint(0,len(pic_list)-1)
 			pic_file = pic_list[random_index_pic]
			now = datetime.datetime.now();
			daily_smoke_show_pic =  month_map[str(now.day)].split("##")[0];
			daily_smoke_show_message =  month_map[str(now.day)].split("##")[1];
			print daily_smoke_show_pic , " " , daily_smoke_show_message;
 			if(message.body=='SETTINGS'):
 				kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="change settings from here",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(SET_BAE_TIME),TextResponse(DISABLE_BAE_TIME)])])])
 			elif message.body==SET_BAE_TIME:
 				kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="plesae select schedule time",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse('8AM'),TextResponse('8PM'),TextResponse('10AM'),TextResponse('10PM'),TextResponse('BACK')])])])
 			elif message.body=='BACK':
 				kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="please choose an option",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(TODAY_BAE),TextResponse(SET_BAE_TIME),TextResponse('SETTINGS')])])])
 			elif message.body=='8AM' or message.body=='8PM' or message.body=='10AM' or message.body=='10PM':
 				record = db(user=message.from_user)
 				if len(record)>0:
 					record[0].update(schedule_time=message.body,enable='yes')
 					kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="BAE TIME SET TO "+message.body,keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(TODAY_BAE),TextResponse(SET_BAE_TIME),TextResponse('SETTINGS')])])])
 				else:
 					db.insert(message.from_user,message.chat_id,message.body,'yes')
 					kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="BAE TIME SET TO "+message.body,keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(TODAY_BAE),TextResponse(SET_BAE_TIME),TextResponse('SETTINGS')])])])
 				db.commit()
 			elif message.body==DISABLE_BAE_TIME:
 				record = db(user=message.from_user)
 				if len(record)>0:
 					record[0].update(enable="no")
 					kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="schedule disabled",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(SET_BAE_TIME),TextResponse(DISABLE_BAE_TIME)])])])
 				else:
 					kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="you have not set any BAE TIME! set now..",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(SET_BAE_TIME),TextResponse(DISABLE_BAE_TIME)])])])
 				db.commit()
 			elif message.body==TODAY_BAE:
 				csv_file = csv.reader(open('input.csv','rU'))
 				todays_day = datetime.datetime.now().day
 				counter = 1
 				media_file_location = ""
 				for row in csv_file:
 					if counter==todays_day:
 						print 'counter: ',counter
 						print 'todays_day: ',todays_day
 						print 'row: ',row
 						media_file = row[0].strip()
 						text_message = row[1].strip()
 						if '.jpg' in media_file:
 							media_file_location = "http://107.170.21.148/pics/"+media_file
 							kik.send_messages([PictureMessage(to=message.from_user,chat_id=message.chat_id,pic_url=media_file_location),TextMessage(to=message.from_user,chat_id=message.chat_id,body=daily_smoke_show_message,keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse('MEET LOCALS'),TextResponse('SETTINGS'),TextResponse('SHARE THIS BAE')])])])
 						elif '.mp4' in media_file:
 							media_file_location = "http://107.170.21.148/videos/"+media_file
 							kik.send_messages([VideoMessage(to=message.from_user,chat_id=message.chat_id,video_url=media_file_location),TextMessage(to=message.from_user,chat_id=message.chat_id,body=daily_smoke_show_message,keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse('MEET LOCALS'),TextResponse('SETTINGS'),TextResponse('SHARE THIS BAE')])])])
 						break
 					else:
 						counter+=1
 			elif message.body=='MEET LOCALS':
 				kik.send_messages([TextMessage(to=message.from_user,chat_id=message.chat_id,body="Are you interested in meeting local girls? Its super easy! Simply go to http://SwipeSmash.com, create a profile and start swiping girls. These girls are local and looking for guys with the same hookup interest! Its the easiest dating app out there! Go to http://SwipeSmash.com",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(TODAY_BAE),TextResponse('SHARE'),TextResponse('SETTINGS')])])])
 			elif message.body in ['SHARE','SHARE THIS BAE']:
 				print 'in link message'
 				msg = LinkMessage(to=message.from_user,text="CLICK HERE to share with your friends", chat_id=message.chat_id,url='http://107.170.21.148:9999/users',pic_url='http://107.170.21.148/share.png',keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(TODAY_BAE),TextResponse('MEET LOCALS'),TextResponse('SETTINGS')])])
 				kik.send_messages([msg])
				
 			else:
 				record = db(user=message.from_user)
 				if len(record)==0:
 					db.insert(message.from_user,message.chat_id,'Default','yes')
 					db.commit()
 				kik.send_messages([TextMessage(to=message.from_user,chat_id=None,body="Welcome to BAE'S DAILY! We will send you daily hot babes with there usernames!"),VideoMessage(to=message.from_user,chat_id=message.chat_id,video_url="http://107.170.21.148/welcome/"+video_file),TextMessage(to=message.from_user,chat_id=message.chat_id,body="Click TODAY'S BAE to get started!",keyboards=[SuggestedResponseKeyboard(to=None,hidden=False,responses=[TextResponse(TODAY_BAE),TextResponse(SET_BAE_TIME),TextResponse('SETTINGS')])])])
 			break
 	# msg.keyboards.append(SuggestedResponseKeyboard(to=message.from_user,hidden=False,responses=[TextResponse('OK')]))


	return Response(status=200)
Beispiel #42
0
def inc():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    #chatID = None
    chatMessage = None
    greetingMessage = "Welcome to LeagueStats! Type in your summoner name in order to find out your\
	worst 3 champions!"

    userNotExist = "This user doesn't exist, please try to enter another summoner name."

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, StartChattingMessage):
            kik.send_messages([
                TextMessage(to=message.from_user,
                            chat_id=message.chat_id,
                            body=greetingMessage)
            ])

        if isinstance(message, TextMessage):
            kik.send_messages([
                IsTypingMessage(to=message.from_user,
                                chat_id=message.chat_id,
                                is_typing=True)
            ])

            searchName = (message.body).lower()
            summInfoJson = requests.get(
                'https://na.api.pvp.net/api/lol/na/v1.4/summoner/by-name/' +
                searchName + '?api_key=' + riotKey)
            if summInfoJson.status_code == 404:
                chatMessage = userNotExist

                kik.send_messages([
                    TextMessage(to=message.from_user,
                                chat_id=message.chat_id,
                                body=chatMessage)
                ])
                break

            summInfoId = str(summInfoJson.json()[searchName]['id'])
            summChampInfoJson = requests.get(
                'https://na.api.pvp.net/api/lol/na/v1.3/stats/by-summoner/' +
                summInfoId + '/ranked?season=SEASON2017&api_key=' + riotKey)
            summChampInfo = summChampInfoJson.json()

            if summChampInfoJson.status_code == 404:
                chatMessage = userNotExist
                kik.send_messages([
                    TextMessage(to=message.from_user,
                                chat_id=message.chat_id,
                                body=chatMessage)
                ])
                break

            champInfo = summChampInfo['champions']
            champArray = []

            for champion in champInfo:
                if champion['id'] == 0:
                    break
                temp = Champion(champion['id'],
                                champion['stats']['totalDeathsPerSession'],
                                champion['stats']['totalChampionKills'],
                                champion['stats']['totalAssists'],
                                champion['stats']['totalSessionsPlayed'])
                champArray.append(temp)

                # sorted by KDA
            sortedChampInfo = sorted(champArray, key=lambda x: x.getKDA())

            #sort out the champions -> take top 3 worst KDA.

            top3 = sortedChampInfo[:3]
            finalList = []

            for champion in top3:
                temp = [
                    champion.championName,
                    champion.getChampionImgURL(),
                    champion.getKDA(), champion.numDeaths, champion.numKills,
                    champion.totalSessions
                ]
                finalList.append(temp)

            print(finalList)

            champ1 = finalList[0][0]
            champ2 = finalList[1][0]
            champ3 = finalList[2][0]

            kik.send_messages([
                TextMessage(to=message.from_user,
                            chat_id=message.chat_id,
                            body="Your top 3 worst champions are " + champ1 +
                            ' , ' + champ2 + ' , ' + champ3),
                TextMessage(
                    to=message.from_user,
                    chat_id=message.chat_id,
                    body="Send another message to search for another summoner."
                )
            ])

    return Response(status=200)
Beispiel #43
0
    def incoming(self):
        """Handle incoming messages to the bot. All requests are authenticated using the signature in
        the 'X-Kik-Signature' header, which is built using the bot's api key (set in main() below).
        :return: Response
        """
        # verify that this is a valid request
        if not self.kik_api.verify_signature(
                request.headers.get("X-Kik-Signature"), request.get_data()):
            return Response(status=403)

        messages = messages_from_json(request.json["messages"])

        response_messages = []

        for message in messages:
            user = self.kik_api.get_user(message.from_user)
            # Check if its the user's first message. Start Chatting messages are sent only once.
            if isinstance(message, StartChattingMessage):

                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body="Hey {}, how are you?".format(user.first_name),
                        # keyboards are a great way to provide a menu of options for a user to respond with!
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("Bad")
                            ])
                        ]))

            # Check if the user has sent a text message.
            elif isinstance(message, TextMessage):
                user = self.kik_api.get_user(message.from_user)
                message_body = message.body.lower()

                if message_body.split()[0] in ["hi", "hello"]:
                    response_messages.append(
                        TextMessage(to=message.from_user,
                                    chat_id=message.chat_id,
                                    body="Hey {}, how are you?".format(
                                        user.first_name),
                                    keyboards=[
                                        SuggestedResponseKeyboard(responses=[
                                            TextResponse("Good"),
                                            TextResponse("Bad")
                                        ])
                                    ]))

                elif message_body == "good":
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body="That's Great! :) Wanna see your profile pic?",
                            keyboards=[
                                SuggestedResponseKeyboard(responses=[
                                    TextResponse("Sure! I'd love to!"),
                                    TextResponse("No Thanks")
                                ])
                            ]))

                elif message_body == "bad":
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body="Oh No! :( Wanna see your profile pic?",
                            keyboards=[
                                SuggestedResponseKeyboard(responses=[
                                    TextResponse("Yep! I Sure Do!"),
                                    TextResponse("No Thank You")
                                ])
                            ]))

                elif message_body in ["yep! i sure do!", "sure! i'd love to!"]:

                    # Send the user a response along with their profile picture (function definition is below)
                    response_messages += self.profile_pic_check_messages(
                        user, message)

                elif message_body in ["no thanks", "no thank you"]:
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=
                            "Ok, {}. Chat with me again if you change your mind."
                            .format(user.first_name)))
                else:
                    response_messages.append(
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=
                            "Sorry {}, I didn't quite understand that. How are you?"
                            .format(user.first_name),
                            keyboards=[
                                SuggestedResponseKeyboard(responses=[
                                    TextResponse("Good"),
                                    TextResponse("Bad")
                                ])
                            ]))

            # If its not a text message, give them another chance to use the suggested responses
            else:

                response_messages.append(
                    TextMessage(
                        to=message.from_user,
                        chat_id=message.chat_id,
                        body=
                        "Sorry, I didn't quite understand that. How are you, {}?"
                        .format(user.first_name),
                        keyboards=[
                            SuggestedResponseKeyboard(responses=[
                                TextResponse("Good"),
                                TextResponse("Bad")
                            ])
                        ]))

            # We're sending a batch of messages. We can send up to 25 messages at a time (with a limit of
            # 5 messages per user).

            self.kik_api.send_messages(response_messages)

        return Response(status=200)
Beispiel #44
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

# list of python objects
    messages = messages_from_json(request.json['messages'])
    user_name = messages[0].from_user
    chatting_id = messages[0].chat_id
    current_msg = messages[0].body.lower()

    # store the user info
    c_user = kik.get_user(user_name)
    # user messages
    #SendMessage(user_name,chatting_id,help_str)
    resp = bot.message(current_msg)
    entity = "#other"
    try:
        entity = list(resp['entities'])[0]
        try:
            # store the location if available
            location_entity = list(resp['entities'])[1]
            # get the location name
            location = resp['entities']['location'][0]['value']
        except:
            pass
    except:
        pass
    if entity == "greetings":
        greeting_list = ["hey-o", "Yo", "Hi-yo", "me cool, you?", "hi", "hey"]
        SendMessage(user_name, chatting_id,
                    greeting_list[random.randint(0,
                                                 len(greeting_list) - 1)])
    elif entity == "fine_tag":
        fine_resp = ["That's great!", "Nice!", "Cool, Human!", "good to know"]
        SendMessage(user_name, chatting_id,
                    fine_resp[random.randint(0,
                                             len(fine_resp) - 1)])
    elif entity == "ask_fine":
        ask_fine_resp = [
            "Yeah me cool!", "I'm cool!", "I'm well", "yeah, I'm awesome!",
            "I'm fine"
        ]
        SendMessage(user_name, chatting_id,
                    ask_fine_resp[random.randint(0,
                                                 len(ask_fine_resp) - 1)])
        # get the weather
    elif entity == "get_weather":
        # if location is available get the weather with location, else
        # get the weather of the current place
        SendMessage(user_name, chatting_id, "Wait a sec...")
        try:
            SendMessage(user_name, chatting_id, "here's the weather")
            wex = WexExtractor(location, weather_key)
            data = wex.GetJsonData()
            weather_msg = data['weather'][0]['description']
            SendMessage(user_name, chatting_id, weather_msg)
        except:
            SendMessage(user_name, chatting_id, "current location weather")

    else:
        SendMessage(user_name, chatting_id, "Sorry, didn't catch that!")
    return Response(status=200)
Beispiel #45
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'),
                                request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])
    for message in messages:
        #if isInUserList(message.from_user):
        if MessageHandler.ShouldBenchMarkBeReset(message) == True:
            MessageHandler.ResetBenchMark(message)
        if isinstance(message, TextMessage):
            global reset
            global resetUser
            DataMessage = ""
            if message.body == 'BENCHMARK ANALYSIS' or message.body.upper(
            ) == "B" or message.body.upper() == "BD":
                if "BD" not in message.body.upper():
                    DataMessage = MessageHandler.BuildBenchMarkAnalysisMessageResults(
                        message)
                else:
                    DataMessage = MessageHandler.BuildBenchMarkAnalysisMessageResults(
                        message, True)
            elif message.body == 'PROBE ANALYSIS' or message.body.upper(
            ) == "P":
                DataMessage = MessageHandler.BuildProbeAnalysisMessageResults(
                    message)
            elif message.body == 'INACTIVE ANALYSIS' or message.body.upper(
            ) == "I" or message.body.upper() == "ID":
                if "ID" not in message.body.upper():
                    DataMessage = MessageHandler.BuildInactiveAnalysisMessageResults(
                        message)
                else:
                    DataMessage = MessageHandler.BuildInactiveAnalysisMessageResults(
                        message, True)
            elif message.body == 'RESET BENCHMARK' or message.body.upper == "RB":
                if isInAdminList(message.from_user):
                    reset = True
                    resetUser = message.from_user
                    return SendResetMessage(message)
                else:
                    return SendNonAdminMessage(message)
            elif message.body.upper(
            ) == 'YES' and message.from_user == resetUser and reset == True:
                DataMessage = MessageHandler.ResetBenchMark(message)
                reset = False
            elif message.body.upper(
            ) == 'NO' and message.from_user == resetUser and reset == True:
                reset = False
                return SendResetCancledMessage(message)
            elif message.body.upper() == 'HELP':
                return SendHelpMessage(message)
            else:
                reset = False
                DataMessage = '**Probing for Activity**'
                MessageHandler.InsertBotEntry(message)
            if reset == False:
                return SendDefaultMessage(message, DataMessage)

        if isinstance(message, ReadReceiptMessage):
            MessageHandler.SaveReceiptData(message)
            return Response(status=200)
Beispiel #46
0
def incoming():
    if not kik.verify_signature(request.headers.get('X-Kik-Signature'), request.get_data()):
        return Response(status=403)

    messages = messages_from_json(request.json['messages'])

    for message in messages:
        if isinstance(message, TextMessage):
            if message.body == 'Hi':
                body = 'What\'s the motive?'
                kik.send_messages([
                        VideoMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            video_url=getGiphy.getGiphy('Hello'),
                            autoplay=True,
                            loop=True,
                        ),
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Staying in'),
                                        TextResponse('Going out'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextResponse

        if isinstance(message, TextMessage):
            if message.body == 'Going out':
                body = 'What day though?'
                kik.send_messages([
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Sunday'),
                                        TextResponse('Monday'),
                                        TextResponse('Tuesday'),
                                        TextResponse('Wednesday'),
                                        TextResponse('Thursday'),
                                        TextResponse('Friday'),
                                        TextResponse('Saturday'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextResponse

        if isinstance(message, TextMessage):
            if message.body == 'Friday':
                body = ('This is what\'s gucci tonight:\nChainsaw: $3 shots\nEthel\'s: $8 for 1.5lbs wings')
                kik.send_messages([
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body=body,
                            keyboards=[
                                SuggestedResponseKeyboard(
                                    responses=[
                                        TextResponse('Chainsaw'),
                                        TextResponse('Ethel\'s'),
                                    ]
                                )
                            ]
                        )
                    ])
                message = TextResponse

        if isinstance(message, TextMessage):
            if message.body == 'Chainsaw':
                kik.send_messages([
                        PictureMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            pic_url='http://thecord.ca/wp-content/uploads/2014/09/Chainsaw-Heather-Davidson.jpg',
                        ),
                        TextMessage(
                            to=message.from_user,
                            chat_id=message.chat_id,
                            body='Address: 28 King St N,\n Waterloo, ON N2J 2W6\nPhone:(519) 954-8660'
                        )
                ])

        return Response(status=200)