def test_no_profile_pic_messages(self): """Test the profile pic helper method- no picture set, should return a test message""" test_user = User("Davey", "Jones") expected_results = [TextMessage(body="It does not look like you have a profile picture, you should set one")] actual_results = self.testbot.profile_pic_check_messages(test_user, TextMessage()) self.assertAlmostEqual(actual_results, expected_results)
def test_profile_pic_messages(self): """Test the profile pic helper method- should return a picture url""" actual_results = self.testbot.profile_pic_check_messages( self.get_test_user(), TextMessage()) expected_results = [ PictureMessage(pic_url="http://example.com/me.png"), TextMessage(body="Here's your profile picture!") ] self.assertEquals(actual_results, expected_results)
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)
def reply(user): kik.send_messages([ TextMessage(to=user, body="Here are the conditions you most likely have.") ]) gender = db.child("Users").child('ericawng').get().val()['gender'] symptoms = db.child("Users").child('ericawng').get().val()['symptoms'] year = db.child("Users").child('ericawng').get().val()['year'] link = "https://priaid-symptom-checker-v1.p.mashape.com/diagnosis?format=json&gender=" + gender + "&language=en-gb&symptoms=" + symptoms + "&year_of_birth=" + year response = unirest.get( link, headers={ "X-Mashape-Key": "H1C4a5gLxlmshtDy9kaV5b8TNYg1p1lcN7wjsnJUGx0cAL0dlJ", "Accept": "application/json" }) result = response.raw_body result = result.replace("'", '"') j = json.loads(result) if len(j) == 0: kik.send_messages([ TextMessage(to=user, body="Sorry, we don't recognize your condition...") ]) for j1 in j: name = j1['Issue']['Name'] profname = j1['Issue']['ProfName'] accuracy = j1['Issue']['Accuracy'] print(j1) kik.send_messages([ TextMessage(to=user, body="There is a " + str(int(accuracy)) + "% chance that you have " + profname + ", more commonly known as " + name) ]) kik.send_messages( [TextMessage(to=user, body="The closest clinical facilities are:")]) for place in query_result.places: place.get_details() address = gmaps.reverse_geocode( (place.geo_location['lat'], place.geo_location['lng']))[0]['formatted_address'] kik.send_messages([ TextMessage(to=user, body=str(place.name) + "\nAddress: " + str(address) + "\nPhone numeber: " + str(place.local_phone_number)) ])
def test_text_messaging_response_see_no_picture(self): """User chose to see their picture, but they don't have one.""" self.testbot.kik_api.get_user = mock.MagicMock( return_value=self.get_test_user_no_picture()) self.testbot.kik_api.verify_signature = mock.MagicMock( return_value=True) self.testbot.kik_api.send_messages = mock.MagicMock() data = self.get_text_message("Sure! I'd love to!") response = self.app.post('/incoming', data=data, content_type='application/json') self.assertEqual(response.status_code, 200) expected_results = [ TextMessage( to="daveyjones", chat_id= "0ee6d46753bfa6ac2f089149959363f3f59ae62b10cba89cc426490ce38ea92d", body= "It does not look like you have a profile picture, you should set one" ) ] self.testbot.kik_api.send_messages.assert_called_once() self.testbot.kik_api.send_messages.assert_called_once_with( expected_results)
def send_text_response(to, chat_id, body, keyboards=None, hidden=False): message = TextMessage(to=to, chat_id=chat_id, body=body) if keyboards: message.keyboards.append( SuggestedResponseKeyboard(hidden=hidden, responses=keyboards)) kik.send_messages([message])
def test_text_message_with_keyboard(self): message = TextMessage(body='Some text', to='aleem', id='8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0', keyboards=[ SuggestedResponseKeyboard( hidden=True, responses=[TextResponse('Foo')]) ]).to_json() self.assertEqual( message, { 'type': 'text', 'to': 'aleem', 'body': 'Some text', 'id': '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0', 'keyboards': [{ 'type': 'suggested', 'hidden': True, 'responses': [{ 'type': 'text', 'body': 'Foo' }] }] })
def test_start_messaging(self): """Tests that the web framework properly handles a start-messenging event""" self.testbot.kik_api.get_user = mock.MagicMock( return_value=self.get_test_user()) self.testbot.kik_api.verify_signature = mock.MagicMock( return_value=True) self.testbot.kik_api.send_messages = mock.MagicMock() data = self.get_start_chatting_message() response = self.app.post('/incoming', data=data, content_type='application/json') self.assertEqual(response.status_code, 200) expected_result = TextMessage( to="daveyjones", chat_id= "b3be3bc15dbe59931666c06290abd944aaa769bb2ecaaf859bfb65678880afab", body="Hey Davey, how are you?", keyboards=[ SuggestedResponseKeyboard( responses=[TextResponse('Good'), TextResponse('Bad')]) ]) self.testbot.kik_api.send_messages.assert_called_once() self.testbot.kik_api.send_messages.assert_called_once_with( [expected_result])
def test_text_messaging_response_no_see_picture(self): """user chose not to see their picture""" self.testbot.kik_api.get_user = mock.MagicMock( return_value=self.get_test_user_no_picture()) self.testbot.kik_api.verify_signature = mock.MagicMock( return_value=True) self.testbot.kik_api.send_messages = mock.MagicMock() data = self.get_text_message("No Thank You") response = self.app.post('/incoming', data=data, content_type='application/json') self.assertEqual(response.status_code, 200) expected_results = [ TextMessage( to="daveyjones", chat_id= "0ee6d46753bfa6ac2f089149959363f3f59ae62b10cba89cc426490ce38ea92d", body="Ok, Davey. Chat with me again if you change your mind.") ] self.testbot.kik_api.send_messages.assert_called_once() self.testbot.kik_api.send_messages.assert_called_once_with( expected_results)
def test_text_messaging_response_bad(self): """The user's feeling bad today.""" self.testbot.kik_api.get_user = mock.MagicMock( return_value=self.get_test_user()) self.testbot.kik_api.verify_signature = mock.MagicMock( return_value=True) self.testbot.kik_api.send_messages = mock.MagicMock() data = self.get_text_message("Bad") response = self.app.post('/incoming', data=data, content_type='application/json') self.assertEqual(response.status_code, 200) expected_results = [ TextMessage( to="daveyjones", chat_id= "0ee6d46753bfa6ac2f089149959363f3f59ae62b10cba89cc426490ce38ea92d", body="Oh No! :( Wanna see your profile pic?", keyboards=[ SuggestedResponseKeyboard(responses=[ TextResponse("Yep! I Sure Do!"), TextResponse("No Thank You") ]) ]) ] self.testbot.kik_api.send_messages.assert_called_once() self.testbot.kik_api.send_messages.assert_called_once_with( expected_results)
def test_text_message(self): message = TextMessage(body='Some text', to='aleem').to_json() self.assertEqual(message, { 'type': 'text', 'to': 'aleem', 'body': 'Some text' })
def error_handler(message_queue, e, queue, count, sending): """ Error handler called in the event of problems sending the message batch. The aim being to log as many details of the surrounding circumstances, not just the error itself - this will only be called if the Kik API or the Kik servers reject the bundle of messages, which could mean a malformed message or server error. So, if this happens, we need to have the context of the call, not just the error. :param message_queue: :param e: :param queue: :param count: :param sending: :return: """ print("Error encountered during message sending.") print("Sending list length: {}".format(len(sending))) print("Queue: {}".format(queue)) print("Count: {}".format(count)) print("Sending: {}".format(sending)) print(e) try: message_queue.kik.send_messages( TextMessage( to=message_queue.config['admin'], body= "Error encountered during message send. See apache logs for details." )) print("Admin notification sent.") except KikError: print("Admin notify failed.")
def profile_pic_check_messages(user, message): """Function to check if user has a profile picture and returns appropriate messages. :param user: Kik User Object (used to acquire the URL the profile picture) :param message: Kik message received by the bot :return: Message """ messages_to_send = [] profile_picture = user.profile_pic_url if profile_picture is not None: messages_to_send.append( # Another type of message is the PictureMessage - your bot can send a pic to the user! PictureMessage(to=message.from_user, chat_id=message.chat_id, pic_url=profile_picture)) profile_picture_response = "Here's your profile picture!" else: profile_picture_response = "It does not look like you have a profile picture, you should set one" messages_to_send.append( TextMessage(to=message.from_user, chat_id=message.chat_id, body=profile_picture_response)) return messages_to_send
def test_unknown_keyboard_message(self): keyboard_json = {'to': 'aleem', 'type': 'some-unknown-type', 'hidden': False} message = TextMessage.from_json({ 'to': 'aleem', 'participants': ['aleem'], 'chatId': 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2', 'body': 'Some text', 'id': '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0', 'timestamp': 1458336131, 'readReceiptRequested': True, 'keyboards': [keyboard_json] }) self.assertEqual(message.to, 'aleem') self.assertEqual(message.participants, ['aleem']) self.assertEqual(message.chat_id, 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2') self.assertEqual(message.body, 'Some text') self.assertEqual(message.id, '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0') self.assertEqual(message.timestamp, 1458336131) self.assertIs(True, message.read_receipt_requested) self.assertIsInstance(message.keyboards, list) self.assertEqual(len(message.keyboards), 1) self.assertEqual(message.keyboards[0].to, 'aleem') self.assertEqual(message.keyboards[0].type, 'some-unknown-type') self.assertEqual(message.keyboards[0].hidden, False) self.assertEqual(message.keyboards[0].raw_keyboard, keyboard_json)
def profile_pic_check_messages(user, message): """Function to check if user has a profile picture and returns appropriate messages. :param user: Kik User Object (used to acquire the URL the profile picture) :param message: Kik message received by the bot :return: Message """ messages_to_send = [] profile_picture = user.profile_pic_url if profile_picture is not None: messages_to_send.append( # Another type of message is the PictureMessage - your bot can send a pic to the user! PictureMessage(to=message.from_user, chat_id=message.chat_id, pic_url=profile_picture)) profile_picture_response = "ini dia foto kamuu!" else: profile_picture_response = "ga mirip loh, yaudh lah yaa" messages_to_send.append( TextMessage(to=message.from_user, chat_id=message.chat_id, body=profile_picture_response)) return messages_to_send
def abstract_kik_message(to,chat_id,content,msg_type): if msg_type == 'text': return TextMessage(to=to,chat_id=chat_id,body=content) if msg_type == 'image': return PictureMessage(to=to,chat_id=chat_id,pic_url=content) if msg_type == 'link': return LinkMessage(to=to,chat_id=chat_id,url=content)
def test_send_messages_failure(self, post): msgs = [TextMessage(to='aleem', body='Sometext')] with self.assertRaises(KikError) as err: self.api.send_messages(msgs) self.assertEqual(str(err.exception), json.dumps({'error': 'BadRequest'})) self.assertEqual(err.exception.status_code, 400)
def test_response_unexpected(self): """Tests that the bot responds with a message, the picture and another message when texted.""" self.testbot.kik_api.get_user = mock.MagicMock( return_value=self.get_test_user()) self.testbot.kik_api.verify_signature = mock.MagicMock( return_value=True) self.testbot.kik_api.send_messages = mock.MagicMock() data = self.get_text_message("omg r u real?") response = self.app.post('/incoming', data=data, content_type='application/json') self.assertEqual(response.status_code, 200) expected_results = [ TextMessage( to="daveyjones", chat_id= "0ee6d46753bfa6ac2f089149959363f3f59ae62b10cba89cc426490ce38ea92d", body= "Sorry Davey, I didn't quite understand that. How are you?", keyboards=[ SuggestedResponseKeyboard( responses=[TextResponse('Good'), TextResponse('Bad')]) ]) ] self.testbot.kik_api.send_messages.assert_called_once() actual_results = self.testbot.kik_api.send_messages.call_args[0][0] self.assertEqual(actual_results, expected_results)
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)
def send_message(user,chatId,body): kik.send_messages([ TextMessage( to=user, chat_id=chatId, body=body ) ])
def SendResetCancledMessage(messageObject): kik.send_messages([ TextMessage(to=messageObject.from_user, chat_id=messageObject.chat_id, body="Reset Canceled", keyboards=SetKeyboard(messageObject.from_user)) ]) return Response(status=200)
def SendDefaultMessage(messageObject, messageToDelivered): kik.send_messages([ TextMessage(to=messageObject.from_user, chat_id=messageObject.chat_id, body=messageToDelivered, keyboards=SetKeyboard(messageObject.from_user)) ]) return Response(status=200)
def SendNonAdminMessage(messageObject): kik.send_messages([ TextMessage(to=messageObject.from_user, chat_id=messageObject.chat_id, body="Sorry you dont have rights to use this feature..:P", keyboards=SetKeyboard(messageObject.from_user)) ]) return Response(status=200)
def test_text_message_delay(self): message = TextMessage(body='Some text', to='aleem', delay=1500).to_json() self.assertEqual(message, { 'type': 'text', 'to': 'aleem', 'body': 'Some text', 'delay': 1500 })
def test_suggested_keyboard_message(self): message = TextMessage.from_json({ 'to': 'aleem', 'participants': ['aleem'], 'chatId': 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2', 'body': 'Some text', 'id': '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0', 'timestamp': 1458336131, 'readReceiptRequested': True, 'keyboards': [{ 'to': 'aleem', 'type': 'suggested', 'hidden': False, 'responses': [{ 'type': 'text', 'body': 'Ok!' }, { 'type': 'text', 'body': 'No way!' }, { 'type': 'friend-picker', 'body': 'Pick a friend!', 'min': 1, 'max': 5, 'preselected': ['foo', 'bar'] }] }] }) self.assertEqual(message.to, 'aleem') self.assertEqual(message.participants, ['aleem']) self.assertEqual( message.chat_id, 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2') self.assertEqual(message.body, 'Some text') self.assertEqual(message.id, '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0') self.assertEqual(message.timestamp, 1458336131) self.assertIs(True, message.read_receipt_requested) responses = [ TextResponse('Ok!'), TextResponse('No way!'), FriendPickerResponse('Pick a friend!', 1, 5, ['foo', 'bar']) ] self.assertEqual(message.keyboards, [ SuggestedResponseKeyboard( to='aleem', hidden=False, responses=responses) ])
def handle_unknown_message(self, message): userid = message.from_user unknown_response = self.get_unknown_response(userid) self._kik_bot.send_messages([ TextMessage(to=message.from_user, chat_id=message.chat_id, body=unknown_response) ])
def OverridableTextMessagedRecieved(self, messageObject, testData=''): kik.send_messages([ TextMessage(to=messageObject.from_user, chat_id=messageObject.chat_id, body="Hello World" + testData #keyboards = SetKeyboard(messageObject.from_user) ) ]) return Response(status=200)
def handle_text_message(self, message): question = message.body userid = message.from_user answer = self.ask_question(userid, question) self._kik_bot.send_messages([ TextMessage(to=message.from_user, chat_id=message.chat_id, body=answer) ])
def send_text(user, chat_id, body, keyboards=[]): """Send text.""" message = TextMessage(to=user, chat_id=chat_id, body=body) if keyboards: message.keyboards.append( SuggestedResponseKeyboard( to=user, hidden=False, responses=[TextResponse(keyboard) for keyboard in keyboards], )) kik.send_messages([message])
def test_text_message_id(self): message = TextMessage( body='Some text', to='aleem', id='8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0').to_json() self.assertEqual( message, { 'type': 'text', 'to': 'aleem', 'body': 'Some text', 'id': '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0' })
def test_suggested_keyboard_message(self): message = TextMessage.from_json({ 'to': 'aleem', 'participants': ['aleem'], 'chatId': 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2', 'body': 'Some text', 'id': '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0', 'timestamp': 1458336131, 'readReceiptRequested': True, 'keyboards': [ { 'to': 'aleem', 'type': 'suggested', 'hidden': False, 'responses': [ { 'type': 'picture', 'picUrl': 'http://foo.bar', 'metadata': {'some': 'data'} }, { 'type': 'text', 'body': 'Ok!' }, { 'type': 'text', 'body': 'No way!' }, { 'type': 'friend-picker', 'body': 'Pick a friend!', 'min': 1, 'max': 5, 'preselected': ['foo', 'bar'] } ] } ] }) self.assertEqual(message.to, 'aleem') self.assertEqual(message.participants, ['aleem']) self.assertEqual(message.chat_id, 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2') self.assertEqual(message.body, 'Some text') self.assertEqual(message.id, '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0') self.assertEqual(message.timestamp, 1458336131) self.assertIs(True, message.read_receipt_requested) responses = [ PictureResponse('http://foo.bar', {'some': 'data'}), TextResponse('Ok!'), TextResponse('No way!'), FriendPickerResponse('Pick a friend!', 1, 5, ['foo', 'bar']) ] self.assertEqual(message.keyboards, [SuggestedResponseKeyboard(to='aleem', hidden=False, responses=responses)])
def test_text_message_incoming(self): message = TextMessage.from_json({ 'from': 'aleem', 'participants': ['aleem'], 'mention': None, 'chatId': 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2', 'body': 'Some text', 'id': '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0', 'timestamp': 1458336131, 'readReceiptRequested': True }) self.assertEqual(message.from_user, 'aleem') self.assertEqual(message.participants, ['aleem']) self.assertIs(None, message.mention) self.assertEqual(message.chat_id, 'c3ab8ff13720e8ad9047dd39466b3c8974e592c2fa383d4a3960714caef0c4f2') self.assertEqual(message.body, 'Some text') self.assertEqual(message.id, '8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0') self.assertEqual(message.timestamp, 1458336131) self.assertIs(True, message.read_receipt_requested)