Skip to content

Commit

Permalink
Quick Replies (digiteinfotech#1156)
Browse files Browse the repository at this point in the history
* 1. Added convertor function for the quick_replies and quick_reply slot
2. Added and fixed  test cases related to that.

* 1. Added convertor function for the quick_replies and quick_reply slot
2. Added and fixed  test cases related to that.

* Added test cases for the coverage issue.

---------

Co-authored-by: Mahesh <[email protected]>
  • Loading branch information
maheshsattala and Mahesh authored Mar 13, 2024
1 parent a08645c commit 1fe874a
Show file tree
Hide file tree
Showing 9 changed files with 189 additions and 48 deletions.
25 changes: 25 additions & 0 deletions kairon/chat/converters/channels/messenger.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,29 @@ def button_transformer(self, message):
except Exception as ex:
raise Exception(f"Exception in MessengerResponseConverter::button_transformer: {str(ex)}")

def quick_reply_transformer(self, message):
try:
quick_replies_json_temp = {}
jsoniterator = ElementTransformerOps.json_generator(message)
quick_replies = []
body_default = ElementTransformerOps.getChannelConfig(self.channel, "body_message")
for item in jsoniterator:
if item.get("type") == ElementTypes.QUICK_REPLY.value:
title = ElementTransformerOps.json_generator(item.get("children"))
for titletext in title:
text = titletext.get("text")
quick_reply_body = {}
if item.get('content_type') == "text":
quick_reply_body.update({"content_type": "text", "title": text,
"payload": item.get("value"), "image_url": item.get("image_url")})
else:
quick_reply_body.update({"content_type": text})
quick_replies.append(quick_reply_body)
quick_replies_json_temp.update({"text": body_default, "quick_replies": quick_replies})
return quick_replies_json_temp
except Exception as ex:
raise Exception(f"Exception in MessengerResponseConverter::quick_reply_transformer: {str(ex)}")

async def messageConverter(self, message):
try:
if self.message_type == ElementTypes.IMAGE.value:
Expand All @@ -64,5 +87,7 @@ async def messageConverter(self, message):
return super().video_transformer(message)
elif self.message_type == ElementTypes.BUTTON.value:
return self.button_transformer(message)
elif self.message_type == ElementTypes.QUICK_REPLY.value:
return self.quick_reply_transformer(message)
except Exception as ex:
raise Exception(f"Error in MessengerResponseConverter::messageConverter {str(ex)}")
5 changes: 4 additions & 1 deletion kairon/chat/handlers/channels/messenger.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import hashlib
import hmac
import json
import logging
from typing import Text, List, Dict, Any, Iterable, Optional, Union
import rasa.shared.utils.io
Expand Down Expand Up @@ -123,7 +124,9 @@ async def message(
# quick reply and user message both share 'text' attribute
# so quick reply should be checked first
if self._is_quick_reply_message(message):
text = message["message"]["quick_reply"]["payload"]
payload = message["message"]["quick_reply"]["payload"]
entity = json.dumps({"quick_reply": payload})
text = f"/k_quick_reply{entity}"
elif self._is_user_message(message):
text = message["message"]["text"]
elif self._is_audio_message(message):
Expand Down
2 changes: 2 additions & 0 deletions kairon/shared/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ class ElementTypes(str, Enum):
AUDIO = "audio"
BUTTON = "button"
DROPDOWN = "dropdown"
QUICK_REPLY = "quick_reply"


class WhatsappBSPTypes(str, Enum):
Expand Down Expand Up @@ -148,6 +149,7 @@ class KaironSystemSlots(str, Enum):
longitude = "longitude"
latitude = "latitude"
flow_reply = "flow_reply"
quick_reply = "quick_reply"
http_status_code = "http_status_code"


Expand Down
2 changes: 1 addition & 1 deletion metadata/message_template.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type_list: ["image","link","video","button","dropdown","audio"]
type_list: ["image","link","video","button","quick_reply","dropdown","audio"]
slack:
image: '{
"blocks": [
Expand Down
23 changes: 23 additions & 0 deletions tests/integration_test/chat_service_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,29 @@ def test_business_messages_with_valid_data(mock_business_messages, mock_credenti
assert actual == {"status": "OK"}


def test_messenger_with_quick_reply():
def _mock_validate_hub_signature(*args, **kwargs):
return True

with patch.object(MessengerHandler, "validate_hub_signature", _mock_validate_hub_signature):
with patch.object(KaironAgent, "handle_message") as mock_agent:
mock_agent.side_effect = mock_agent_response
response = client.post(
f"/api/bot/messenger/{bot}/{token}",
headers={"Authorization": "Bearer Test"},
json={'object': 'page', 'entry': [{'id': '193566777888505', 'time': 1709550920950, 'messaging': [
{'sender': {'id': '715782344534303980'},
'recipient': {'id': '19357777855505'},
'timestamp': 174739433964,
'message': {
'mid': 'm_l5_0QHbTfskfIL-rZjh_PJsdksjdlkj6VRBodfud98dXFD3-XljmN-sRqfXnAGA99uu42alStBFiOjujUog',
'text': '+919876543210',
'quick_reply': {'payload': '+919876543210'}}}]}]}
)
actual = response.json()
assert actual == "success"


def test_chat():
with patch.object(Utility, "get_local_mongo_store") as mocked:
mocked.side_effect = empty_store
Expand Down
6 changes: 3 additions & 3 deletions tests/integration_test/services_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -2937,7 +2937,7 @@ def test_list_entities_empty():
)
actual = response.json()
assert actual["error_code"] == 0
assert len(actual['data']) == 12
assert len(actual['data']) == 13
assert actual["success"]


Expand Down Expand Up @@ -3063,7 +3063,7 @@ def test_list_entities():
assert {e['name'] for e in actual["data"]} == {'bot', 'file', 'category', 'file_text', 'ticketid', 'file_error',
'priority', 'requested_slot', 'fdresponse', 'kairon_action_response',
'audio', 'image', 'doc_url', 'document', 'video', 'order', 'latitude',
'longitude', 'flow_reply', 'http_status_code'}
'longitude', 'flow_reply', 'quick_reply', 'http_status_code'}
assert actual["success"]


Expand Down Expand Up @@ -3464,7 +3464,7 @@ def test_get_slots():
)
actual = response.json()
assert "data" in actual
assert len(actual["data"]) == 19
assert len(actual["data"]) == 20
assert actual["success"]
assert actual["error_code"] == 0
assert Utility.check_empty_string(actual["message"])
Expand Down
45 changes: 42 additions & 3 deletions tests/testing_data/channel_data/channel_data.json
Original file line number Diff line number Diff line change
Expand Up @@ -151,10 +151,49 @@
"type":"paragraph",
"children":[{"text":""}]
}],
"button_one": [{"type":"button","value":"single button is clicked","id":"5","children":[{"text":"One"}]},{"type":"paragraph","children":[{"text":""}]}],
"button_two": [{"type":"button","value":"seeds are treated with Bavistin","id":"1","children":[{"text":"Yes"}]},
"quick_reply_one": [{"type": "quick_reply", "content_type": "text", "value": "single button is clicked",
"image_url": "https://buffer.com/library/content/images/size/w1200/2023/10/free-images.jpg",
"id": "3", "children": [{"text": "One"}]}],
"quick_reply_two": [
{"type": "quick_reply", "content_type": "text", "value": "single button is clicked",
"image_url": "https://buffer.com/library/content/images/size/w1200/2023/10/free-images.jpg",
"id": "3", "children": [{"text": "One"}]},
{"type": "quick_reply", "content_type": "phone_number", "value": "", "image_url": "", "id": "2",
"children": [{"text": "9876543210"}]}
],
"quick_reply_three": [
{"type": "quick_reply", "content_type": "text", "value": "single button is clicked",
"image_url": "", "id": "3", "children": [{"text": "One"}]},
{"type": "quick_reply", "content_type": "phone_number", "value": "", "image_url": "", "id": "2",
"children": [{"text": "9876543210"}]},
{"type": "quick_reply", "content_type": "email", "value": "", "image_url": "", "id": "1",
"children": [{"text": "[email protected]"}]}
],
"messenger_quick_reply_op_one": {
"text": "Please select from quick buttons:",
"quick_replies": [{"content_type": "text", "title": "One", "payload": "single button is clicked",
"image_url": "https://buffer.com/library/content/images/size/w1200/2023/10/free-images.jpg"}]
},
"messenger_quick_reply_op_two": {
"text": "Please select from quick buttons:",
"quick_replies": [{"content_type": "text", "title": "One", "payload": "single button is clicked",
"image_url": "https://buffer.com/library/content/images/size/w1200/2023/10/free-images.jpg"},
{"content_type": "9876543210"}]
},
"messenger_quick_reply_op_three": {
"text": "Please select from quick buttons:",
"quick_replies": [{"content_type": "text", "title": "One", "payload": "single button is clicked", "image_url": ""},
{"content_type": "9876543210"},
{"content_type": "[email protected]"}]},
"button_one": [
{"type":"button","value":"single button is clicked","id":"5","children":[{"text":"One"}]},
{"type":"paragraph","children":[{"text":""}]}
],
"button_two": [
{"type":"button","value":"seeds are treated with Bavistin","id":"1","children":[{"text":"Yes"}]},
{"type":"button","value":"Bavistin is not sprayed on seeds","id":"2","children":[{"text":"No"}]},
{"type":"paragraph","children":[{"text":""}]}],
{"type":"paragraph","children":[{"text":""}]}
],
"button_three": [{"type":"button","value":"Vegetables only","id":"2","children":[{"text":"Veg"}]},
{"type":"button","value":"fish food served","id":"3","children":[{"text":"Non-veg"}]},
{"type":"button","value":"Only Desert food","id":"4","children":[{"text":"Desert"}]},
Expand Down
Loading

0 comments on commit 1fe874a

Please sign in to comment.