def handle_abc_media(msg_id, msg_from, data):
    content = data.get("content", {})
    platform = get_platform(msg_from)
    platform.is_typing = False
    platform.save()
    if not Message.message_exits(platform, msg_id):
        if content.get("type", "").startswith("image/"):
            message_m: Message = Message(
                platform=platform,
                platform_message_id=msg_id,
                image=content.get("uri"),
                direction=Message.FROM_CUSTOMER,
                state=Message.DELIVERED,
            )
            message_m.save()
            operator_interface.tasks.process_message.delay(message_m.id)
            text = content.get("title", "").replace("", "")
            if text:
                message_m: Message = Message(
                    platform=platform,
                    platform_message_id=msg_id,
                    text=html.conditional_escape(text),
                    direction=Message.FROM_CUSTOMER,
                    state=Message.DELIVERED,
                )
                message_m.save()
                operator_interface.tasks.process_message.delay(message_m.id)
    send_abc_notification(msg_id, msg_from, "consumed")
def handle_as207960_file(msg_id, msg_platform, msg_conv_id, metadata, content):
    platform = get_platform(msg_platform, msg_conv_id, metadata)
    platform.is_typing = False
    platform.save()
    if not Message.message_exits(platform, msg_id):
        if content.get("media_type", "").startswith("image/"):
            message_m: Message = Message(
                platform=platform,
                platform_message_id=msg_id,
                image=content.get("url"),
                direction=Message.FROM_CUSTOMER,
                state=Message.DELIVERED,
            )
            message_m.save()
            operator_interface.tasks.process_message.delay(message_m.id)
        else:
            message_m: Message = Message(
                platform=platform,
                platform_message_id=msg_id,
                text=content.get("url"),
                direction=Message.FROM_CUSTOMER,
                state=Message.DELIVERED,
            )
            message_m.save()
            operator_interface.tasks.process_message.delay(message_m.id)
예제 #3
0
def handle_whatsapp(msg_id, msg_from, data):
    text = data.get("Body")
    platform = get_platform(msg_from)
    if not Message.message_exits(platform, msg_id):
        if text:
            message_m: Message = Message(
                platform=platform,
                platform_message_id=msg_id,
                text=html.conditional_escape(text),
                direction=Message.FROM_CUSTOMER,
                state=Message.DELIVERED,
            )
            message_m.save()
            operator_interface.tasks.process_message.delay(message_m.id)
def handle_as207960_text(msg_id, msg_platform, msg_conv_id, metadata, content):
    platform = get_platform(msg_platform, msg_conv_id, metadata)
    platform.is_typing = False
    platform.save()
    if not Message.message_exits(platform, msg_id):
        if content:
            message_m: Message = Message(
                platform=platform,
                platform_message_id=msg_id,
                text=html.conditional_escape(content),
                direction=Message.FROM_CUSTOMER,
                state=Message.DELIVERED,
            )
            message_m.save()
            operator_interface.tasks.process_message.delay(message_m.id)
def handle_abc_text(msg_id, msg_from, data):
    text = data.get("content")
    platform = get_platform(msg_from)
    platform.is_typing = False
    platform.save()
    if not Message.message_exits(platform, msg_id):
        if text:
            message_m: Message = Message(
                platform=platform,
                platform_message_id=msg_id,
                text=html.conditional_escape(text),
                direction=Message.FROM_CUSTOMER,
                state=Message.DELIVERED,
            )
            message_m.save()
            operator_interface.tasks.process_message.delay(message_m.id)
    send_abc_notification(msg_id, msg_from, "consumed")
예제 #6
0
def handle_azure_message(msg):
    conversation = event_to_conversation(msg)
    mid = msg["id"]
    timestamp = msg["timestamp"]
    text = msg.get("text")

    if not Message.message_exits(conversation, mid):
        message_m = Message(
            conversation=conversation,
            message_id=mid,
            direction=Message.FROM_CUSTOMER,
            state=Message.DELIVERED,
            timestamp=dateutil.parser.parse(timestamp),
        )

        if text:
            message_m.text = text
        else:
            return

        message_m.save()
        operator_interface.tasks.process_message.delay(message_m.id)
def handle_abc_own(data: dict):
    msg_from: str = data.get("from")
    msg_id: str = data.get("id")
    device: str = data.get("device")
    capabilities: [str] = data.get("capabilities")
    msg_locale: str = data.get("locale")
    # msg_group: str = data.get("group")
    # msg_intent: str = data.get("intent")
    contents: dict = data.get("contents")

    platform = get_platform(msg_from)
    conversation = platform.conversation
    if not platform.additional_platform_data:
        info = {}
    else:
        try:
            info = json.loads(platform.additional_platform_data)
        except json.JSONDecodeError:
            info = {}

    info["current_capabilities"] = capabilities

    if conversation.conversation_user_id:
        django_keycloak_auth.users.update_user(
            str(conversation.conversation_user_id),
            locale=msg_locale,
            force_update=False,
        )

    if not Message.message_exits(platform, msg_id):
        if contents.get("text"):
            platform.is_typing = False
            platform.save()
            message_m: Message = Message(platform=platform,
                                         platform_message_id=msg_id,
                                         text=html.conditional_escape(
                                             contents["text"]),
                                         direction=Message.FROM_CUSTOMER,
                                         state=Message.DELIVERED,
                                         device_data=device)
            message_m.save()
            operator_interface.tasks.process_message.delay(message_m.id)
        elif contents.get("action"):
            action: str = contents["action"]
            if action == "typing_start":
                platform.is_typing = True
                platform.save()
            elif action == "typing_end":
                platform.is_typing = False
                platform.save()
            elif action == "close":
                platform.is_typing = False
                platform.save()
                m = Message(platform=platform,
                            platform_message_id=msg_id,
                            end=True,
                            direction=Message.FROM_CUSTOMER,
                            state=Message.DELIVERED,
                            device_data=device)
                m.save()
                operator_interface.tasks.send_message_to_interface.delay(m.id)

    platform.additional_platform_data = json.dumps(info)
    platform.save()

    for attachment in data.get("attachments", []):
        contents: str = attachment.get("contents")
        name: str = attachment.get("name")
        mime_type: str = attachment.get("mime-type")
        if contents:
            try:
                contents: bytes = base64.b64decode(contents)
            except ValueError:
                continue
            fs = DefaultStorage()
            file_name = fs.save(name, BytesIO(contents))

            if mime_type.startswith("image"):
                m = Message(platform=platform,
                            platform_message_id=msg_id,
                            direction=Message.FROM_CUSTOMER,
                            state=Message.DELIVERED,
                            device_data=device,
                            image=fs.base_url + file_name)
            else:
                m = Message(
                    platform=platform,
                    platform_message_id=msg_id,
                    direction=Message.FROM_CUSTOMER,
                    state=Message.DELIVERED,
                    device_data=device,
                    text=
                    f"<a href=\"{fs.base_url + file_name}\" target=\"_blank\">{name}</a>",
                )
            m.save()
            operator_interface.tasks.process_message.delay(m.id)
예제 #8
0
def handle_telegram_message(message):
    text = message.get("text")
    contact = message.get("contact")
    photo = message.get("photo")
    sticker = message.get("sticker")
    document = message.get("document")
    entities = message.get("entities")
    caption = message.get("caption")
    mid = message["message_id"]
    chat_id = message["chat"]["id"]
    timestamp = message["date"]
    conversation = Conversation.get_or_create_conversation(
        Conversation.TELEGRAM, chat_id, agent_responding=False)
    update_telegram_profile(chat_id, conversation.id)
    if not Message.message_exits(conversation, mid):
        message_m = Message(
            conversation=conversation,
            message_id=mid,
            direction=Message.FROM_CUSTOMER,
            state=Message.DELIVERED,
            timestamp=datetime.datetime.fromtimestamp(timestamp),
        )
        if text:
            if entities:
                for entity in entities:
                    if entity["type"] == "bot_command":
                        command = text[entity["offset"] + 1:entity["offset"] +
                                       entity["length"]]
                        if command == "start":
                            operator_interface.tasks.process_event.delay(
                                conversation.id, "WELCOME")
                        else:
                            operator_interface.tasks.process_event.delay(
                                conversation.id, command)
                    else:
                        message_m.text = text
            else:
                message_m.text = text
        elif photo or sticker:
            if photo:
                photo = photo[-1]
            else:
                photo = sticker
            file = requests.get(
                f"https://api.telegram.org/bot{settings.TELEGRAM_TOKEN}/getFile",
                json={"file_id": photo["file_id"]},
            )
            file.raise_for_status()
            fs = DefaultStorage()
            file_name = fs.save(photo["file_id"], BytesIO(file.content))

            message_m.image = fs.base_url + file_name
            if caption:
                message.text = caption
        elif document:
            file_name = document["file_name"] if document.get(
                "file_name") else "File"
            file = requests.get(
                f"https://api.telegram.org/bot{settings.TELEGRAM_TOKEN}/getFile",
                json={"file_id": document["file_id"]},
            )
            file.raise_for_status()
            fs = DefaultStorage()
            file_url = fs.save(photo["file_id"], BytesIO(file.content))
            message_m.text = (
                f'<a href="{fs.base_url + file_url}" target="_blank">{file_name}</a>'
            )
            if caption:
                message.text = caption
        elif contact:
            message_m.text = contact["phone_number"]
        else:
            return
        message_m.save()
        operator_interface.tasks.process_message.delay(message_m.id)
def handle_facebook_message(psid: dict, message: dict, timestamp: int) -> None:
    text: typing.Text = message.get("text")
    reply_to = message.get("reply_to", {})
    attachments: typing.List[typing.Dict] = message.get("attachments")
    mid: typing.Text = message["mid"]
    is_echo: bool = message.get("is_echo")
    psid: typing.Text = psid["sender"] if not is_echo else psid["recipient"]
    platform: ConversationPlatform = ConversationPlatform.exists(
        ConversationPlatform.FACEBOOK, psid
    )
    if not platform:
        user_id = attempt_get_user_id(psid)
        platform = ConversationPlatform.create(
            ConversationPlatform.FACEBOOK, psid, customer_user_id=user_id
        )
    message_m: typing.Optional[Message] = None
    if not is_echo:
        update_facebook_profile(psid, platform.conversation.id)
        if not Message.message_exits(platform, mid):
            handle_mark_facebook_message_read.delay(psid)
            if text:
                message_m = Message(
                    platform=platform,
                    platform_message_id=mid,
                    text=html.conditional_escape(text),
                    direction=Message.FROM_CUSTOMER,
                    state=Message.DELIVERED,
                    timestamp=datetime.datetime.fromtimestamp(timestamp / 1000),
                )
            if attachments:
                for attachment in attachments:
                    payload = attachment["payload"]
                    att_type: typing.Text = attachment.get("type")
                    if att_type == "image" or att_type == "file":
                        url = payload.get("url")
                        r = requests.get(url)
                        if r.status_code == 200:
                            orig_file_name = os.path.basename(
                                urllib.parse.urlparse(url).path
                            )
                            fs = DefaultStorage()
                            file_name = fs.save(orig_file_name, BytesIO(r.content))

                            if att_type == "image":
                                message_m = Message(
                                    platform=platform,
                                    platform_message_id=mid,
                                    image=fs.base_url + file_name,
                                    direction=Message.FROM_CUSTOMER,
                                    state=Message.DELIVERED,
                                    timestamp=datetime.datetime.fromtimestamp(
                                        timestamp / 1000
                                    ),
                                )
                            else:
                                message_m = Message(
                                    platform=platform,
                                    platform_message_id=mid,
                                    direction=Message.FROM_CUSTOMER,
                                    state=Message.DELIVERED,
                                    timestamp=datetime.datetime.fromtimestamp(
                                        timestamp / 1000
                                    ),
                                    text=f'<a href="{fs.base_url + file_name}" target="_blank">'
                                    f"{html.conditional_escape(orig_file_name)}"
                                    f"</a>",
                                )
                    elif att_type == "location":
                        message_m = Message(
                            platform=platform,
                            platform_message_id=mid,
                            direction=Message.FROM_CUSTOMER,
                            state=Message.DELIVERED,
                            timestamp=datetime.datetime.fromtimestamp(timestamp / 1000),
                            text=f"<a href=\"{attachment.get('url')}\" target=\"_blank\">Location</a>",
                        )
                    elif att_type == "fallback":
                        message_m = Message(
                            platform=platform,
                            platform_message_id=mid,
                            direction=Message.FROM_CUSTOMER,
                            state=Message.DELIVERED,
                            timestamp=datetime.datetime.fromtimestamp(timestamp / 1000),
                            text=f"<a href=\"{payload.get('url')}\" target=\"_blank\">{payload.get('title')}</a>",
                        )
    else:
        if not Message.message_exits(platform, mid):
            message_m: Message = Message(
                platform=platform,
                platform_message_id=mid,
                text=html.conditional_escape(text) if text else "",
                direction=Message.TO_CUSTOMER,
                state=operator_interface.models.Message.DELIVERED,
            )

    if message_m:
        if reply_to:
            reply_to_mid = reply_to.get("mid")
            reply_to_m = Message.objects.filter(platform_message_id=reply_to_mid).first()
            if reply_to_m:
                message_m.reply_to = reply_to_m
        message_m.save()
        operator_interface.tasks.process_message.delay(message_m.id)
def handle_twitter_message(mid: str, psid, message, user):
    text: str = message.get("text")
    attachment: dict = message.get("attachment")
    if text is not None:
        platform: ConversationPlatform = ConversationPlatform.exists(
            ConversationPlatform.TWITTER, psid)
        if not platform:
            kc_user = django_keycloak_auth.users.get_or_create_user(
                federated_provider="twitter",
                federated_user_id=user.get("id"),
                federated_user_name=user.get("screen_name"),
                first_name=user.get("name"),
            )
            if kc_user:
                django_keycloak_auth.users.link_roles_to_user(
                    kc_user.get("id"), ["customer"])
                user_id = kc_user.get("id")
            platform = ConversationPlatform.create(
                ConversationPlatform.TWITTER, psid, customer_user_id=user_id)
        conversation = platform.conversation

        if not conversation.conversation_user_id:
            kc_user = django_keycloak_auth.users.get_or_create_user(
                federated_provider="twitter",
                federated_user_id=user.get("id"),
                federated_user_name=user.get("screen_name"),
                first_name=user.get("name"),
            )
            if kc_user:
                django_keycloak_auth.users.link_roles_to_user(
                    kc_user.get("id"), ["customer"])
                conversation.update_user_id(kc_user.get("id"))

        if conversation.conversation_user_id:
            django_keycloak_auth.users.link_federated_identity_if_not_exists(
                str(conversation.conversation_user_id),
                federated_provider="twitter",
                federated_user_id=user.get("id"),
                federated_user_name=user.get("screen_name"),
            )

            django_keycloak_auth.users.update_user(str(
                conversation.conversation_user_id),
                                                   first_name=user.get("name"))

        if not Message.message_exits(platform, mid):
            message_m: Message = Message(
                platform=platform,
                platform_message_id=mid,
                text=html.conditional_escape(text.strip()),
                direction=Message.FROM_CUSTOMER,
                state=Message.DELIVERED,
            )
            platform.is_typing = False
            platform.save()

            if attachment:
                if attachment["type"] == "media":
                    creds = views.get_creds()
                    url: str = attachment["media"]["media_url_https"]
                    indices: typing.Tuple = attachment["media"]["indices"]
                    message_m.text = (text[:indices[0]] +
                                      text[indices[1]:]).strip()

                    media_r = requests.get(url, auth=creds)
                    if media_r.status_code == 200:
                        orig_file_name = os.path.basename(
                            urllib.parse.urlparse(url).path)
                        fs = DefaultStorage()
                        file_name = fs.save(orig_file_name,
                                            BytesIO(media_r.content))
                        message_m.image = fs.base_url + file_name

            message_m.save()
            handle_mark_twitter_message_read.delay(psid, mid)
            operator_interface.tasks.process_message.delay(message_m.id)

        file_name = os.path.basename(
            urllib.parse.urlparse(user["profile_image_url_https"]).path)
        r = requests.get(user["profile_image_url_https"])
        if r.status_code == 200:
            if not conversation.conversation_pic:
                conversation.conversation_pic.save(
                    file_name,
                    InMemoryUploadedFile(
                        file=BytesIO(r.content),
                        size=len(r.content),
                        charset=r.encoding,
                        content_type=r.headers.get("content-type"),
                        field_name=file_name,
                        name=file_name,
                    ),
                )
            django_keycloak_auth.users.update_user(
                str(conversation.conversation_user_id),
                profile_picture=conversation.conversation_pic.url,
            )
            conversation.save()