Skip to content

Commit

Permalink
Merge branch '2.8.x' into tarsafe-on-2.8.x
Browse files Browse the repository at this point in the history
  • Loading branch information
usc-m authored Oct 13, 2021
2 parents 190684b + 6e30256 commit d28c2e4
Show file tree
Hide file tree
Showing 4 changed files with 152 additions and 27 deletions.
29 changes: 29 additions & 0 deletions changelog/5657.bugfix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
Add List handling in the `send_custom_json` method on `channels/facebook.py`.
Bellow are some examples that could cause en error before.

Example 1: when the whole json is a List
```
[
{
"blocks": {
"type": "progression_bar",
"text": {"text": "progression 1", "level": "1"},
}
},
{"sender": {"id": "example_id"}},
]
```

Example 2: instead of being a Dict, *blocks* is a List when there are 2 *type*
keys under it
```
{
"blocks": [
{"type": "title", "text": {"text": "Conversation progress"}},
{
"type": "progression_bar",
"text": {"text": "Look how far we are...", "level": "1"},
},
]
}
```
16 changes: 12 additions & 4 deletions rasa/core/channels/facebook.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -276,11 +276,19 @@ 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)
elif isinstance(json_message, list):
for message in json_message:
if "sender" in message.keys():
recipient_id = message.pop("sender", {}).pop("id", recipient_id)
break

self.messenger_client.send(json_message, recipient_id, "RESPONSE")

Expand Down
111 changes: 111 additions & 0 deletions tests/core/channels/test_facebook.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
import logging
import pytest
from rasa.core import utils, run
from rasa.core.channels.facebook import MessengerBot
from fbmessenger import MessengerClient

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 = 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")


@pytest.mark.parametrize(
"test_input, expected",
[
(
{
"blocks": [
{"type": "title", "text": {"text": "Conversation progress"}},
{
"type": "progression_bar",
"text": {"text": "progression 1", "level": "1"},
},
]
},
"test_id",
),
(
{
"blocks": [
{"type": "title", "text": {"text": "Conversation progress"}},
{
"type": "progression_bar",
"text": {"text": "progression 1", "level": "1"},
},
],
"sender": {"id": "test_json_id"},
},
"test_json_id",
),
(
{
"blocks": {
"type": "progression_bar",
"text": {"text": "progression 1", "level": "1"},
},
"sender": {"id": "test_json_id_2"},
},
"test_json_id_2",
),
(
[
{
"blocks": {
"type": "progression_bar",
"text": {"text": "progression 1", "level": "1"},
}
},
{"sender": {"id": "test_json_id_3"}},
],
"test_json_id_3",
),
],
)
async def test_facebook_send_custom_json(test_input, expected):
# 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.

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=test_input
)
assert messenger_bot.messenger_client.recipient_id == expected
23 changes: 0 additions & 23 deletions tests/core/test_channels.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,29 +127,6 @@ async def test_console_input():
assert b == {"message": "Test Input", "sender": "default"}


# USED FOR DOCS - don't rename without changing in the docs
def test_facebook_channel():
# START DOC INCLUDE
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)
# END DOC INCLUDE
# the above marker marks the end of the code snipped included
# in the docs
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")


# USED FOR DOCS - don't rename without changing in the docs
def test_webexteams_channel():
# START DOC INCLUDE
Expand Down

0 comments on commit d28c2e4

Please sign in to comment.