This repository has been archived by the owner on Aug 22, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1k
added socketio channel implementation #987
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,144 @@ | ||
from __future__ import absolute_import | ||
from __future__ import division | ||
from __future__ import print_function | ||
from __future__ import unicode_literals | ||
|
||
import logging | ||
import socketio | ||
from flask import Blueprint, jsonify | ||
from typing import Optional, Text | ||
|
||
from rasa_core.channels import InputChannel | ||
from rasa_core.channels.channel import ( | ||
UserMessage, | ||
OutputChannel) | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
|
||
class SocketBlueprint(Blueprint): | ||
def __init__(self, sio, *args, **kwargs): | ||
self.sio = sio | ||
super(SocketBlueprint, self).__init__(*args, **kwargs) | ||
|
||
def register(self, app, options, first_registration=False): | ||
app.wsgi_app = socketio.Middleware(self.sio, app.wsgi_app) | ||
super(SocketBlueprint, self).register(app, options, first_registration) | ||
|
||
|
||
class SocketIOOutput(OutputChannel): | ||
|
||
@classmethod | ||
def name(cls): | ||
return "socketio" | ||
|
||
def __init__(self, sio, bot_message_evt): | ||
self.sio = sio | ||
self.bot_message_evt = bot_message_evt | ||
|
||
def send(self, recipient_id, message): | ||
# type: (Text, Any) -> None | ||
"""Sends a message to the recipient.""" | ||
self.sio.emit(message, room=recipient_id) | ||
|
||
def _send_message(self, recipient_id, response): | ||
# type: (Text, Any) -> None | ||
"""Sends a message to the recipient using the bot event.""" | ||
self.sio.emit(self.bot_message_evt, response, room=recipient_id) | ||
|
||
def send_text_message(self, recipient_id, message): | ||
# type: (Text, Text) -> None | ||
"""Send a message through this channel.""" | ||
|
||
self._send_message(recipient_id, {"text": message}) | ||
|
||
def send_image_url(self, recipient_id, image_url): | ||
# type: (Text, Text) -> None | ||
"""Sends an image. Default will just post the url as a string.""" | ||
message = { | ||
"attachment": { | ||
"type": "image", | ||
"payload": {"src": image_url} | ||
} | ||
} | ||
self._send_message(recipient_id, message) | ||
|
||
def send_text_with_buttons(self, recipient_id, text, buttons, **kwargs): | ||
# type: (Text, Text, List[Dict[Text, Any]], **Any) -> None | ||
"""Sends buttons to the output.""" | ||
|
||
message = { | ||
"text": text, | ||
"quick_replies": [] | ||
} | ||
|
||
for button in buttons: | ||
message["quick_replies"].append({ | ||
"content_type": "text", | ||
"title": button['title'], | ||
"payload": button['payload'] | ||
}) | ||
|
||
self._send_message(recipient_id, message) | ||
|
||
def send_custom_message(self, recipient_id, elements): | ||
# type: (Text, List[Dict[Text, Any]]) -> None | ||
"""Sends elements to the output.""" | ||
|
||
message = {"attachment": { | ||
"type": "template", | ||
"payload": { | ||
"template_type": "generic", | ||
"elements": elements[0] | ||
}}} | ||
|
||
self._send_message(recipient_id, message) | ||
|
||
|
||
class SocketIOInput(InputChannel): | ||
"""A socket.io input channel.""" | ||
|
||
@classmethod | ||
def name(cls): | ||
return "socketio" | ||
|
||
@classmethod | ||
def from_credentials(cls, credentials): | ||
credentials = credentials or {} | ||
return cls(credentials.get("user_message_evt", "user_uttered"), | ||
credentials.get("bot_message_evt", "bot_uttered"), | ||
credentials.get("namespace")) | ||
|
||
def __init__(self, | ||
user_message_evt="user_uttered", # type: Text | ||
bot_message_evt="bot_uttered", # type: Text | ||
namespace=None # type: Optional[Text] | ||
): | ||
self.bot_message_evt = bot_message_evt | ||
self.user_message_evt = user_message_evt | ||
self.namespace = namespace | ||
|
||
def blueprint(self, on_new_message): | ||
sio = socketio.Server() | ||
socketio_webhook = SocketBlueprint(sio, 'socketio_webhook', __name__) | ||
|
||
@socketio_webhook.route("/", methods=['GET']) | ||
def health(): | ||
return jsonify({"status": "ok"}) | ||
|
||
@sio.on('connect', namespace=self.namespace) | ||
def connect(sid, environ): | ||
logger.debug("User {} connected to socketio endpoint.".format(sid)) | ||
|
||
@sio.on('disconnect', namespace=self.name()) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. why is this There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. good spot, should be namespace as well 👍 |
||
def disconnect(sid): | ||
logger.debug("User {} disconnected from socketio endpoint." | ||
"".format(sid)) | ||
|
||
@sio.on(self.user_message_evt, namespace=self.namespace) | ||
def handle_message(sid, data): | ||
output_channel = SocketIOOutput(sio, self.bot_message_evt) | ||
message = UserMessage(data['message'], output_channel, sid) | ||
on_new_message(message) | ||
|
||
return socketio_webhook |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -39,3 +39,4 @@ pymongo==3.5.1 | |
python-dateutil==2.7.3 | ||
rocketchat_API==0.6.22 | ||
flask-jwt-simple==0.0.3 | ||
python-socketio==2.0.0 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
what's this namespace for? if we're reading it from the credentials file it should also be explained in the docs right?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
no clue :D didn't read the socket io docs - but i think it allows you to use the same message names in different contexts. don't think it is important though.