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_message_inequality(self): message1 = PictureMessage( pic_url='http://foo.bar/image', to='aleem', mention='anotherbot', chat_id= 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', keyboards=[ SuggestedResponseKeyboard(hidden=True, responses=[TextResponse('Foo')]) ], attribution=CustomAttribution(name='Foobar Not The Same'), delay=100) message2 = PictureMessage( pic_url='http://foo.bar/image', to='aleem', mention='anotherbot', chat_id= 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', keyboards=[ SuggestedResponseKeyboard(hidden=True, responses=[TextResponse('Foo')]) ], attribution=CustomAttribution(name='Foobar'), delay=100) self.assertNotEqual(message1, message2)
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 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 keyboard_admin_confirm_manual(): """ Keyboard for confirming a manual message. :return: """ return [ TextResponse(BUTTONS['admin_confirm_manual']), TextResponse(BUTTONS['admin_reset']), ]
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 keyboard_admin_default(): """ Create default keyboard responses that are sent to an admin user. :return: An array with the responses that should be sent on the present message. """ return [ TextResponse(BUTTONS['admin_send_feel']), TextResponse(BUTTONS['admin_status']), TextResponse(BUTTONS['admin_send_manual']), ]
def keyboard_admin_approval(): """ Keyboard for approving or blocking a new feels message. :return: """ return [ TextResponse(BUTTONS['admin_approve']), TextResponse(BUTTONS['admin_block']), TextResponse(BUTTONS['admin_reset']), ]
def seeResultsOnWebsite(chat_id, context): from_user = context['from_user'] img_url = context['user_img_url'] msg = LinkMessage(to=from_user, chat_id=chat_id, url='http://gofindfashion.com?' + img_url, title="Go Find Fashion Seach Engine") msg.keyboards.append( SuggestedResponseKeyboard(responses=[ TextResponse('See more results'), TextResponse('Search with this pic'), TextResponse('New search') ])) kik.send_messages([msg])
def keyboard_admin_status(): """ Keyboard for the system status report, allowing options related to the status. :return: """ keyboard = [] with FeelsTable() as table: if table.count_need_approval() > 0: keyboard += [ TextResponse(BUTTONS['admin_approve_new']), ] keyboard += [ TextResponse(BUTTONS['admin_reset']), ] return keyboard
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 SendResetMessage(messageObject): kik.send_messages([ TextMessage( to=messageObject.from_user, chat_id=messageObject.chat_id, body= "Resetting will clear all previously recorded member data. Do you wish to continue?", keyboards=[ SuggestedResponseKeyboard( to=messageObject.from_user, hidden=True, responses=[TextResponse('YES'), TextResponse('NO')]) ]) ]) return Response(status=200)
def selectAnImageMsg(chat_id, context): from_user = context['from_user'] responses = [ TextResponse('Digging the first one'), TextResponse('Like the second'), TextResponse("Let's go with the third"), TextResponse('See more like this'), TextResponse('New search') ] # if context['search_type'] == 'image': # responses.append(TextResponse('See results on the GoFindFashion website')) # website down for now select_an_image_msg = TextMessage(to=from_user, chat_id=chat_id, body=canned_responses.show_outfits()) select_an_image_msg.keyboards.append( SuggestedResponseKeyboard(responses=responses)) kik.send_messages([select_an_image_msg])
def test_link_message_complete(self): message = LinkMessage( url='http://foo.bar', to='aleem', mention='anotherbot', chat_id= 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', title='A Title', text='Some Text', pic_url='http://foo.bar/image', no_forward=True, kik_js_data='foobar', keyboards=[ SuggestedResponseKeyboard(hidden=True, responses=[TextResponse('Foo')]) ], attribution=CustomAttribution(name='Foobar'), delay=100).to_json() self.assertEqual( message, { 'type': 'link', 'to': 'aleem', 'url': 'http://foo.bar', 'mention': 'anotherbot', 'chatId': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'title': 'A Title', 'text': 'Some Text', 'picUrl': 'http://foo.bar/image', 'noForward': True, 'kikJsData': 'foobar', 'keyboards': [{ 'type': 'suggested', 'hidden': True, 'responses': [{ 'type': 'text', 'body': 'Foo' }] }], 'attribution': { 'name': 'Foobar' }, 'delay': 100 })
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_video_message_complete(self): message = VideoMessage( video_url='http://foo.bar/vid', to='aleem', mention='anotherbot', chat_id= 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', autoplay=True, muted=True, loop=True, no_save=True, keyboards=[ SuggestedResponseKeyboard(hidden=True, responses=[TextResponse('Foo')]) ], attribution=CustomAttribution(name='Foobar'), delay=100).to_json() self.assertEqual( message, { 'type': 'video', 'to': 'aleem', 'mention': 'anotherbot', 'chatId': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'videoUrl': 'http://foo.bar/vid', 'muted': True, 'loop': True, 'autoplay': True, 'noSave': True, 'keyboards': [{ 'type': 'suggested', 'hidden': True, 'responses': [{ 'type': 'text', 'body': 'Foo' }] }], 'attribution': { 'name': 'Foobar' }, 'delay': 100 })
def send_message_with_responses(self, message, responses): text_responses = [] for response in responses: text_responses.append(TextResponse(response)) self.response_messages.append( TextMessage(to=self.message.from_user, chat_id=self.message.chat_id, body=message, keyboards=[ SuggestedResponseKeyboard(responses=text_responses) ]))
def SetKeyboard(user): if user in adminlist: Keyboard = [SuggestedResponseKeyboard( to=user, hidden=True, responses=[TextResponse('Set Probe'), TextResponse('Benchmark Analysis'), TextResponse('Probe Analysis'), TextResponse('Inactive Analysis'), TextResponse('Reset Benchmark')] )] else: Keyboard = [SuggestedResponseKeyboard( to=user, hidden=True, responses=[TextResponse('Set Probe'), TextResponse('Benchmark Analysis'), TextResponse('Probe Analysis'), TextResponse('Inactive Analysis'), TextResponse('Help')] )] return Keyboard
def test_set_configuration(self, post): config = Configuration(webhook='https://example.com/incoming', features={'manuallySendReadReceipts': True}, static_keyboard=SuggestedResponseKeyboard( responses=[TextResponse('foo')])) response = self.api.set_configuration(config) self.assertEqual(post.call_count, 1) self.assertEqual(post.call_args[0][0], 'https://api.kik.com/v1/config') self.assertEqual(post.call_args[1]['timeout'], 60) self.assertEqual(post.call_args[1]['auth'], ('mybotusername', 'mybotapikey')) self.assertEqual(post.call_args[1]['headers'], {'Content-Type': 'application/json'}) self.assertEqual( json.loads(post.call_args[1]['data']), { 'webhook': 'https://example.com/incoming', 'features': { 'manuallySendReadReceipts': True }, 'staticKeyboard': { 'type': 'suggested', 'responses': [{ 'type': 'text', 'body': 'foo' }] } }) self.assertIsInstance(response, Configuration) self.assertEqual(response.webhook, 'https://example.com/incoming') self.assertEqual(response.features, {'manuallySendReadReceipts': True}) self.assertIsInstance(response.static_keyboard, SuggestedResponseKeyboard) self.assertEqual( response.static_keyboard, SuggestedResponseKeyboard(responses=[TextResponse('foo')]))
def __choose_response(self, message): messages = [] response = self.engine.computeResponse(message.body) message = TextMessage(to=message.from_user, chat_id=message.chat_id, body=response) message.keyboards.append( SuggestedResponseKeyboard(hidden=False, responses=[TextResponse('OK')])) messages.append(message) return messages
def test_get_configuration(self, get): config = self.api.get_configuration() get.assert_called_once_with('https://api.kik.com/v1/config', timeout=60, auth=('mybotusername', 'mybotapikey')) self.assertIsInstance(config, Configuration) self.assertEqual(config.webhook, 'https://example.com/incoming') self.assertEqual(config.features, {'manuallySendReadReceipts': True}) self.assertIsInstance(config.static_keyboard, SuggestedResponseKeyboard) self.assertEqual( config.static_keyboard, SuggestedResponseKeyboard(responses=[TextResponse('foo')]))
def test_text_message_with_all_keyboard_types(self): message = TextMessage( body='Some text', to='aleem', id='8e7fc0ad-36aa-43dd-8c5f-e72f5f2ed7e0', keyboards=[ SuggestedResponseKeyboard( hidden=True, responses=[ PictureResponse('http://foo.bar', {'some': 'data'}), FriendPickerResponse('Foo', 7, 16, ['bar', 'dar']), TextResponse('Bar') ]) ]).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': 'picture', 'picUrl': 'http://foo.bar', 'metadata': { 'some': 'data' } }, { 'type': 'friend-picker', 'body': 'Foo', 'min': 7, 'max': 16, 'preselected': ['bar', 'dar'] }, { 'type': 'text', 'body': 'Bar' }] }] })
def sendKikMessages(chat_id,from_user,msgs,suggested_responses=[],msg_type=None): send_these = [] for msg in msgs: send_these.append(abstract_kik_message( to=from_user, chat_id=chat_id, content=msg, msg_type=msg_type )) if msg_type == 'text' and suggested_responses: text_resonses = [TextResponse(r) for r in suggested_responses] send_these[-1].keyboards.append( SuggestedResponseKeyboard( responses=text_resonses ) ) kik.send_messages(send_these)
def test_to_json(self): config = Configuration(webhook='https://mybot.com/incoming', features={'manuallySendReadReceipts': True}, static_keyboard=SuggestedResponseKeyboard( responses=[TextResponse('foo')])) self.assertEqual( config.to_json(), { 'webhook': 'https://mybot.com/incoming', 'features': { 'manuallySendReadReceipts': True }, 'staticKeyboard': { 'type': 'suggested', 'responses': [{ 'type': 'text', 'body': 'foo' }] } })
def test_from_json(self): config = Configuration.from_json({ 'webhook': 'https://mybot.com/incoming', 'features': { 'manuallySendReadReceipts': True }, 'staticKeyboard': { 'type': 'suggested', 'responses': [{ 'type': 'text', 'body': 'foo' }] } }) self.assertEqual(config.webhook, 'https://mybot.com/incoming') self.assertEqual(config.features, {'manuallySendReadReceipts': True}) self.assertIsInstance(config.static_keyboard, SuggestedResponseKeyboard) self.assertEqual( config.static_keyboard, SuggestedResponseKeyboard(responses=[TextResponse('foo')]))
def test_picture_message_complete(self): message = PictureMessage( pic_url='http://foo.bar/image', to='aleem', mention='anotherbot', chat_id= 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', keyboards=[ SuggestedResponseKeyboard(hidden=True, responses=[TextResponse('Foo')]) ], attribution=CustomAttribution(name='Foobar'), delay=100).to_json() self.assertEqual( message, { 'type': 'picture', 'to': 'aleem', 'mention': 'anotherbot', 'chatId': 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', 'picUrl': 'http://foo.bar/image', 'keyboards': [{ 'type': 'suggested', 'hidden': True, 'responses': [{ 'type': 'text', 'body': 'Foo' }] }], 'attribution': { 'name': 'Foobar' }, 'delay': 100 })
def SetKeyboard(user): if user in adminlist: Keyboard = [ SuggestedResponseKeyboard(to=user, hidden=True, responses=[ TextResponse('BENCHMARK ANALYSIS'), TextResponse('PROBE ANALYSIS'), TextResponse('INACTIVE ANALYSIS'), TextResponse('RESET BENCHMARK') ]) ] else: Keyboard = [ SuggestedResponseKeyboard(to=user, hidden=True, responses=[ TextResponse('BENCHMARK ANALYSIS'), TextResponse('PROBE ANALYSIS'), TextResponse('INACTIVE ANALYSIS') ]) ] return Keyboard
resetUser = "" MessageHandler = MessageBuilder() app = Flask(__name__) kik = KikApi('BOTID', 'API_KEY') #-------------------------KIK BOT CONFIG------------------------------------------------------ afeatures = { "manuallySendReadReceipts": False, "receiveReadReceipts": True, "receiveDeliveryReceipts": False, "receiveIsTyping": False } staticKeyboard = SuggestedResponseKeyboard(responses=[ TextResponse('BENCHMARK ANALYSIS'), TextResponse('PROBE ANALYSIS'), TextResponse('INACTIVE ANALYSIS'), TextResponse('HELP') ]) kik.set_configuration( Configuration(webhook='WEBHOOK', features=afeatures, static_keyboard=staticKeyboard)) banlist = "" #list of users to have privadged access to reset benchmark adminlist = {}
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)
def buyThis(chat_id, context): """ User has selected a picture she likes, and would like to visit the store webpage """ from_user = context['from_user'] prev_context = retrieveContext(chat_id, from_user) if 'image_query_result' not in prev_context and 'text_query_result' not in prev_context: say(chat_id, context, canned_responses.error_message() + 'query results issue') elif 'selected_outfit' not in prev_context: say(chat_id, context, canned_responses.error_message() + 'selection issuse') else: i = int(prev_context['selected_outfit']) - 1 if prev_context['search_type'] == 'image': i = int( prev_context['image_query_result_index']) - SHOW_THIS_MANY + i link = prev_context['image_query_result']['images'][i]['pageUrl'] title = prev_context['image_query_result']['images'][i]['title'] img_url = prev_context['image_query_result']['images'][i][ 'imageUrl'] # using a text message to send fitroom results because Kik breaks out links by putting a trailing "/" link_message = TextMessage(to=from_user, chat_id=chat_id, body=link) # link_message = LinkMessage(to=from_user,chat_id=chat_id,url=link,title=title) elif prev_context['search_type'] == 'text': i = int( prev_context['text_query_result_index']) - SHOW_THIS_MANY + i img_url = prev_context['text_query_result']['products'][i][ 'image']['sizes']['IPhone']['url'] link = prev_context['text_query_result']['products'][i]['clickUrl'] title = prev_context['text_query_result']['products'][i][ 'brandedName'] link_message = LinkMessage(to=from_user, chat_id=chat_id, url=link, title=title) if context['platform'] == 'KIK': here = TextMessage(to=from_user, chat_id=chat_id, body="Here ya go:") tip = TextMessage( to=from_user, chat_id=chat_id, body= "Remember you can search again anytime by sending me a pic ;)") tip.keyboards.append( SuggestedResponseKeyboard(responses=[ TextResponse('See more results'), TextResponse('Search with this pic'), TextResponse('New search') ])) kik.send_messages([here, link_message, tip]) elif context['platform'] == 'FB': dispatchMessage(context, 'link', chat_id, from_user, [link], suggested_responses=[title], extras=[img_url])