Beispiel #1
0
    def __init__(self, account=None, token=None, base="https://api.twilio.com",
                 version="2010-04-01", timeout=UNSET_TIMEOUT,
                 request_account=None):
        """
        Create a Twilio API client.
        """

        # Get account credentials
        if not account or not token:
            account, token = find_credentials()
            if not account or not token:
                raise TwilioException("""
Twilio could not find your account credentials. Pass them into the
TwilioRestClient constructor like this:

    client = TwilioRestClient(account='AC38135355602040856210245275870',
                              token='2flnf5tdp7so0lmfdu3d')

Or, add your credentials to your shell environment. From the terminal, run

    echo "export TWILIO_ACCOUNT_SID=AC3813535560204085626521" >> ~/.bashrc
    echo "export TWILIO_AUTH_TOKEN=2flnf5tdp7so0lmfdu3d7wod" >> ~/.bashrc

and be sure to replace the values for the Account SID and auth token with the
values from your Twilio Account at https://www.twilio.com/user/account.
""")
        self.base = base
        self.auth = (account, token)
        self.timeout = timeout
        req_account = request_account if request_account else account
        self.account_uri = "{0}/{1}/Accounts/{2}".format(base,
                                                         version, req_account)
Beispiel #2
0
 def get_instance(self, payload):
     """
     :param dict payload: A JSON-loaded representation of an instance record.
     :return: A rich, resource-dependent object.
     """
     raise TwilioException(
         'Page.get_instance() must be implemented in the derived class')
Beispiel #3
0
    def __init__(self,
                 username=None,
                 password=None,
                 account_sid=None,
                 region=None,
                 http_client=None,
                 environment=None):
        """
        Initializes the Twilio Client

        :param str username: Username to authenticate with
        :param str password: Password to authenticate with
        :param str account_sid: Account Sid, defaults to Username
        :param str region: Twilio Region to make requests to
        :param HttpClient http_client: HttpClient, defaults to TwilioHttpClient
        :param dict environment: Environment to look for auth details, defaults to os.environ

        :returns: Twilio Client
        :rtype: twilio.rest.Client
        """
        environment = environment or os.environ

        self.username = username or environment.get('TWILIO_ACCOUNT_SID')
        """ :type : str """
        self.password = password or environment.get('TWILIO_AUTH_TOKEN')
        """ :type : str """
        self.account_sid = account_sid or self.username
        """ :type : str """
        self.region = region
        """ :type : str """

        if not self.username or not self.password:
            raise TwilioException(
                "Credentials are required to create a TwilioClient")

        self.auth = (self.username, self.password)
        """ :type : tuple(str, str) """
        self.http_client = http_client or TwilioHttpClient()
        """ :type : HttpClient """

        # Domains
        self._accounts = None
        self._api = None
        self._chat = None
        self._fax = None
        self._ip_messaging = None
        self._lookups = None
        self._monitor = None
        self._notify = None
        self._preview = None
        self._pricing = None
        self._proxy = None
        self._taskrouter = None
        self._trunking = None
        self._video = None
        self._messaging = None
        self._wireless = None
        self._sync = None
        self._studio = None
        self._verify = None
    def load_page(self, payload):
        if 'meta' in payload and 'key' in payload['meta']:
            return payload[payload['meta']['key']]
        else:
            keys = set(payload.keys())
            key = keys - self.META_KEYS
            if len(key) == 1:
                return payload[key.pop()]

        raise TwilioException('Page Records can not be deserialized')
Beispiel #5
0
    def process_response(self, response):
        """
        Load a JSON response.

        :param Response response: The HTTP response.
        :return dict: The JSON-loaded content.
        """
        if response.status_code != 200:
            raise TwilioException('Unable to fetch page', response)

        return json.loads(response.text)
    def update(self, sid, **kwargs):
        """Update an :class:`Address` with the given parameters.

        Parameters are described above in :meth:`create`, with
        the exception that `iso_country` cannot be updated on
        an existing Address (create a new one instead).
        """
        if 'iso_country' in kwargs:
            raise TwilioException(
                "Cannot update iso_country on an existing Address", )

        return self.update_instance(sid, kwargs)
Beispiel #7
0
 def request(self,
             method,
             url,
             params=None,
             data=None,
             headers=None,
             auth=None,
             timeout=None,
             allow_redirects=False):
     """
     Make an HTTP request.
     """
     raise TwilioException('HttpClient is an abstract class')
Beispiel #8
0
    def load_page(self, payload):
        """
        Parses the collection of records out of a list payload.

        :param dict payload: The JSON-loaded content.
        :return list: The list of records.
        """
        if 'meta' in payload and 'key' in payload['meta']:
            return payload[payload['meta']['key']]
        else:
            keys = set(payload.keys())
            key = keys - self.META_KEYS
            if len(key) == 1:
                return payload[key.pop()]

        raise TwilioException('Page Records can not be deserialized')
    def test_send_sms_fail(self, fake_twilio):
        # Arrange
        client = Mock()
        client.messages.create.side_effect = TwilioException('Boom!')
        fake_twilio.return_value = client

        # Act
        response = self.client.post(
            reverse('sample_app:send_sms'),
            json.dumps({
                'body': 'Test Message',
                'to': '11111'
            }),
            content_type='application/json',
        )

        # Assert
        self.assertEqual(response.status_code, 500)
        self.assertIn(b'Failed to send SMS', response.content)
Beispiel #10
0
    def get_page(self, target_url):
        """
        Retrieve a specific page of TaskQueueInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of TaskQueueInstance
        :rtype: twilio.rest.taskrouter.v1.workspace.task_queue.TaskQueuePage
        """
        resource_url = self._version.absolute_url(self._uri)
        if not target_url.startswith(resource_url):
            raise TwilioException('Invalid target_url for TaskQueueInstance resource.')

        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return TaskQueuePage(self._version, response, self._solution)
Beispiel #11
0
    def get_page(self, target_url):
        """
        Retrieve a specific page of PhoneNumberInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of PhoneNumberInstance
        :rtype: twilio.rest.preview.proxy.service.phone_number.PhoneNumberPage
        """
        resource_url = self._version.absolute_url(self._uri)
        if not target_url.startswith(resource_url):
            raise TwilioException('Invalid target_url for PhoneNumberInstance resource.')

        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return PhoneNumberPage(self._version, response, self._solution)
Beispiel #12
0
    def get_page(self, target_url):
        """
        Retrieve a specific page of DomainInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of DomainInstance
        :rtype: twilio.rest.api.v2010.account.sip.domain.DomainPage
        """
        resource_url = self._version.absolute_url(self._uri)
        if not target_url.startswith(resource_url):
            raise TwilioException('Invalid target_url for DomainInstance resource.')

        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return DomainPage(self._version, response, self._solution)
Beispiel #13
0
    def get_page(self, target_url):
        """
        Retrieve a specific page of ShortCodeInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of ShortCodeInstance
        :rtype: twilio.rest.messaging.v1.service.short_code.ShortCodePage
        """
        resource_url = self._version.absolute_url(self._uri)
        if not target_url.startswith(resource_url):
            raise TwilioException('Invalid target_url for ShortCodeInstance resource.')

        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return ShortCodePage(self._version, response, self._solution)
Beispiel #14
0
    def get_page(self, target_url):
        """
        Retrieve a specific page of CredentialListInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of CredentialListInstance
        :rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialListPage
        """
        resource_url = self._version.absolute_url(self._uri)
        if not target_url.startswith(resource_url):
            raise TwilioException('Invalid target_url for CredentialListInstance resource.')

        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return CredentialListPage(self._version, response, self._solution)
Beispiel #15
0
    def get_page(self, target_url):
        """
        Retrieve a specific page of AvailableAddOnInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of AvailableAddOnInstance
        :rtype: twilio.rest.preview.marketplace.available_add_on.AvailableAddOnPage
        """
        resource_url = self._version.absolute_url(self._uri)
        if not target_url.startswith(resource_url):
            raise TwilioException(
                'Invalid target_url for AvailableAddOnInstance resource.')

        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return AvailableAddOnPage(self._version, response, self._solution)
    def get_page(self, target_url):
        """
        Retrieve a specific page of UserChannelInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of UserChannelInstance
        :rtype: twilio.rest.chat.v2.service.user.user_channel.UserChannelPage
        """
        resource_url = self._version.absolute_url(self._uri)
        if not target_url.startswith(resource_url):
            raise TwilioException(
                'Invalid target_url for UserChannelInstance resource.')

        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return UserChannelPage(self._version, response, self._solution)
Beispiel #17
0
    def get_page(self, target_url):
        """
        Retrieve a specific page of AssignedAddOnExtensionInstance records from the API.
        Request is executed immediately

        :param str target_url: API-generated URL for the requested results page

        :returns: Page of AssignedAddOnExtensionInstance
        :rtype: twilio.rest.api.v2010.account.incoming_phone_number.assigned_add_on.assigned_add_on_extension.AssignedAddOnExtensionPage
        """
        resource_url = self._version.absolute_url(self._uri)
        if not target_url.startswith(resource_url):
            raise TwilioException(
                'Invalid target_url for AssignedAddOnExtensionInstance resource.'
            )

        response = self._version.domain.twilio.request(
            'GET',
            target_url,
        )

        return AssignedAddOnExtensionPage(self._version, response,
                                          self._solution)
    def test_send_sms_invalid_number(self, fake_twilio):
        # Arrange
        client = Mock()
        client.messages.create.side_effect = TwilioException('Boom!')
        fake_twilio.return_value = client
        timeout = 2

        # Act
        self.selenium.get(self.live_server_url)
        self._send_sms()

        WebDriverWait(
            self.selenium,
            timeout).until(lambda driver: 'alert-danger' in driver.
                           find_element_by_id('dialog').get_attribute('class'))

        # Assert
        self.assertEqual(client.messages.create.call_count, 1)
        dialog = self.selenium.find_element_by_id('dialog')
        dialog_title = self.selenium.find_element_by_id('dialogTitle')
        dialog_content = self.selenium.find_element_by_id('dialogContent')
        self.assertNotIn('d-none', dialog.get_attribute('class'))
        self.assertIn('Error', dialog_title.text)
        self.assertIn('Failed to send SMS', dialog_content.text)
Beispiel #19
0
    def __init__(self,
                 username=None,
                 password=None,
                 account_sid=None,
                 region=None,
                 http_client=None,
                 environment=None,
                 edge=None):
        """
        Initializes the Twilio Client

        :param str username: Username to authenticate with
        :param str password: Password to authenticate with
        :param str account_sid: Account SID, defaults to Username
        :param str region: Twilio Region to make requests to, defaults to 'us1' if an edge is provided
        :param HttpClient http_client: HttpClient, defaults to TwilioHttpClient
        :param dict environment: Environment to look for auth details, defaults to os.environ
        :param str edge: Twilio Edge to make requests to, defaults to None

        :returns: Twilio Client
        :rtype: twilio.rest.Client
        """
        environment = environment or os.environ

        self.username = username or environment.get('TWILIO_ACCOUNT_SID')
        """ :type : str """
        self.password = password or environment.get('TWILIO_AUTH_TOKEN')
        """ :type : str """
        self.account_sid = account_sid or self.username
        """ :type : str """
        self.edge = edge or environment.get('TWILIO_EDGE')
        """ :type : str """
        self.region = region or environment.get('TWILIO_REGION')
        """ :type : str """

        if not self.username or not self.password:
            raise TwilioException(
                "Credentials are required to create a TwilioClient")

        self.auth = (self.username, self.password)
        """ :type : tuple(str, str) """
        self.http_client = http_client or TwilioHttpClient()
        """ :type : HttpClient """

        # Domains
        self._accounts = None
        self._api = None
        self._autopilot = None
        self._chat = None
        self._conversations = None
        self._events = None
        self._fax = None
        self._flex_api = None
        self._frontline_api = None
        self._insights = None
        self._ip_messaging = None
        self._lookups = None
        self._media = None
        self._messaging = None
        self._monitor = None
        self._notify = None
        self._numbers = None
        self._preview = None
        self._pricing = None
        self._proxy = None
        self._serverless = None
        self._studio = None
        self._sync = None
        self._taskrouter = None
        self._trunking = None
        self._trusthub = None
        self._verify = None
        self._video = None
        self._voice = None
        self._wireless = None
        self._supersim = None
        self._bulkexports = None
 def get_instance(self, payload):
     raise TwilioException('Page.get_instance() must be implemented in the derived class')
 def get(self, sid):
     raise TwilioException("Individual AvailablePhoneNumbers have no sid")
    def process_response(self, response):
        if response.status_code != 200:
            raise TwilioException('Unable to fetch page', response)

        return json.loads(response.content)