diff --git a/README.md b/README.md index d01e219f5e62..8f7a4ee56a2c 100644 --- a/README.md +++ b/README.md @@ -404,4 +404,4 @@ Copyright 2021 Rasa Technologies GmbH. [Copy of the license](LICENSE.txt). A list of the Licenses of the dependencies of the project can be found at the bottom of the -[Libraries Summary](https://libraries.io/github/RasaHQ/rasa). +[Libraries Summary](https://libraries.io/github/RasaHQ/rasa). \ No newline at end of file diff --git a/changelog/5657.improvement.md b/changelog/5657.improvement.md new file mode 100644 index 000000000000..2063dd6cc3da --- /dev/null +++ b/changelog/5657.improvement.md @@ -0,0 +1 @@ +Add list handling in the `send_custom_json` method on `channels/facebook.py`. diff --git a/rasa/core/channels/facebook.py b/rasa/core/channels/facebook.py index 16b4a6568ab7..4526a9b76e0b 100644 --- a/rasa/core/channels/facebook.py +++ b/rasa/core/channels/facebook.py @@ -10,7 +10,7 @@ import rasa.shared.utils.io from sanic import Blueprint, response from sanic.request import Request -from typing import Text, List, Dict, Any, Callable, Awaitable, Iterable, Optional +from typing import Text, List, Dict, Any, Callable, Awaitable, Iterable, Optional, Union from rasa.core.channels.channel import UserMessage, OutputChannel, InputChannel from sanic.response import HTTPResponse @@ -276,11 +276,14 @@ async def send_elements( self.messenger_client.send(payload, recipient_id, "RESPONSE") async def send_custom_json( - self, recipient_id: Text, json_message: Dict[Text, Any], **kwargs: Any + self, + recipient_id: Text, + json_message: Union[List, Dict[Text, Any]], + **kwargs: Any, ) -> None: """Sends custom json data to the output.""" - - recipient_id = json_message.pop("sender", {}).pop("id", None) or recipient_id + if isinstance(json_message, dict) and "sender" in json_message.keys(): + recipient_id = json_message.pop("sender", {}).pop("id", recipient_id) self.messenger_client.send(json_message, recipient_id, "RESPONSE") diff --git a/tests/test_facebook.py b/tests/test_facebook.py new file mode 100644 index 000000000000..ec2f269f1638 --- /dev/null +++ b/tests/test_facebook.py @@ -0,0 +1,91 @@ +import logging +from rasa.core.channels.facebook import MessengerBot +from fbmessenger import MessengerClient + +from _pytest.monkeypatch import MonkeyPatch + +import rasa.core.run +from rasa.core import utils + + +# this is needed so that the tests included as code examples look better +from tests.utilities import json_of_latest_request, latest_request + +logger = logging.getLogger(__name__) + + +def test_facebook_channel(): + from rasa.core.channels.facebook import FacebookInput + + input_channel = FacebookInput( + fb_verify="YOUR_FB_VERIFY", + # you need tell facebook this token, to confirm your URL + fb_secret="YOUR_FB_SECRET", # your app secret + fb_access_token="YOUR_FB_PAGE_ACCESS_TOKEN" + # token for the page you subscribed to + ) + + s = rasa.core.run.configure_app([input_channel], port=5004) + + routes_list = utils.list_routes(s) + + assert routes_list["fb_webhook.health"].startswith("/webhooks/facebook") + assert routes_list["fb_webhook.webhook"].startswith("/webhooks/facebook/webhook") + + +async def test_facebook_send_custom_json(): + # This function tests cases when the custom json is a list + # The send_custom_json function doesn't return anything. Rather + # it calls an object MessengerClient, that will + # then make a post request. + # Since the purpose is to test the extraction of the recipient_id + # by the MessengerBot.send_custom_json_list we + # modify MessengerClient (from the fbmessenger pypackage) to + # return the recipient ID. + + json_without_id = { + "blocks": [ + {"type": "title", "text": {"text": "Conversation progress"}}, + { + "type": "progression_bar", + "text": {"text": "progression 1", "level": "1"}, + }, + ] + } + json_with_id = { + "blocks": [ + {"type": "title", "text": {"text": "Conversation progress"}}, + { + "type": "progression_bar", + "text": {"text": "progression 1", "level": "1"}, + }, + ], + "sender": {"id": "test_json_id"}, + } + + class TestableMessengerClient(MessengerClient): + def __init__(self, page_access_token, **kwargs): + self.recipient_id = "" + super(TestableMessengerClient, self).__init__(page_access_token, **kwargs) + + def send( + self, + payload, + recipient_id, + messaging_type="RESPONSE", + notification_type="REGULAR", + timeout=None, + tag=None, + ): + self.recipient_id = recipient_id + + messenger_client = TestableMessengerClient(page_access_token="test_token") + messenger_bot = MessengerBot(messenger_client) + await messenger_bot.send_custom_json( + recipient_id="test_id", json_message=json_without_id + ) + assert messenger_bot.messenger_client.recipient_id == "test_id" + await messenger_bot.send_custom_json( + recipient_id="test_id", json_message=json_with_id + ) + assert messenger_bot.messenger_client.recipient_id == "test_json_id"