def check_credits_remaining(self):
        """Does a GET request to /v1/messaging/credits.

        TODO: type endpoint description here.

        Returns:
            mixed: Response from the API. 

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/v1/messaging/credits'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {'accept': 'application/json'}

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        AuthManager.apply(_request, _url_path)
        _context = self.execute_request(_request)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body)
Example #2
0
    def __init__(self,
                 content=None,
                 destination_number=None,
                 callback_url=None,
                 delivery_report=False,
                 format=None,
                 message_expiry_timestamp=None,
                 metadata=None,
                 scheduled=None,
                 source_number=None,
                 source_number_type=None,
                 message_id=None,
                 status=None,
                 media=None,
                 subject=None):
        """Constructor for the Message class"""

        # Initialize members of the class
        self.callback_url = callback_url
        self.content = content
        self.destination_number = destination_number
        self.delivery_report = delivery_report
        self.format = format
        self.message_expiry_timestamp = APIHelper.RFC3339DateTime(message_expiry_timestamp) if message_expiry_timestamp else None
        self.metadata = metadata
        self.scheduled = APIHelper.RFC3339DateTime(scheduled) if scheduled else None
        self.source_number = source_number
        self.source_number_type = source_number_type
        self.message_id = message_id
        self.status = status
        self.media = media
        self.subject = subject
    def __init__(self,
                 callback_url=None,
                 date_received=None,
                 delay=None,
                 delivery_report_id=None,
                 message_id=None,
                 metadata=None,
                 original_text=None,
                 source_number=None,
                 status=None,
                 submitted_date=None,
                 vendor_account_id=None):
        """Constructor for the DeliveryReport class"""

        # Initialize members of the class
        self.callback_url = callback_url
        self.date_received = APIHelper.RFC3339DateTime(date_received) if date_received else None
        self.delay = delay
        self.delivery_report_id = delivery_report_id
        self.message_id = message_id
        self.metadata = metadata
        self.original_text = original_text
        self.source_number = source_number
        self.status = status
        self.submitted_date = APIHelper.RFC3339DateTime(submitted_date) if submitted_date else None
        self.vendor_account_id = vendor_account_id
Example #4
0
    def add_query_parameter(self, name, value):
        """ Add a query parameter to the HttpRequest.

        Args:
	        name (string): The name of the query parameter.
            value (string): The value of the query parameter.

        """
        self.query_url = APIHelper.append_url_with_query_parameters(self.query_url,
                                                                    {name:value})
        self.query_url = APIHelper.clean_url(self.query_url)
Example #5
0
    def execute_request(self, request, binary=False):
        """Executes an HttpRequest.

        Args:
            request (HttpRequest): The HttpRequest to execute.
            binary (bool): A flag which should be set to True if
                a binary response is expected.

        Returns:
            HttpContext: The HttpContext of the request. It contains,
                both, the request itself and the HttpResponse object.

        """
        # Invoke the on before request HttpCallBack if specified
        if self.http_call_back != None:
            self.http_call_back.on_before_request(request)

        # Add global headers to request
        request.headers = APIHelper.merge_dicts(self.global_headers,
                                                request.headers)

        # Invoke the API call to fetch the response.
        func = self.http_client.execute_as_binary if binary else self.http_client.execute_as_string
        response = func(request)
        context = HttpContext(request, response)

        # Invoke the on after response HttpCallBack if specified
        if self.http_call_back != None:
            self.http_call_back.on_after_response(context)

        return context
Example #6
0
    def test_send_messages_1(self):
        # Parameters for the API call
        body = APIHelper.json_deserialize((
            '{"messages":[{"callback_url":"https://my.callback.url.com","content":"My fi'
            'rst message","destination_number":"+61491570156","delivery_report":true,"fo'
            'rmat":"SMS","message_expiry_timestamp":"2016-11-03T11:49:02.807Z","metadata'
            '":{"key1":"value1","key2":"value2"},"scheduled":"2016-11-03T11:49:02.807Z",'
            '"source_number":"+61491570157","source_number_type":"INTERNATIONAL"},{"call'
            'back_url":"https://my.callback.url.com","content":"My second message","dest'
            'ination_number":"+61491570158","delivery_report":true,"format":"SMS","messa'
            'ge_expiry_timestamp":"2016-11-03T11:49:02.807Z","metadata":{"key1":"value1"'
            ',"key2":"value2"},"scheduled":"2016-11-03T11:49:02.807Z","source_number":"+'
            '61491570159","source_number_type":"INTERNATIONAL"}]}'),
                                          SendMessagesRequest.from_dictionary)

        # Perform the API call through the SDK function
        result = self.controller.create_send_messages(body)

        # Test response code
        self.assertEquals(self.response_catcher.response.status_code, 202)

        # Test headers
        expected_headers = {}
        expected_headers['content-type'] = None

        self.assertTrue(
            TestHelper.match_headers(expected_headers,
                                     self.response_catcher.response.headers))

        # Test whether the captured response is as we expected
        self.assertIsNotNone(result)
        self.assertEqual(
            '{  "messages": [    {      "message_id": "04fe9a97-a579-43c5-bb1a-58ed29bf0a6a",      "callback_url": "https://my.url.com",      "status": "delivered",      "content": "My first message",      "destination_number": "+61491570156",      "delivery_report": true,      "format": "SMS",      "message_expiry_timestamp": "2016-11-03T11:49:02.807Z",      "metadata": {        "key1": "value1",        "key2": "value2"      },      "scheduled": "2016-11-03T11:49:02.807Z",      "source_number": "+61491570157",      "source_number_type": "INTERNATIONAL"    }  ]}',
            self.response_catcher.response.raw_body)
    def test_confirm_replies_with_dummy_account(self):
        # Parameters for the API call
        body = APIHelper.json_deserialize((
            '{"reply_ids":["011dcead-6988-4ad6-a1c7-6b6c68ea628d","3487b3fa-6586-4979-a2'
            '33-2d1b095c7718","ba28e94b-c83d-4759-98e7-ff9c7edb87a1"]}'
            ), ConfirmRepliesAsReceivedRequest.from_dictionary)

        try:
            # Perform the API call through the SDK function
            self.controller.create_confirm_replies_as_received(body, 'INVALID ACCOUNT')
        except APIException as apiException:
            self.assertEquals(apiException.response_code, 403, "Exception must be raised with 403 error code.")
    def test_confirm_replies_as_received_1(self):
        # Parameters for the API call
        body = APIHelper.json_deserialize((
            '{"reply_ids":["011dcead-6988-4ad6-a1c7-6b6c68ea628d","3487b3fa-6586-4979-a2'
            '33-2d1b095c7718","ba28e94b-c83d-4759-98e7-ff9c7edb87a1"]}'
            ), ConfirmRepliesAsReceivedRequest.from_dictionary)

        # Perform the API call through the SDK function
        self.controller.create_confirm_replies_as_received(body)

        # Test response code
        self.assertEquals(self.response_catcher.response.status_code, 202)

        # Test headers
        expected_headers = {'content-type': None}

        self.assertTrue(TestHelper.match_headers(expected_headers, self.response_catcher.response.headers))
    def test_check_replies_with_dummy_account(self):
        # Parameters for the API call
        body = APIHelper.json_deserialize((
            '{"messages":[{"callback_url":"https://my.callback.url.com","content":"My fi'
            'rst message","destination_number":"+61491570156","delivery_report":true,"fo'
            'rmat":"SMS","message_expiry_timestamp":"2016-11-03T11:49:02.807Z","metadata'
            '":{"key1":"value1","key2":"value2"},"scheduled":"2016-11-03T11:49:02.807Z",'
            '"source_number":"+61491570157","source_number_type":"INTERNATIONAL"},{"call'
            'back_url":"https://my.callback.url.com","content":"My second message","dest'
            'ination_number":"+61491570158","delivery_report":true,"format":"SMS","messa'
            'ge_expiry_timestamp":"2016-11-03T11:49:02.807Z","metadata":{"key1":"value1"'
            ',"key2":"value2"},"scheduled":"2016-11-03T11:49:02.807Z","source_number":"+'
            '61491570159","source_number_type":"INTERNATIONAL"}]}'),
                                          SendMessagesRequest.from_dictionary)

        try:
            # Perform the API call through the SDK function
            self.controller.create_send_messages(body, 'INVALID ACCOUNT')
        except APIException as apiException:
            self.assertEquals(apiException.response_code, 403,
                              "Exception must be raised with 403 error code.")
    def check_replies(self):
        """Does a GET request to /v1/replies.

        Check for any replies that have been received.
        Replies are messages that have been sent from a handset in response to
        a message sent by an
        application or messages that have been sent from a handset to a
        inbound number associated with
        an account, known as a dedicated inbound number (contact
        <*****@*****.**> for more
        information on dedicated inbound numbers).
        Each request to the check replies endpoint will return any replies
        received that have not yet
        been confirmed using the confirm replies endpoint. A response from the
        check replies endpoint
        will have the following structure:
        ```json
        {
            "replies": [
                {
                    "metadata": {
                        "key1": "value1",
                        "key2": "value2"
                    },
                    "message_id": "877c19ef-fa2e-4cec-827a-e1df9b5509f7",
                    "reply_id": "a175e797-2b54-468b-9850-41a3eab32f74",
                    "date_received": "2016-12-07T08:43:00.850Z",
                    "callback_url": "https://my.callback.url.com",
                    "destination_number": "+61491570156",
                    "source_number": "+61491570157",
                    "vendor_account_id": {
                        "vendor_id": "MessageMedia",
                        "account_id": "MyAccount"
                    },
                    "content": "My first reply!"
                },
                {
                    "metadata": {
                        "key1": "value1",
                        "key2": "value2"
                    },
                    "message_id": "8f2f5927-2e16-4f1c-bd43-47dbe2a77ae4",
                    "reply_id": "3d8d53d8-01d3-45dd-8cfa-4dfc81600f7f",
                    "date_received": "2016-12-07T08:43:00.850Z",
                    "callback_url": "https://my.callback.url.com",
                    "destination_number": "+61491570157",
                    "source_number": "+61491570158",
                    "vendor_account_id": {
                        "vendor_id": "MessageMedia",
                        "account_id": "MyAccount"
                    },
                    "content": "My second reply!"
                }
            ]
        }
        ```
        Each reply will contain details about the reply message, as well as
        details of the message the reply was sent
        in response to, including any metadata specified. Every reply will
        have a reply ID to be used with the
        confirm replies endpoint.
        *Note: The source number and destination number properties in a reply
        are the inverse of those
        specified in the message the reply is in response to. The source
        number of the reply message is the
        same as the destination number of the original message, and the
        destination number of the reply
        message is the same as the source number of the original message. If a
        source number
        wasn't specified in the original message, then the destination number
        property will not be present
        in the reply message.*
        Subsequent requests to the check replies endpoint will return the same
        reply messages and a maximum
        of 100 replies will be returned in each request. Applications should
        use the confirm replies endpoint
        in the following pattern so that replies that have been processed are
        no longer returned in
        subsequent check replies requests.
        1. Call check replies endpoint
        2. Process each reply message
        3. Confirm all processed reply messages using the confirm replies
        endpoint
        *Note: It is recommended to use the Webhooks feature to receive reply
        messages rather than polling
        the check replies endpoint.*

        Returns:
            CheckRepliesResponse: Response from the API. Unconfirmed replies

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/v1/replies'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {'accept': 'application/json'}

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        AuthManager.apply(_request, _url_path)
        _context = self.execute_request(_request)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body,
                                          CheckRepliesResponse.from_dictionary)
    def confirm_replies_as_received(self, body):
        """Does a POST request to /v1/replies/confirmed.

        Mark a reply message as confirmed so it is no longer returned in check
        replies requests.
        The confirm replies endpoint is intended to be used in conjunction
        with the check replies endpoint
        to allow for robust processing of reply messages. Once one or more
        reply messages have been processed
        they can then be confirmed using the confirm replies endpoint so they
        are no longer returned in
        subsequent check replies requests.
        The confirm replies endpoint takes a list of reply IDs as follows:
        ```json
        {
            "reply_ids": [
                "011dcead-6988-4ad6-a1c7-6b6c68ea628d",
                "3487b3fa-6586-4979-a233-2d1b095c7718",
                "ba28e94b-c83d-4759-98e7-ff9c7edb87a1"
            ]
        }
        ```
        Up to 100 replies can be confirmed in a single confirm replies
        request.

        Args:
            body (ConfirmRepliesAsReceivedRequest): TODO: type description
                here. Example: 

        Returns:
            mixed: Response from the API. Requested replies will be marked as
                confirmed

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/v1/replies/confirmed'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json',
            'content-type': 'application/json; charset=utf-8'
        }

        # Prepare and execute request
        _request = self.http_client.post(
            _query_url,
            headers=_headers,
            parameters=APIHelper.json_serialize(body))
        AuthManager.apply(_request, _url_path, APIHelper.json_serialize(body))
        _context = self.execute_request(_request)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body)
    def test_send_messages_1(self):
        # Parameters for the API call
        body = APIHelper.json_deserialize((
            '{"messages":[{"callback_url":"https://my.callback.url.com","content":"My fi'
            'rst message","destination_number":"+61491570156","delivery_report":true,"fo'
            'rmat":"SMS","message_expiry_timestamp":"2016-11-03T11:49:02.807Z","metadata'
            '":{"key1":"value1","key2":"value2"},"scheduled":"2016-11-03T11:49:02.807Z",'
            '"source_number":"+61491570157","source_number_type":"INTERNATIONAL"},{"call'
            'back_url":"https://my.callback.url.com","content":"My second message","dest'
            'ination_number":"+61491570158","delivery_report":true,"format":"SMS","messa'
            'ge_expiry_timestamp":"2016-11-03T11:49:02.807Z","metadata":{"key1":"value1"'
            ',"key2":"value2"},"scheduled":"2016-11-03T11:49:02.807Z","source_number":"+'
            '61491570159","source_number_type":"INTERNATIONAL"}]}'),
                                          SendMessagesRequest.from_dictionary)

        # Perform the API call through the SDK function
        result = self.controller.create_send_messages(body)

        # Test response code
        self.assertEquals(self.response_catcher.response.status_code, 202)

        # Test headers
        expected_headers = {'content-type': None}

        self.assertTrue(
            TestHelper.match_headers(expected_headers,
                                     self.response_catcher.response.headers))

        # Test whether the captured response is as we expected
        self.assertIsNotNone(result)

        self.assertEqual(
            body.messages[0]['callback_url'],
            result.messages[0]['callback_url'],
            'Callback URL should match exactly (string literal match)')
        self.assertEqual(
            body.messages[0]['content'], result.messages[0]['content'],
            'Content should match exactly (string literal match)')
        self.assertEqual(body.messages[0]['format'],
                         result.messages[0]['format'],
                         'Format should match exactly (string literal match)')
        self.assertEqual(
            body.messages[0]['delivery_report'],
            result.messages[0]['delivery_report'],
            'Delivery Report should match exactly (boolean match)')
        self.assertEqual(
            body.messages[0]['destination_number'],
            result.messages[0]['destination_number'],
            'Destination Number should match exactly (string literal match)')
        self.assertEqual(
            body.messages[0]['source_number'],
            result.messages[0]['source_number'],
            'Source Number should match exactly (string literal match)')

        self.assertIsNotNone(result.messages[0]['message_id'],
                             'Message ID should not be empty')
        self.assertIsNotNone(result.messages[0]['message_expiry_timestamp'],
                             'Message Expiry should not be empty')
        self.assertIsNotNone(result.messages[0]['scheduled'],
                             'Scheduled time should not be empty')

        self.assertEqual(
            body.messages[1]['callback_url'],
            result.messages[1]['callback_url'],
            'Callback URL should match exactly (string literal match)')
        self.assertEqual(
            body.messages[1]['content'], result.messages[1]['content'],
            'Content should match exactly (string literal match)')
        self.assertEqual(body.messages[1]['format'],
                         result.messages[1]['format'],
                         'Format should match exactly (string literal match)')
        self.assertEqual(
            body.messages[1]['delivery_report'],
            result.messages[1]['delivery_report'],
            'Delivery Report should match exactly (boolean match)')
        self.assertEqual(
            body.messages[1]['destination_number'],
            result.messages[1]['destination_number'],
            'Destination Number should match exactly (string literal match)')
        self.assertEqual(
            body.messages[1]['source_number'],
            result.messages[1]['source_number'],
            'Source Number should match exactly (string literal match)')

        self.assertIsNotNone(result.messages[1]['message_id'],
                             'Message ID should not be empty')
        self.assertIsNotNone(result.messages[1]['message_expiry_timestamp'],
                             'Message Expiry should not be empty')
        self.assertIsNotNone(result.messages[1]['scheduled'],
                             'Scheduled time should not be empty')
    def send_messages(self, body):
        """Does a POST request to /v1/messages.

        Submit one or more (up to 100 per request) SMS, MMS or text to voice
        messages for delivery.
        The most basic message has the following structure:
        ```json
        {
            "messages": [
                {
                    "content": "My first message!",
                    "destination_number": "+61491570156"
                }
            ]
        }
        ```
        More advanced delivery features can be specified by setting the
        following properties in a message:
        - ```callback_url``` A URL can be included with each message to which
        Webhooks will be pushed to
          via a HTTP POST request. Webhooks will be sent if and when the
          status of the message changes as
          it is processed (if the delivery report property of the request is
          set to ```true```) and when replies
          are received. Specifying a callback URL is optional.
        - ```content``` The content of the message. This can be a Unicode
        string, up to 5,000 characters long.
          Message content is required.
        - ```delivery_report``` Delivery reports can be requested with each
        message. If delivery reports are requested, a webhook
          will be submitted to the ```callback_url``` property specified for
          the message (or to the webhooks)
          specified for the account every time the status of the message
          changes as it is processed. The
          current status of the message can also be retrieved via the Delivery
          Reports endpoint of the
          Messages API. Delivery reports are optional and by default will not
          be requested.
        - ```destination_number``` The destination number the message should
        be delivered to. This should be specified in E.164
          international format. For information on E.164, please refer to
          http://en.wikipedia.org/wiki/E.164.
          A destination number is required.
        - ```format``` The format specifies which format the message will be
        sent as, ```SMS``` (text message), ```MMS``` (multimedia message)
          or ```TTS``` (text to speech). With ```TTS``` format, we will call
          the destination number and read out the
          message using a computer generated voice. Specifying a format is
          optional, by default ```SMS``` will be used.
        - ```source_number``` A source number may be specified for the
        message, this will be the number that
          the message appears from on the handset. By default this feature is
          _not_ available and will be ignored
          in the request. Please contact <*****@*****.**> for more
          information. Specifying a source
          number is optional and a by default a source number will be assigned
          to the message.
        - ```media``` The media is used to specify the url of the media file
        that you are trying to send. Supported file formats include png, jpeg
        and gif. ```format``` parameter must be set to ```MMS``` for this to
        work.
        - ```subject``` The subject field is used to denote subject of the MMS
        message and has a maximum size of 64 characters long. Specifying a
        subject is optional.
        - ```source_number_type``` If a source number is specified, the type
        of source number may also be
          specified. This is recommended when using a source address type that
          is not an internationally
          formatted number, available options are ```INTERNATIONAL```,
          ```ALPHANUMERIC``` or ```SHORTCODE```. Specifying a
          source number type is only valid when the ```source_number```
          parameter is specified and is optional.
          If a source number is specified and no source number type is
          specified, the source number type will be
          inferred from the source number, however this may be inaccurate.
        - ```scheduled``` A message can be scheduled for delivery in the
        future by setting the scheduled property.
          The scheduled property expects a date time specified in ISO 8601
          format. The scheduled time must be
          provided in UTC and is optional. If no scheduled property is set,
          the message will be delivered immediately.
        - ```message_expiry_timestamp``` A message expiry timestamp can be
        provided to specify the latest time
          at which the message should be delivered. If the message cannot be
          delivered before the specified
          message expiry timestamp elapses, the message will be discarded.
          Specifying a message expiry 
          timestamp is optional.
        - ```metadata``` Metadata can be included with the message which will
        then be included with any delivery
          reports or replies matched to the message. This can be used to
          create powerful two-way messaging
          applications without having to store persistent data in the
          application. Up to 10 key / value metadata data
          pairs can be specified in a message. Each key can be up to 100
          characters long, and each value up to 
          256 characters long. Specifying metadata for a message is optional.
        The response body of a successful POST request to the messages
        endpoint will include a ```messages```
        property which contains a list of all messages submitted. The list of
        messages submitted will
        reflect the list of messages included in the request, but each message
        will also contain two new
        properties, ```message_id``` and ```status```. The returned message ID
        will be a 36 character UUID
        which can be used to check the status of the message via the Get
        Message Status endpoint. The status
        of the message which reflect the status of the message at submission
        time which will always be
        ```queued```. See the Delivery Reports section of this documentation
        for more information on message
        statues.
        *Note: when sending multiple messages in a request, all messages must
        be valid for the request to be successful.
        If any messages in the request are invalid, no messages will be
        sent.*

        Args:
            body (SendMessagesRequest): TODO: type description here. Example:
                
        Returns:
            SendMessagesResponse: Response from the API. Messages were
                accepted for processing

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/v1/messages'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json',
            'content-type': 'application/json; charset=utf-8'
        }

        # Prepare and execute request
        _request = self.http_client.post(
            _query_url,
            headers=_headers,
            parameters=APIHelper.json_serialize(body))
        AuthManager.apply(_request, _url_path, APIHelper.json_serialize(body))
        _context = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _context.response.status_code == 400:
            raise SendMessages400ResponseException(
                'Unexpected error in API call. See HTTP response body for details.',
                _context)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body,
                                          SendMessagesResponse.from_dictionary)
    def cancel_scheduled_message(self, message_id, body):
        """Does a PUT request to /v1/messages/{messageId}.

        Cancel a scheduled message that has not yet been delivered.
        A scheduled message can be cancelled by updating the status of a
        message from ```scheduled```
        to ```cancelled```. This is done by submitting a PUT request to the
        messages endpoint using
        the message ID as a parameter (the same endpoint used above to
        retrieve the status of a message).
        The body of the request simply needs to contain a ```status```
        property with the value set
        to ```cancelled```.
        ```json
        {
            "status": "cancelled"
        }
        ```
        *Note: Only messages with a status of scheduled can be cancelled. If
        an invalid or non existent
        message ID parameter is specified in the request, then a HTTP 404 Not
        Found response will be 
        returned*

        Args:
            message_id (string): TODO: type description here. Example: 
            body (CancelScheduledMessageRequest): TODO: type description here.
                Example: 

        Returns:
            mixed: Response from the API. Message status updated successfully

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/v1/messages/{messageId}'
        _url_path = APIHelper.append_url_with_template_parameters(
            _url_path, {'messageId': message_id})
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {
            'accept': 'application/json',
            'content-type': 'application/json; charset=utf-8'
        }

        # Prepare and execute request
        _request = self.http_client.put(
            _query_url,
            headers=_headers,
            parameters=APIHelper.json_serialize(body))
        AuthManager.apply(_request, _url_path, APIHelper.json_serialize(body))
        _context = self.execute_request(_request)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(_context.response.raw_body)
    def get_message_status(self, message_id):
        """Does a GET request to /v1/messages/{messageId}.

        Retrieve the current status of a message using the message ID returned
        in the send messages end point.
        A successful request to the get message status endpoint will return a
        response body as follows:
        ```json
        {
            "format": "SMS",
            "content": "My first message!",
            "metadata": {
                "key1": "value1",
                "key2": "value2"
            },
            "message_id": "877c19ef-fa2e-4cec-827a-e1df9b5509f7",
            "callback_url": "https://my.callback.url.com",
            "delivery_report": true,
            "destination_number": "+61401760575",
            "scheduled": "2016-11-03T11:49:02.807Z",
            "source_number": "+61491570157",
            "source_number_type": "INTERNATIONAL",
            "message_expiry_timestamp": "2016-11-03T11:49:02.807Z",
            "status": "enroute"
        }
        ```
        The status property of the response indicates the current status of
        the message. See the Delivery
        Reports section of this documentation for more information on message
        statues.
        *Note: If an invalid or non existent message ID parameter is specified
        in the request, then
        a HTTP 404 Not Found response will be returned*

        Args:
            message_id (string): TODO: type description here. Example: 

        Returns:
            GetMessageStatusResponse: Response from the API. The submitted
                message including the status of the message

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/v1/messages/{messageId}'
        _url_path = APIHelper.append_url_with_template_parameters(
            _url_path, {'messageId': message_id})
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {'accept': 'application/json'}

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        AuthManager.apply(_request, _url_path)
        _context = self.execute_request(_request)

        # Endpoint and global error handling using HTTP status codes.
        if _context.response.status_code == 404:
            raise APIException('Resource not found', _context)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(
            _context.response.raw_body,
            GetMessageStatusResponse.from_dictionary)
Example #16
0
    def check_delivery_reports(self):
        """Does a GET request to /v1/delivery_reports.

        Check for any delivery reports that have been received.
        Delivery reports are a notification of the change in status of a
        message as it is being processed.
        Each request to the check delivery reports endpoint will return any
        delivery reports received that
        have not yet been confirmed using the confirm delivery reports
        endpoint. A response from the check
        delivery reports endpoint will have the following structure:
        ```json
        {
            "delivery_reports": [
                {
                    "callback_url": "https://my.callback.url.com",
                    "delivery_report_id":
                    "01e1fa0a-6e27-4945-9cdb-18644b4de043",
                    "source_number": "+61491570157",
                    "date_received": "2017-05-20T06:30:37.642Z",
                    "status": "enroute",
                    "delay": 0,
                    "submitted_date": "2017-05-20T06:30:37.639Z",
                    "original_text": "My first message!",
                    "message_id": "d781dcab-d9d8-4fb2-9e03-872f07ae94ba",
                    "vendor_account_id": {
                        "vendor_id": "MessageMedia",
                        "account_id": "MyAccount"
                    },
                    "metadata": {
                        "key1": "value1",
                        "key2": "value2"
                    }
                },
                {
                    "callback_url": "https://my.callback.url.com",
                    "delivery_report_id":
                    "0edf9022-7ccc-43e6-acab-480e93e98c1b",
                    "source_number": "+61491570158",
                    "date_received": "2017-05-21T01:46:42.579Z",
                    "status": "enroute",
                    "delay": 0,
                    "submitted_date": "2017-05-21T01:46:42.574Z",
                    "original_text": "My second message!",
                    "message_id": "fbb3b3f5-b702-4d8b-ab44-65b2ee39a281",
                    "vendor_account_id": {
                        "vendor_id": "MessageMedia",
                        "account_id": "MyAccount"
                    },
                    "metadata": {
                        "key1": "value1",
                        "key2": "value2"
                    }
                }
            ]
        }
        ```
        Each delivery report will contain details about the message, including
        any metadata specified
        and the new status of the message (as each delivery report indicates a
        change in status of a
        message) and the timestamp at which the status changed. Every delivery
        report will have a 
        unique delivery report ID for use with the confirm delivery reports
        endpoint.
        *Note: The source number and destination number properties in a
        delivery report are the inverse of
        those specified in the message that the delivery report relates to.
        The source number of the
        delivery report is the destination number of the original message.*
        Subsequent requests to the check delivery reports endpoint will return
        the same delivery reports
        and a maximum of 100 delivery reports will be returned in each
        request. Applications should use the
        confirm delivery reports endpoint in the following pattern so that
        delivery reports that have been
        processed are no longer returned in subsequent check delivery reports
        requests.
        1. Call check delivery reports endpoint
        2. Process each delivery report
        3. Confirm all processed delivery reports using the confirm delivery
        reports endpoint
        *Note: It is recommended to use the Webhooks feature to receive reply
        messages rather than
        polling the check delivery reports endpoint.*

        Returns:
            CheckDeliveryReportsResponse: Response from the API. Unconfirmed
                reports

        Raises:
            APIException: When an error occurs while fetching the data from
                the remote API. This exception includes the HTTP Response
                code, an error message, and the HTTP body that was received in
                the request.

        """

        # Prepare query URL
        _url_path = '/v1/delivery_reports'
        _query_builder = Configuration.base_uri
        _query_builder += _url_path
        _query_url = APIHelper.clean_url(_query_builder)

        # Prepare headers
        _headers = {'accept': 'application/json'}

        # Prepare and execute request
        _request = self.http_client.get(_query_url, headers=_headers)
        AuthManager.apply(_request, _url_path)
        _context = self.execute_request(_request)
        self.validate_response(_context)

        # Return appropriate type
        return APIHelper.json_deserialize(
            _context.response.raw_body,
            CheckDeliveryReportsResponse.from_dictionary)