Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import inspect
- import emoji
- import logging
- import json
- from abc import ABC
- from typing import Text, Optional, Callable, Awaitable, Dict, Any
- from rasa.core.channels import InputChannel, UserMessage, OutputChannel
- from sanic import response, Blueprint
- from sanic.request import Request
- from sanic.response import HTTPResponse
- logger = logging.getLogger(__name__)
- def _give_emoji_free_text(text):
- allchars = [str for str in text]
- emoji_list = [c for c in allchars if c in emoji.UNICODE_EMOJI]
- clean_text = text
- for em in emoji_list:
- clean_text = clean_text.replace(em, '')
- return clean_text.lower()
- def _process_request(req: Request):
- sender_id = req.json.get("sender", None)
- text = req.json.get("message", None)
- text = emoji.emojize(text, use_aliases=True)
- text = _give_emoji_free_text(text)
- message_id = req.json.get("message_id", None)
- return UserMessage(
- sender_id=sender_id,
- text=text,
- message_id=message_id,
- output_channel=CustomOutput()
- )
- class CustomOutput(OutputChannel, ABC):
- def __init__(self):
- self.options = None
- self.utter = None
- async def send_response(self, recipient_id: Text, message: Dict[Text, Any]) -> None:
- # logger.warn(json.dumps(message, default=lambda o: o.__dict__, sort_keys=True, indent=4))
- self.options = message['custom'] or None
- self.utter = message['text'] or None
- class CustomInput(InputChannel):
- @classmethod
- def name(cls) -> Text:
- return "customInput"
- def blueprint(self, on_new_message: Callable[[UserMessage], Awaitable[None]]):
- custom_webhook = Blueprint(
- "custom_webhook_{}".format(type(self).__name__),
- inspect.getmodule(self).__name__,
- )
- @custom_webhook.route("/", methods=["GET"])
- def health(request: Request) -> HTTPResponse:
- return response.json({"status": "ok"})
- @custom_webhook.route("/webhook", methods=["POST"])
- async def receive(request: Request) -> HTTPResponse:
- user_message = _process_request(request)
- # logger.warn(json.dumps(user_message, default=lambda o: o.__dict__, sort_keys=True, indent=4))
- await on_new_message(user_message)
- # logger.warn(json.dumps(user_message, default=lambda o: o.__dict__, sort_keys=True, indent=4))
- return response.json({
- "utter": user_message.output_channel.utter,
- "options": user_message.output_channel.options
- })
- return custom_webhook
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement