def post(self, request, *args, **kwargs):
        logger.info(f'Voice Enqueue POST received: {json.dumps(request.data)}')

        digit_pressed = int(request.data.get("Digits", "1"))
        if digit_pressed == 1:
            language = "english"
        else:
            language = "spanish"

        # Store (or update, if this redundant) the contact and message in the database
        contact, created = Contact.objects.get_or_create(phone_number=request.data['From'], defaults={
            "uuid": uuid.uuid4(),
            "phone_number": request.data['From'],
        })

        Message.objects.update_or_create(sid=request.data['CallSid'], defaults={
            "timestamp": timezone.now(),
            "channel": enums.CHANNEL_VOICE,
            "sender": contact.uuid,
            "recipient": request.data['To'],
            "direction": enums.MESSAGE_INBOUND,
            "status": request.data['CallStatus'],
            "addons": messageutils.cleanup_json(request.data['AddOns']) if 'AddOns' in request.data else None,
            "raw": json.dumps(request.data),
        })

        channel = twilioservice.get_or_create_chat_channel(contact.phone_number, str(contact.uuid))

        attributes = {
            "from": str(contact.uuid),
            "language": language,
            "channel": channel.unique_name
        }

        response = VoiceResponse()
        enqueue = response.enqueue(None, workflow_sid=twilioauthservice.get_workflow().sid)
        enqueue.task(json.dumps(attributes))
        response.append(enqueue)

        return HttpResponse(str(response))
Пример #2
0
    def post(self, request, *args, **kwargs):
        logger.info(f'Chat POST received: {json.dumps(request.data)}')

        if 'EventType' in request.data:
            if request.data['EventType'] == 'onMessageSent':
                logger.info('Processing onMessageSent')

                attributes = json.loads(
                    messageutils.cleanup_json(request.data['Attributes']))

                # TODO: detect the originating channel of the inbound (ex. SMS)
                channel = enums.CHANNEL_SMS
                contact = Contact.objects.get(uuid=attributes['To'])

                # TODO: here you would execute different "sends" for different originating channels
                if channel == enums.CHANNEL_SMS:
                    twilioservice.send_sms(
                        contact.phone_number,
                        f"{request.data['Body']} - {request.data['ClientIdentity']}"
                    )

                # Store (or update, if this message is redundant) the message in the database
                Message.objects.update_or_create(
                    sid=request.data['MessageSid'],
                    defaults={
                        "timestamp": parser.parse(request.data['DateCreated']),
                        "channel": channel,
                        "sender": settings.TWILIO_PHONE_NUMBER,
                        "recipient": contact.uuid,
                        "direction": enums.MESSAGE_OUTBOUND,
                        "status": enums.MESSAGE_STATUS_SENT,
                        "text": request.data['Body'],
                        "raw": json.dumps(request.data),
                    })

        return viewutils.get_empty_messaging_webhook_response()
    def post(self, request, *args, **kwargs):
        logger.info('SMS POST received: {}'.format(json.dumps(request.data)))

        # Store (or update, if this redundant) the contact and message in the database
        contact, created = Contact.objects.get_or_create(
            phone_number=request.data['From'],
            defaults={
                "sid": request.data['MessageSid'],
                "phone_number": request.data['From'],
            })

        message, created = Message.objects.update_or_create(
            sid=request.data['MessageSid'],
            defaults={
                "timestamp":
                timezone.now(),
                "channel":
                enums.CHANNEL_SMS,
                "sender":
                contact.sid,
                "recipient":
                request.data['To'],
                "direction":
                enums.MESSAGE_INBOUND,
                "status":
                request.data['SmsStatus'],
                "text":
                request.data['Body'],
                "addons":
                messageutils.cleanup_json(request.data['AddOns'])
                if 'AddOns' in request.data else None,
                "raw":
                json.dumps(request.data),
            })

        channel = twilioservice.get_or_create_channel(contact.phone_number,
                                                      contact.sid)

        # Check if the other messages exist from this sender that are associated with an open Task
        sender_messages_with_tasks = Message.objects.not_resolved().inbound(
        ).for_contact(contact.sid).has_task()
        task = None
        if sender_messages_with_tasks.exists():
            db_task = sender_messages_with_tasks[0]

            try:
                task = twilioservice.get_task(db_task.task_sid)

                if task.assignment_status not in [
                        'pending', 'reserved', 'assigned'
                ]:
                    task = None
                else:
                    logger.info('Found an open Task: {}'.format(task.sid))

                    message.task_sid = db_task.task_sid
                    message.worker_sid = db_task.worker_sid

                    message.save()
            except TwilioRestException as e:
                if e.status != 404:
                    raise e

                for message in sender_messages_with_tasks.iterator():
                    message.resolve = True
                    message.save()

        # If no open Task was found, create a new one
        if not task:
            attributes = {"from": message.sender}

            message_addons = json.loads(message.addons)
            if message_addons and \
                            "results" in message_addons and \
                            "ibm_watson_insights" in message_addons["results"] and \
                            "result" in message_addons["results"]["ibm_watson_insights"] and \
                            "language" in message_addons["results"]["ibm_watson_insights"]["result"]:
                attributes["language"] = message_addons["results"][
                    "ibm_watson_insights"]["result"]["language"]

            attributes["channel"] = channel.unique_name

            twilioservice.create_task(attributes)

            twilioservice.send_sms(
                contact.phone_number,
                "Hey, your question has been received. Sit tight and we'll get you an answer ASAP!"
            )

        twilioservice.send_chat_message(channel, message)

        return viewutils.get_empty_webhook_response()
    def post(self, request, *args, **kwargs):
        logger.info(f'Workspace POST received: {json.dumps(request.data)}')

        if 'EventType' in request.data:
            if request.data['EventType'] == 'reservation.accepted':
                logger.info('Processing reservation.accepted')

                task_attributes = json.loads(
                    messageutils.cleanup_json(request.data['TaskAttributes']))

                if 'from' in task_attributes:
                    for message in Message.objects.not_resolved(
                    ).for_channel('sms').inbound().for_contact(
                            task_attributes['from']).no_worker().iterator():
                        message.worker_sid = request.data['WorkerSid']

                        message.save()
            elif request.data['EventType'] == 'task.created':
                logger.info('Processing task.created')

                task_attributes = json.loads(
                    messageutils.cleanup_json(request.data['TaskAttributes']))

                if 'from' in task_attributes:
                    for message in Message.objects.not_resolved(
                    ).for_channel('sms').inbound().for_contact(
                            task_attributes['from']).no_worker().iterator():
                        message.task_sid = request.data['TaskSid']

                        message.save()
            elif request.data['EventType'] == 'task.canceled':
                logger.info('Processing task.canceled')

                task_attributes = json.loads(
                    messageutils.cleanup_json(request.data['TaskAttributes']))

                # TODO: detect other types of originating channels
                task_channel = request.data.get('TaskChannelUniqueName',
                                                'default')
                if task_channel == 'voice':
                    channel = enums.CHANNEL_VOICE
                else:
                    channel = enums.CHANNEL_SMS
                contact = Contact.objects.get(uuid=task_attributes['channel'])

                # TODO: here you would execute different "sends" for different originating channels
                cancelled_message = 'Sorry, your question could not be answered because the agent assigned to it is ' \
                                    'no longer available. Try submitting it again!'
                if channel == enums.CHANNEL_SMS:
                    twilioservice.send_sms(contact.phone_number,
                                           cancelled_message)
            elif request.data['EventType'] == 'task.completed':
                logger.info('Processing task.completed')

                # TODO: once TaskRouter supports Task transfer, we could utilize that here instead
                if 'TaskCompletedReason' in request.data and request.data[
                        'TaskCompletedReason'].startswith('User logged out'):
                    task_attributes = json.loads(
                        messageutils.cleanup_json(
                            request.data['TaskAttributes']))

                    twilioservice.create_task(task_attributes)

                for message in Message.objects.for_task(
                        request.data['TaskSid']).iterator():
                    message.worker_sid = None
                    message.resolved = True
                    message.save()
            elif request.data['EventType'] == 'worker.deleted':
                try:
                    user = get_user_model().objects.get(
                        worker_sid=request.data['WorkerSid'])
                    authservice.delete_user(user)
                except get_user_model().DoesNotExist:
                    pass

        return Response(status=status.HTTP_204_NO_CONTENT)
Пример #5
0
    def post(self, request, *args, **kwargs):
        logger.info('Workspace POST received: {}'.format(
            json.dumps(request.data)))

        if 'EventType' in request.data:
            if request.data['EventType'] == 'reservation.accepted':
                logger.info('Processing reservation.accepted')

                task_attributes = json.loads(
                    messageutils.cleanup_json(request.data['TaskAttributes']))

                for message in Message.objects.not_resolved().for_channel(
                        'sms').inbound().for_contact(
                            task_attributes['from']).no_worker().iterator():
                    message.worker_sid = request.data['WorkerSid']

                    message.save()
            elif request.data['EventType'] == 'task.created':
                logger.info('Processing task.created')

                task_attributes = json.loads(
                    messageutils.cleanup_json(request.data['TaskAttributes']))

                for message in Message.objects.not_resolved().for_channel(
                        'sms').inbound().for_contact(
                            task_attributes['from']).no_worker().iterator():
                    message.task_sid = request.data['TaskSid']

                    message.save()
            elif request.data['EventType'] == 'task.canceled':
                logger.info('Processing task.canceled')

                task_attributes = json.loads(
                    messageutils.cleanup_json(request.data['TaskAttributes']))

                # TODO: detect the originating channel of the inbound (ex. SMS)
                channel = enums.CHANNEL_SMS
                contact = Contact.objects.get(sid=task_attributes['from'])

                # TODO: here you would execute different "sends" for different originating channels
                cancelled_message = 'Sorry, your question could not be answered because the agent assigned to it is ' \
                                    'no longer available. Try submitting it again!'
                if channel == enums.CHANNEL_SMS:
                    twilioservice.send_sms(contact.phone_number,
                                           cancelled_message)
            elif request.data['EventType'] == 'task.completed':
                logger.info('Processing task.completed')

                # TODO: once TaskRouter supports Task transfer, we would want to utilize that instead here
                if 'TaskCompletedReason' in request.data and request.data[
                        'TaskCompletedReason'].startswith('User logged out'):
                    task_attributes = json.loads(
                        messageutils.cleanup_json(
                            request.data['TaskAttributes']))

                    twilioservice.create_task(task_attributes)

                for message in Message.objects.for_task(
                        request.data['TaskSid']).iterator():
                    message.worker_sid = None
                    message.resolved = True
                    message.save()

        return Response(status=status.HTTP_204_NO_CONTENT)